Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array List of objects via intent

Tags:

java

android

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?

like image 278
adit Avatar asked Nov 13 '11 05:11

adit


People also ask

How can we send ArrayList from activity to fragment?

Intent intent = new Intent(getActivity(), StudentResult. class); intent. putExtra("ExtraData", allStudents); startActivity(intent); and in target class to show the objects in ListView();

Can I pass an object in intent Android?

One option could be letting your custom class implement the Serializable interface and then you can pass object instances in the intent extra using the putExtra(Serializable..) variant of the Intent#putExtra() method.


2 Answers

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.

like image 194
Ted Hopp Avatar answered Sep 29 '22 15:09

Ted Hopp


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

    }
}
like image 23
wannik Avatar answered Sep 29 '22 13:09

wannik