Array List of objects via intent

This is an example. MainActivity sends list of persons to OtherActivity via Intent.

class Person implements Serializable {
    int id;
    String name;

    Person(int i, String s) {
        id = i;
        name = s;
    }
}

public class TestAndroidActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ArrayList<Person> list = new ArrayList<Person>();
        list.add(new Person(1, "Tom"));
        list.add(new Person(5, "John"));

        Intent intent = new Intent(this, OtherActitity.class);
        intent.putExtra("list", list);
        startActivity(intent);

OtherActivity.java

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class OtherActitity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other);

        Intent i = getIntent();
        ArrayList<Person> list = (ArrayList<Person>) i
                .getSerializableExtra("list");
        Toast.makeText(this, list.get(1).name, Toast.LENGTH_LONG).show();

    }
}

You can make your objects implement Parcelable and use putParcelableArrayListExtra. Alternatively, you can serialize your objects in some way and put the byte array of your serialized objects.


One more way - you can serialize list of objects into some kind of string representation (let it be JSON) and then retrieve the string value back to list

// here we use GSON to serialize mMyObjectList and pass it throught intent to second Activity
String listSerializedToJson = new Gson().toJson(mMyObjectList);
intent.putExtra("LIST_OF_OBJECTS", listSerializedToJson);
startActivity(intent);

// in second Activity we get intent and retrieve the string value (listSerializedToJson) back to list 
String listSerializedToJson = getIntent().getExtras().getString("LIST_OF_OBJECTS");
mMyObjectList = new Gson().fromJson(objectsInJson, MyObject[].class); // in this example we have array but you can easy convert it to list - new ArrayList<MyObject>(Arrays.asList(mMyObjectList)); 

Tags:

Java

Android