Retrieve data from a Fragment from another Fragment

1

Let's say I have a Activity called MainActivity

that has three Fragments

  

F1, F2 and F3

These three'Fragments' are loaded from the MainActivity in the following way:

 public void initFragments(){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        fragmentTransaction.add(R.id.fraOrderDetailsOrderWorkActivity,
                F1);
        fragmentTransaction.add(R.id.fraOrderDetailsOrderWorkActivity,
                F2);
        fragmentTransaction.add(R.id.fraOrderDetailsOrderWorkActivity,
               F3);
        fragmentTransaction.commit();
        hideAllFragments();
    }

I have three buttons

  

B1, B2 and B3

Clicking any of these buttons opens each of the fragments, that is, the B1 button opens the fragment F1, B2 opens the F2 ....

Suppose that the user clicks on B1 and fill in a series of data in the Fragment F1, say a surname and a name, then click on B2 and fill in other data in Fragment F2 .... My question is: when the user clicks on button B3 and the Fragment F3 opens From the F3 how can I check the name and surname written in Fragment F1?

    
asked by JoCuTo 15.03.2018 в 16:22
source

1 answer

0

A serious way by using SharedPreferences , in which you can save information locally as if you were creating a SQL database but in a simpler way.

Example

Suppose that in the Fragment1 you need to take the information that receives a EditText , to save it do the following:

Context context = getActivity();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Mis_preferences",context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("nombre_dato", valor);
editor.apply();

Then, in the Fragment3 you can retrieve that information as follows:

Context context = getActivity();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Mis_preferences",context.MODE_PRIVATE);
String dato = sharedPreferences.getString("nombre_dato","No hay dato");//"No hay dato" es el valor por defecto que mostrara si no se encuentra el dato guardado
    
answered by 15.03.2018 в 16:46