user2815087
user2815087

Reputation: 27

Android: pass a value from container Activity to its fragment

My code contains a main Activity and three fragments inside it and I want to pass a value from the container activity to its fragment, but it's not working.
I tried to make an interface to communicate to each other but nothing happened.
I also tried to make a bundle but I have an error in setArguments.

Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

and in the fragment

Bundle bundle = this.getArguments();
if(bundle != null){
    int i = bundle.getInt(key, defaulValue);
}

Can you please help me? Thank you!

Upvotes: 2

Views: 1284

Answers (1)

Adrien Cerdan
Adrien Cerdan

Reputation: 1015

Try with an Intent in your activity :

Intent a = new Intent (this, yourfragment.class);
a.putInt(key, value);
setIntent(a);

And in your fragment :

ActivityName activity = (ActivityName) getActivity();
Intent b= activity.getIntent();    
int Uid = b.getIntExtra(key);

Upvotes: 3

Related Questions