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 ??
Asked
Active
Viewed 622 times
0
-
1put them in bundle and pass them to your fragment. I recommend you to use shared-preference for this . – Nouman Ghaffar Sep 28 '16 at 10:53
-
Why are you not using shared preference for this ? – Somesh Kumar Sep 28 '16 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 Sep 28 '16 at 11:12
-
Dont know how to use shared preference. – Arman Reyaz Sep 28 '16 at 11:13
-
1It will be helpful if you share code snippet – Himanshu Dudhat Sep 28 '16 at 11:29
3 Answers
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);
}

BOUTERBIAT Oualid
- 1,494
- 13
- 15
-
It shows null pointer Exception in the fragment at line where we are storing value in String. – Arman Reyaz Sep 28 '16 at 11:10
-
@ArmanReyaz you should set the bundle before adding the fragment to your Activity – BOUTERBIAT Oualid Sep 28 '16 at 12:29
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

Rahul Sharma
- 2,867
- 2
- 27
- 40
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);
}

Jaydroid
- 334
- 3
- 13
-
It shows null pointer Exception in the fragment at line where we are storing value in String. – Arman Reyaz Sep 28 '16 at 11:10
-
@ArmanReyaz Can you try String strtext = this.getArguments().getString("username"); – Jaydroid Sep 28 '16 at 11:36