9

Am working in a project with an Activity that host many fragments. Now I need to share some data (integers, strings, arraylist) between these fragments.

First time i used static fields but I think it's a bad way then I found this solution.

but in my case there is no button to click i have just to navigate between fragments is there any simple way to make sharing data between fragments

Community
  • 1
  • 1
Soufiane
  • 368
  • 1
  • 3
  • 14
  • If you just view the data without any user-interaction (no button to click, listview selection to make, ...) why do you need to pass data from the view-only-fragment to an other fragment? – k3b Jul 12 '16 at 14:46
  • in the first fragment i make many traitements; the same traitements are needed in the others so i don t want to repeat them again to reduice the compexity and use of time – Soufiane Jul 12 '16 at 14:52

7 Answers7

8

I think the best solution for you is to have the variables inside the main activity and access them from fragments. I mean, if you have to do THE SAME in all fragments, you can write the code inside the activity and just call the method you need.

You need to use an interface for this purpose

public interface DataCommunication {
    public String getMyVariableX();
    public void setMyVariableX(String x);
    public int getMyVariableY();
    public void setMyVariableY(int y);
}

Then, implement it inside your activity

public class MainActivity extends Activity implements DataCommunication {

    private String x;
    private int y;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...   
    }

    ...

    @Override
    public String getMyVariableX(){
        return x;
    }

    @Override
    public void setMyVariableX(String x){
        //do whatever or just set
        this.x = x;
    }

    @Override
    public int getMyVariableY(){
        return y;
    }

    @Override
    public void setMyVariableY(int y){
        //do whatever or just set
        this.y = y;
    }

    ...

Then, attach the activity in ALL your fragments:

public class Fragment_1 extends Fragment{

    DataCommunication mCallback;

 @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (DataCommunication) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement DataCommunication");
        }
    }

    ...

And finally, when you need to use a variable inside a fragment, just use get and se methods you've created

https://developer.android.com/training/basics/fragments/communicating.html

adalpari
  • 3,052
  • 20
  • 39
7

The easiest way to do this is to use Bundle. You do something like this:

Fragment A:

Bundle b = new Bundle();
b.putString("Key", "YourValue");
b.putInt("YourKey", 1);

FragmentB fragB = new FragmentB();
fragB.setArguments(b); 
getFragmentManager().beginTransaction().replace(R.id.your_container, fragB);

Fragment B:

Bundle b = this.getArguments();
if(b != null){
   int i = b.getInt("YourKey");
   String s =b.getString("Key");
}

This is the easiest way that I have found to send data from one fragment to another. Hope it helps someone.

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
3

You have some options:

Options 1: If you need to share information between fragments, you can use the SharedPreferences to store the information. This is an example:

SharedPreferences settings = context.getSharedPreferences("Preferences", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("string1", var);
    editor.putBoolean("bool1", var);
    ...
    editor.commit();

Option 2: If you have instantiated a fragment, you can create a set method to store some kind of information in the fragment. For example, if you want to pass an array of string, you can create an array variable in the fragment (with setter method). Later, when you have instantiated this fragment, you can use the setter method to pass this array to the fragment.

cNgamba
  • 111
  • 1
  • 10
JUANM4
  • 344
  • 2
  • 5
1

You can create a Application class ( i mean extend Application ) then take some variable what you need , make getter and setter method. set value to variable and get value when and where you need. if you wish i can give you some demo code for it .

Osman Goni Nahid
  • 1,193
  • 2
  • 15
  • 24
0

We can share the Data between fragments in 2 ways.

  1. By Using Bundle

  2. By using Persistence Storage

By Using Bundle:-

Bundle bundle=new Bundle();
bundle.putString("firstName",Fist);
bundle.putString("LastName",lastN);

Second Persistence Storage :- this you can check how to store Data in Persistence Storage. Hope it will work for you

Pradeep Sheoran
  • 493
  • 6
  • 15
0

Use a SharedViewModel proposed at the official ViewModel documentation

First implement fragment-ktx to instantiate your viewmodel more easily

dependencies {
implementation "androidx.fragment:fragment-ktx:1.2.2"
}

Then, you just need to put inside the viewmodel the data you will be sharing with the other fragment

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

Then, to finish up, just instantiate your viewModel in each fragment, and set the value of selected from the fragment you want to set the data

Fragment A

class MasterFragment : Fragment() {

    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        itemSelector.setOnClickListener { item ->
        model.select(item)
      }

    }
}

And then, just listen for this value at your Fragment destination

Fragment B

class DetailFragment : Fragment() {

        private val model: SharedViewModel by activityViewModels()

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
                // Update the UI
            })
        }
    }

This answer can help you, https://stackoverflow.com/a/60696777/6761436

Zeeshan Ayaz
  • 858
  • 6
  • 11
-1

1.Use BroadCastReceiver (a little complicated)

2.Use SharePreference

3.save data into MyApplication extends Application

Cgx
  • 753
  • 3
  • 6