6

I want to transfer the user ID from the main Activity to a fragment.

So in the main activity, I do:

 Fragment fragment = new Fragment();
 final Bundle bundle = new Bundle();
 bundle.putString("id_User", id);
 Log.i("BUNDLE", bundle.toString());
 fragment.setArguments(bundle); 

And in the log I can see

BUNDLE : Bundle[{id_User=1}]

In the fragment, I test it in onCreate

Bundle arguments = getArguments();
if (arguments != null)
{
Log.i("BUNDLE != null","NO NULL");
} else {
Log.i("BUNDLE == null","NULL");
}

And I have

BUNDLE == null: NULL

So the transfer is successful, but how can I receive the data in fragment, please?

Steve
  • 9,270
  • 5
  • 47
  • 61

2 Answers2

11

You can use:

 Bundle args = getArguments();
 if (args  != null && args.containsKey("id_User"))
     String userId = args.getString("id_User");
Szymon
  • 42,577
  • 16
  • 96
  • 114
  • what should i do if i have to retrieve data in user defined method not in oncreate method. – Android Learner Feb 14 '14 at 12:51
  • @AndroidLearner It would be better if you posted a separate question with a proper description of your problem. Provide your code and me or someone else will be able to help you. – Szymon Feb 14 '14 at 12:58
  • @AndroidLearner Did you solved your problem? i have such a problem :/ – Dr.jacky Jul 22 '14 at 14:47
  • @Szymon : Can we pass data between two fragments without an activity? I have parent fragment in which there are two child fragments and i need to pass data between two child fragments. – Siddharth_Vyas Dec 15 '14 at 11:27
2

Just use:

String User = getArguments().getString("id_User", "Default Value");

The default value you supply will be returned if the key you request does not exist.

Kuffs
  • 35,581
  • 10
  • 79
  • 92