java – Save/Send ArrayList info of objects in Intent to Activity

Question:

I would like to know if there is any way to store data as an ArrayList for a multi-activity app, I move through several activities and back from one to another, I handle several ArrayList and I would like to know if I can store those ArrayLists without constantly passing them with Bundles and Intents between activities.

Answer:

You can do it by 2 methods:

Send ArrayList between Activities.

But definitely the ideal way is to send the data between Activities through the bundle .

Where your object must implement the Serializable or Parcelable class:

public class Dato implements Serializable {

You would send an ArrayList of objects in the Intent via .putExtra() :

   Intent intent = new Intent(MainActivity.this, SegundaActivity.class);
                intent.putExtra("listaDatos", listaDatos);
                startActivity(intent);

To receive the ArrayList in the destination Activity, it is done in this way:

ArrayList<tipoObjeto> listaDatos = (ArrayList<tipoObjeto> ) getIntent().getSerializableExtra("listaDatos");

Save ArrayList in preferences.

You can store the data in a HashSet

SharedPreferences settings = context.getSharedPreferences( "mispreferencias", MODE_PRIVATE);
    SharedPreferences.Editor editor;
    editor = settings.edit();
    Set<String> set = new HashSet<String>();
    set.addAll(listaDatos);
    editor.putStringSet("key", set);
    editor.commit();

and get them like this:

SharedPreferences preferences = context.getSharedPreferences("mispreferencias", MODE_PRIVATE);
Set<String> set = preferences.getStringSet("key", null);
Scroll to Top