47

I want to pass a list of objects from one activity from another activity. I have one class SharedBooking Below:

public class SharedBooking {
  public int account_id;
  public Double betrag;
  public Double betrag_effected;
  public int taxType;
  public int tax;
  public String postingText;
}

Code from Calling activity:

public List<SharedBooking> SharedBookingList = new ArrayList<SharedBooking>();

public void goDivision(Context context, Double betrag, List<SharedBooking> bookingList) {
  final Intent intent = new Intent(context, Division.class);    
  intent.putExtra(Constants.BETRAG, betrag);        
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  context.startActivity(intent);        
}

COde on called activity:

Bundle extras = getIntent().getExtras();
if (extras != null) {
  amount = extras.getDouble(Constants.BETRAG,0);
}

How can I send the list of SharedBooking from one activity and receive that on other activity?

Please suggest me any usable link or sample code.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Sushant Bhatnagar
  • 3,684
  • 10
  • 31
  • 42

9 Answers9

109

First, make the class of the list implement Serializable.

public class MyObject implements Serializable{}

Then you can just cast the list to (Serializable). Like so:

List<MyObject> list = new ArrayList<>();
myIntent.putExtra("LIST", (Serializable) list);

And to retrieve the list you do:

Intent i = getIntent();
list = (List<MyObject>) i.getSerializableExtra("LIST");

That's it.

Ruzin
  • 1,645
  • 2
  • 14
  • 14
53

Use parcelable. Here is how you will do it:

public class SharedBooking implements Parcelable{

    public int account_id;
    public Double betrag;
    public Double betrag_effected;
    public int taxType;
    public int tax;
    public String postingText;

    public SharedBooking() {
        account_id = 0;
        betrag = 0.0;
        betrag_effected = 0.0;
        taxType = 0;
        tax = 0;
        postingText = "";
    }

    public SharedBooking(Parcel in) {
        account_id = in.readInt();
        betrag = in.readDouble();
        betrag_effected = in.readDouble();
        taxType = in.readInt();
        tax = in.readInt();
        postingText = in.readString();
    }

    public int getAccount_id() {
        return account_id;
    }
    public void setAccount_id(int account_id) {
        this.account_id = account_id;
    }
    public Double getBetrag() {
        return betrag;
    }
    public void setBetrag(Double betrag) {
        this.betrag = betrag;
    }
    public Double getBetrag_effected() {
        return betrag_effected;
    }
    public void setBetrag_effected(Double betrag_effected) {
        this.betrag_effected = betrag_effected;
    }
    public int getTaxType() {
        return taxType;
    }
    public void setTaxType(int taxType) {
        this.taxType = taxType;
    }
    public int getTax() {
        return tax;
    }
    public void setTax(int tax) {
        this.tax = tax;
    }
    public String getPostingText() {
        return postingText;
    }
    public void setPostingText(String postingText) {
        this.postingText = postingText;
    }
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(account_id);
        dest.writeDouble(betrag);
        dest.writeDouble(betrag_effected);
        dest.writeInt(taxType);
        dest.writeInt(tax);
        dest.writeString(postingText);

    }

    public static final Parcelable.Creator<SharedBooking> CREATOR = new Parcelable.Creator<SharedBooking>()
    {
        public SharedBooking createFromParcel(Parcel in)
        {
            return new SharedBooking(in);
        }
        public SharedBooking[] newArray(int size)
        {
            return new SharedBooking[size];
        }
    };

}

Passing the data:

Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("data", sharedBookingObject);
intent.putExtras(bundle);
startActivity(intent);

Retrieving the data:

Bundle bundle = getIntent().getExtras();
sharedBookingObject = bundle.getParcelable("data");
Vineet Shukla
  • 23,865
  • 10
  • 55
  • 63
  • 2
    Excellent answer! Will use this as example for my own app. – Qw4z1 Aug 23 '12 at 13:42
  • Thanks , good answer , i have modified my code but i need to pass list of sharedBooking class , not a single objects , then please explain me how i pass list of object ? – Sushant Bhatnagar Aug 23 '12 at 13:46
  • 14
    you can use bundle.putParcelableArrayList(key, value) to set the and bundle.getParcelableArrayList(key) to get the list. – Vineet Shukla Aug 23 '12 at 13:52
  • @VineetShukla in the line: bundle.putParcelable("data", sharedBookingObject); what is sharedBookingObject ?? one object or a list of objects ????? – rainman Sep 03 '16 at 23:43
14

Parcelable object class

    public class Student implements Parcelable {

        int id;
        String name;

        public Student(int id, String name) {
            this.id = id;
            this.name = name;

        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }


        @Override
        public int describeContents() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int arg1) {
            // TODO Auto-generated method stub
            dest.writeInt(id);
            dest.writeString(name);
        }

        public Student(Parcel in) {
            id = in.readInt();
            name = in.readString();
        }

        public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
            public Student createFromParcel(Parcel in) {
                return new Student(in);
            }

            public Student[] newArray(int size) {
                return new Student[size];
            }
        };
    }

And the list

ArrayList<Student> arraylist = new ArrayList<Student>();

Code from Calling activity

Intent intent = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", arraylist);
intent.putExtras(bundle);       
this.startActivity(intent);

Code on called activity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);   

    Bundle bundle = getIntent().getExtras();
    ArrayList<Student> arraylist = bundle.getParcelableArrayList("mylist");
}
Shahin ShamS
  • 498
  • 5
  • 7
2

You may want to implement the Parcelable Interface in your SharedBooking class and add them to the Intent i.e. with the putParcelableArrayListExtra Method. Check the documentation.

cyborg86pl
  • 2,597
  • 2
  • 26
  • 43
Hans Hohenfeld
  • 1,729
  • 11
  • 14
  • 1
    i have modified the class :- public class SharedBooking implements Parcelable and implement its unimplement methods , but i send this using intent.putParcelableArrayListExtra(Constants.BOOKING_LIST, bookingList); where bookingList is ArrayList extends Parcelable> . But how i declare this list in any activity and how i add an object in this activity . – Sushant Bhatnagar Aug 23 '12 at 13:39
2

A simpler way would be to convert the list to a String using Gson, then pass it like so:

String yourListAsString = new Gson().toJson(yourList);
bundle.putString("data",yourListAsString);

Then retrieve it back using your class as the type:

List<YourList> listName = new Gson().fromJson("data", new TypeToken<List<YourList>>(){}.getType());
Oush
  • 3,090
  • 23
  • 22
0

there are 2 ways to send an arraylist of objects or an object from one activity to another:

  1. Parcelable
  2. Searializable
0

If there is someone who is looking for answer this is how i implemented it using Kotlin.

Parcelable object class

data class CollectedMilk(
    @SerializedName("id")
    var id: Int,
    @SerializedName("igicuba")
    var igicuba: Int,
    @SerializedName("collector")
    var collector: String?,
    @SerializedName("collected")
    var collected: Int,
    @SerializedName("accepted")
    var accepted: Int,
    @SerializedName("standard")
    var standard: String?,
    @SerializedName("created_at")
    var created_at: String?,
    @SerializedName("updated_at")
    var updated_at: String?,
): Parcelable {

    constructor(parcel: Parcel) : this(
        parcel.readInt(),
        parcel.readInt(),
        parcel.readString(),
        parcel.readInt(),
        parcel.readInt(),
        parcel.readString(),
        parcel.readString(),
        parcel.readString()
    )

    override fun describeContents(): Int {
        return 0
    }

    override fun writeToParcel(parcel: Parcel?, int: Int) {
        parcel?.writeInt(id)
        parcel?.writeInt(igicuba)
        parcel?.writeString(collector)
        parcel?.writeInt(collected)
        parcel?.writeInt(accepted)
        parcel?.writeString(standard)
        parcel?.writeString(created_at)
        parcel?.writeString(updated_at)
    }

    companion object CREATOR : Parcelable.Creator<CollectedMilk> {
        override fun createFromParcel(parcel: Parcel): CollectedMilk {
            return CollectedMilk(parcel)
        }

        override fun newArray(size: Int): Array<CollectedMilk?> {
            return arrayOfNulls(size)
        }
    }
}

Then in Fragment

collectedMilkAdapter.onItemClick = { collectedMilk ->
            Toast.makeText(
                MccApp.applicationContext(),
                "Collector: " + collectedMilk.collector,
                Toast.LENGTH_LONG
            ).show()

            val intent = Intent(MccApp.applicationContext(), CollectedMilkActivity::class.java)
            val bundle: Bundle = Bundle()

            bundle.putParcelableArrayList("collectedMilk", collectedMilkArrayList)
            intent.putExtras(bundle)

            activity?.startActivity(intent)
        }

Then on another Activity my Detail Activity

Global Variable

private lateinit var collectedMilk: ArrayList<CollectedMilk>

In Function or OnCreate Activity

val bundle = intent.extras
        collectedMilk = (bundle?.getParcelableArrayList<CollectedMilk>("collectedMilk") as ArrayList<CollectedMilk>)

        Toast(this).showCustomToast(
            this,
            ""+collectedMilk,
            dark
        ) 
Bercove
  • 987
  • 10
  • 18
0

Another alternative will be the use of Gson.

copy this extension to your code:

// will write a list of objects to intent
fun Intent.putExtra(name: String, objs: List<*>) = putExtra(name, Gson().toJson(objs))

// will read a list of objects from intent
inline fun <reified T> Intent.getObjListExtra(name: String): List<T>? {
    val lstStr = getStringExtra(name) ?: return null
    val lst = Gson().fromJson<List<T>>(lstStr, object: ParameterizedType {
        override fun getActualTypeArguments(): Array<Type> = arrayOf(T::class.java)
        override fun getRawType(): Type = List::class.java
        override fun getOwnerType(): Type = T::class.java
    })
    return lst
}

and use them:

Activity 1:

startActivity(Intent(this, Activity2::class.java).also {
   val people = listOf(Person("Moishe"), Person("Albert"), Person("Lezly"))
   it.putExtra("people", people)
 })

Activity 2:

val people = intent.getObjExtra<Person>("Person")

This solution aim to use Gson as the parser

Oz Shabat
  • 1,434
  • 17
  • 16
0

Kotlin

First, make the class of the list implement Serializable.

class MyObject: Serializable{}

Then you can just cast the list to (Serializable). Like so:

val list: List<MyObject> = mutableListOf<MyObject>();
myIntent.putExtra("LIST", list as Serializable);

And to retrieve the list you do:

val mlist = intent.getSerializableExtra("LIST") as? List<ModuleDataRow>

That's it.

Jithin Jude
  • 840
  • 14
  • 19