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
- 1put them in bundle and pass them to your fragment. I recommend you to use shared-preference for this .Nouman Ghaffar– Nouman Ghaffar2016-09-28 10:53:01 +00:00Commented Sep 28, 2016 at 10:53
- Why are you not using shared preference for this ?Somesh Kumar– Somesh Kumar2016-09-28 10:58:14 +00:00Commented 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!!Arman Reyaz– Arman Reyaz2016-09-28 11:12:21 +00:00Commented Sep 28, 2016 at 11:12
- Dont know how to use shared preference.Arman Reyaz– Arman Reyaz2016-09-28 11:13:50 +00:00Commented Sep 28, 2016 at 11:13
- 1It will be helpful if you share code snippetHimanshu Dudhat– Himanshu Dudhat2016-09-28 11:29:21 +00:00Commented Sep 28, 2016 at 11:29
Add a comment |
3 Answers
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); } 2 Comments
Arman Reyaz
It shows null pointer Exception in the fragment at line where we are storing value in String.
BOUTERBIAT Oualid
@ArmanReyaz you should set the bundle before adding the fragment to your Activity
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
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
Arman Reyaz
It shows null pointer Exception in the fragment at line where we are storing value in String.
Jaydroid
@ArmanReyaz Can you try String strtext = this.getArguments().getString("username");