22

I know you can pass in an array list of String via intent, but what if it's an array list of some object that I defined? Say an array list of Bicyles, how do I do this?

0

4 Answers 4

24

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. However, while Serializable is easier to implement, it does not perform as well at run time--requiring all objects to be converted to byte streams and generating lots of temporary objects.

There are a lot of examples of how to implement Parcelable, including several in this thread. If you're using Kotlin, the easiest is to use the kotlin-parcelize plugin. First, add the following to your module's build.gradle file:

plugins {
    id 'kotlin-parcelize'
}

Then, make your Bicycle class parcelable:

import kotlinx.parcelize.Parcelize

@Parcelize
class Bicycle(val id: Int, val brand: String): Parcelable

Now you can pass an array list of Bicycle via an intent using putParcelableArrayListExtra:

var bicycles : MutableList<Bicycle> = ...

...

intent.putParcelableArrayListExtra("bicycles",
    bicycles as java.util.ArrayList<out Parcelable>
)

The receiving activity can retrieve the bicycles like this:

var bicycles : List<Bicycle>

list=intent.getParcelableArrayListExtra("bicycles")

If you're targeting API level 33 or later, you can use:

list=intent.getParcelableArrayListExtra("bicycles", Bicycle)

which has better type safety.

Sign up to request clarification or add additional context in comments.

8 Comments

@adit - For a code example of making something Parcelable, look at the docs for Parcelable. Then you can use an ArrayList<MyParcelableClass> in a call to putParcelableArrayListExtra().
having issues as my object has a Location object, so don't really know on how to handle this in the writeToParcel method
@adit - Location implements Parcelable itself, so in your writeToParcel method, you can just use Parcel's writeParcelable to write the Location along with the rest of your data.
please put examples not suggestions
This is not a solution! This is just a regular, completely unusefull, "bla-bla-bla" answer. The only solution is: wannik's answer!
|
24

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();

    }
}

5 Comments

Note that using Serializable for this involves a performance penalty, so you actually should use Parcelable.
intent.putExtra("list", list); gives me an error : cannot resolve method
Thank you for the answer it helped me solve the problem. I have one question. When I create a List<Person> list = new ArrayList<>(); object, it gave me error. But Creating a ArrayList<Person> list = new ArrayList<>(); object didn't give any error. What is the difference.
@viper Maybe you forgot to import java.util.List;
Note that you MUST pass an ArrayList and not a List otherwise it will show an error: Cannot resolve method putExtra
9

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)); 

Comments

7

A better idea is to implement Parcelable interface for the object whose arraylist you want to put in the Intent .For Example :

public class Person implements Parcelable{

    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public int describeContents() {
        return this.hashCode();
    }
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
    }
}

And then application code you can say :

bundle.putParcelableArrayList("personList", personList);

1 Comment

That's what the first answer says.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.