Android Fragments bundle getArguments () returns null

1

I try to pass an arraylist (which is not empty) from one fragment to another. This is the code in which I try to pass through the arguments:

Instalaciones_fragment itf = new Instalaciones_fragment();
    Bundle bundle = new Bundle();        
    bundle.putParcelableArrayList("tipos_instalacion_array_list", arrayTiposInstalaciones);
    itf.setArguments(bundle);

    getFragmentManager().beginTransaction().replace(R.id.flContenedor, new Instalaciones_fragment()).addToBackStack(null).commit();

and this gift I try to recover it:

Bundle arguments = getArguments();
    if (arguments != null){
        arrayTiposInstalacion = arguments.getParcelableArrayList("tipos_instalacion_array_list");
    }

The problem I have is that arguments is null. Am I passing the arguments wrongly or recovering them wrong? Any solution?

Thanks in advance!

    
asked by Juan 14.05.2018 в 13:45
source

2 answers

2

The problem is that you are initializing a new Fragment after you do setArguments in an instance already created, therefore getArguments will return null in your Fragment .

You do this:

getFragmentManager().beginTransaction().replace(R.id.flContenedor, new Instalaciones_fragment()).addToBackStack(null).commit();

instead of passing itf which is the instance of your Fragment with arguments:

getFragmentManager().beginTransaction().replace(R.id.flContenedor, itf).addToBackStack(null).commit();
    
answered by 14.05.2018 / 16:42
source
0

Not long ago I was going through the same situation, I solved it by implementing Serializable to the object that I created my ArrayList:

Example:

   Instalaciones_fragment itf = new Instalaciones_fragment();
   Bundle bundle = new Bundle();
   bundle.putSerializable("keyArrayList", (Serializable) arrayList);
   itf.setArguments(bundle);     

Now to use the Serializable property you need to implement it in the class where you create your linked list.

Example:

public class Profile implements Serializable {
String first;
String second;
String phone;
String cityAddress;
String cityStreet;

public Student(String s1, String s2, String s3, String s4, String s5) {
    this.first = s1;
    this.second = s2;
    this.phone = s3;
    this.cityAddress = s4;
    this.cityStreet = s5;
}

}

Finally, you simply get the list using this code:

ArrayList<Profile> array = (ArrayList<Profile>)extras.getSerializable("keyArrayList");
    
answered by 14.05.2018 в 15:22