0

I have a query regarding fragment. Scenario is: After I login, I am on an actiivity which have 3 fragments. For fragments I have used ViewPager. Now I have to use login username in one of my fragment. I have bought username from login page using putExtra. My query is how take that username to the fragments ??

5
  • 1
    put them in bundle and pass them to your fragment. I recommend you to use shared-preference for this . Commented Sep 28, 2016 at 10:53
  • Why are you not using shared preference for this ? Commented Sep 28, 2016 at 10:58
  • You are right. Can be done from that also but I did bundle thing but got null pointer exception in fragment. Any idea!! Commented Sep 28, 2016 at 11:12
  • Dont know how to use shared preference. Commented Sep 28, 2016 at 11:13
  • 1
    It will be helpful if you share code snippet Commented Sep 28, 2016 at 11:29

3 Answers 3

1

From your BaseActivity send data with intent :

Bundle bundle = new Bundle(); bundle.putString("username", "From your BaseActivity"); // set Fragmentclass Arguments Fragmentclass fragmentclass = new Fragmentclass(); fragmentclass .setArguments(bundle); 

And in your Fragment onCreatView method :

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String username= getArguments().getString("username"); return inflater.inflate(R.layout.yourFragment, container, false); } 
Sign up to request clarification or add additional context in comments.

2 Comments

It shows null pointer Exception in the fragment at line where we are storing value in String.
@ArmanReyaz you should set the bundle before adding the fragment to your Activity
1

You can also use SharedPreferences. Store the username or what so ever you want to save in SharedPreferences and use it anywhere in your app. For your reference SharedPreferences Tutorials

Comments

0

From your activity you can send data with intent:

Bundle bundle = new Bundle(); bundle.putString("username", "abcd"); // set Fragmentclass Arguments FragmentClass frag_one = new Fragmentclass(); frag_one.setArguments(bundle); 

and add below code in Fragment onCreateView method:

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String strtext = getArguments().getString("username"); return inflater.inflate(R.layout.fragment_layout, container, false); } 

2 Comments

It shows null pointer Exception in the fragment at line where we are storing value in String.
@ArmanReyaz Can you try String strtext = this.getArguments().getString("username");

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.