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?
You can use:
Bundle args = getArguments();
if (args != null && args.containsKey("id_User"))
String userId = args.getString("id_User");
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.
Related
I am trying to get bundle extras from activity 1 to fragment of activity 2 but getargument() always returns as null.
//Using this to get string in fragment
String value = getArguments().getString("abc");
//activity1 code that i used to get the extras
Bundle bundle = new Bundle();
bundle.putString("abc", townextra);
UserFragment myFrag = new UserFragment();
myFrag.setArguments(bundle);
There is a problem with logic of passing data.
Correct way would be: Pass data from Activity1 to Activity2, and then from Activity2 to Fragment.
all fixed. I added a new function on my activity 2 to create fragment. instead of doing it in oncreat. it all works fine, thanks
Your Activity
Bundle bundle = new Bundle();
bundle.putString("params", "Your String data");
// set MyFragment Arguments
MyFragment myObj = new MyFragment();
myObj.setArguments(bundle);
The Fragment.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam = getArguments().getString("params");
}
}
But will be better if you show the code how you pass data between activities and then use my answer.
And please add your fragment code.
I am passing data from an activity to fragment by using following code.
Bundle bundle= new Bundle();
bundle.putString("seatId", seatId);
fragment.setArguments(bundle);
Then I consume the data by using following code in my fragment.
Bundle args = getArguments();
if(args!=null && args.getString("seatId")!=null){
matchId = args.getString("seatId", "");
}
Now after this I want to set bundle to null.
The issue is once I set data to fragment through bundle, it keeps it there.
Get hold of the bundle or simply getArguments().clear() as stated here.
i want to send multiple bundles from activity to fragment, the problem i'm facing here is bundle 2 get the reference of bundle 1, how to differentiate both the bundles. please provide me some suggestion.
Here is what i pass from activity to fragment,
FeatureTab featureTab = new FeatureTab();
featureTab.setArguments(bundle_DescriptioneTab);
featureTab.setArguments(bundle_User_Review);
fragmentTransaction.replace(R.id.tabcontainer, featureTab, "FeatureTab");
fragmentTransaction.commit();
Here is what i used in fragments to get the bundle,
Bundle 1 :
private void setDescription() {
try {
Bundle bundle = getArguments();
txt_Description.setText(bundle.getString("long_description"));
} catch (NullPointerException e) {
AppUtils.logError(TAG, "NullPointerException");
}
}
Bundle 2:
private void getUserReviewsParcel() {
try {
Bundle bundle = this.getArguments();
UserReviewsParcel userReviewsParcel = bundle.getParcelable("user_reviews");
List<UserReviewsBean> list = userReviewsParcel.getparcelList();
// set the listview adapter
setListviewAdapter(list);
} catch (NullPointerException e) {
AppUtils.logError(TAG, "NullPointerException");
}
}
i'm calling both the methods in onCreateView.
How to send multiple bundles from activity to fragment
Use Bundle.putBundle(KEY,VALUE) to prepare a bundle which contains other bundles and you can access using keys:
Bundle bundle=new Bundle();
bundle.putBundle("bundle_DescriptioneTab",bundle_DescriptioneTab);
bundle.putBundle("bundle_User_Review",bundle_User_Review);
Pass bundle to setArguments method and you can access both Bundle using bundle_DescriptioneTab and bundle_User_Review keys.
Here's my code in
MainActivity.java
ViewFragment fr = new ViewFragment();
Bundle bundle = new Bundle();
String val="sonali";
bundle.putString("myname", val);
fr.setArguments(bundle);
return fr;
In my ViewFragment.java the code for retrieving data in onActivityCreated() is..
Bundle bundle = getArguments();
String val = bundle.getString("myname");
if (val == null) {
Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "text " + val , Toast.LENGTH_LONG).show();
}
It gives null. Can any one help me.
a) Activity -> Fragment
In your activity : create a bundle and use
fragment.setArguments(bundle)
in your fragment : use
Bundle bundle = getArguments()
2) fragment -> Activity
In your fragment : create un interface with getter and setter methods (callback methods)
In your activity : implement the interface
3) fragment -> Activity
In your activity : Create public getter and setter or other methods
In your fragment : called public activity getter, setter or other methods using :
getActivity().getSomething(), getActivity().setSomething(args) or getActivity().someMethod(args)
4) activity -> fragment
In your fragment : create a public method
In your activity : call an active fragment public method :
getSupportFragmentManager().findFragmentById(R.id.your_fragment).publicMethod(args)
You can also set a new instance metho for your fragment (I think it's the easiest way) and things as user name can be saved in usersettings (SharedPref).
static final ViewFragment newInstance(String myName) {
//TODO: Save myName
}}
I tried it & it works fine. In activity onCreate method add
Bundle bundle = new Bundle();
bundle.putString("my_key","my_value");
ViewFragment fg = new ViewFragment();
fg.setArguments(bundle);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, fg)
.commit();
}
In fragment on onActivityCreated add
Bundle bundle = getArguments();
String value = bundle.getString("my_key");
Toast.makeText(getActivity(),value,Toast.LENGTH_SHORT).show();
I'm having some problems.
In a class "A" I have the code:
Bundle extras = getIntent().getExtras();
if ( extras == null ){
Log.e("extras", "Extra NULL");
}
String arrayWatt = extras.getString("valoresWatt");
String arrayHorario = extras.getString("valoresHorario");
Bundle extras = getIntent().getExtras(); --> this is returning NULL`
This method throws NUllPointerException. What is the problem here? Syntax?
---EDIT----
So sorry, I forgot this code:
(This code is from another class that starts the activity)
Intent i = new Intent();
i.setClassName("org.me.android",
"org.me.android.GraphViewDemo");
i.putExtra("valoresWatt", watt);
i.putExtra("valoresHorario", hora);
startActivity(i);
If you want to get the extras, this is what I would do:
Intent i = getIntent();
String arrayWatt = i.getStringExtra("valoresWatt");
String arrayHorario = i.getStringExtra("valoresHorario");
Where is the code you listed for getting the Extras located? Are you overriding the onCreate method? If so, make sure you call super.onCreate(bundleVariableName) before trying to work with the Extras. So...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
// ...
Bundle data = getIntent().getExtras();
if (data != null ) {
// should actually verify that the key exists, so:
// if (data.containsKey("valoresWatt")) {
// ... do something with the value
String watt = data.getString("valoresWatt");
String horario = data.getString("valoresHorario");
}
// ...
}
In your original code, you say that this first line is returning null:
Bundle extras = getIntent().getExtras(); // --> this is returning NULL
From the Android docs for Intent, it seems that the getExtras() method will return null if no extras have been added yet.
In that case, you may have to add your String extras by calling .putExtra(key, value) on the Intent object directly, rather than on its Map of extras, which doesn't exist yet.
For the NPE crash
Bundle extras = getIntent().getExtras();
if ( extras == null ){
Log.e("extras", "Extra NULL");
} else {
String arrayWatt = extras.getString("valoresWatt");
String arrayHorario = extras.getString("valoresHorario");
}
Instead of
i.putExtra("valoresWatt", watt);
i.putExtra("valoresHorario", hora);
try
i.putStringArrayListExtra("valoresWatt", watt);
i.putStringArrayListExtra("valoresHorario", hora);
if it is an arraylist of strings.