Shoaib Ahmed
Shoaib Ahmed

Reputation: 781

How to pass array of custom type from one activity to other activity?

This is how i am passing array of custom data type Items ** Items[] itemsArr ** to intent

Intent pruchadeDetails = new Intent(getApplicationContext(),PurchaseHistoryDetails.class);
pruchadeDetails.putExtra("item",itemsArr[position].getShoppingItems());
startActivityForResult(pruchadeDetails, 0);

unable to retrive it using both methods

Item[] itemArr = (Item[])getIntent().getSerializableExtra("item"); //method 1
String json = pruchadeDetails.getStringExtra("item");//method 2

any help is highly appreciated thanks

Upvotes: 0

Views: 931

Answers (6)

Noman
Noman

Reputation: 4109

Try this code

 intent.putCharSequenceArrayListExtra("ArrayListName", ArrayList)
Intent purchaseDetails= new Intent(getApplicationContext(), this.class);
purchaseDetails.putCharSequenceArrayListExtra("items", ArrayList);
startActivityForResult(purchaseDetails,0);

Upvotes: 1

user1621629
user1621629

Reputation: 765

For First activity use below.

List<String> itemList = new ArrayList();
for(int i=0;i<5;i++){
itemList.add("i'th List"+i);
}

Intent intent= new Intent(this,ReportsActivity.class);
intent.putStringArrayListExtra("items", (ArrayList<String>) itemList);
startActivity(intent);

And get this array to another activity using

Bundle bundle = getIntent().getExtras();
    List<String> itemList= bundle.getStringArrayList("items");

    for(int i=0;i<itemList.size();i++){
       Log.i("TAG", itemList.get(i));       
    }

Upvotes: 0

Pradeep Kumar
Pradeep Kumar

Reputation: 877

Hope this code help you.

    intent.putCharSequenceArrayListExtra("ListName", ArrayList)
    Intent purchaseDetails= new Intent(getApplicationContext(), PurchaseHistoryDetails.class);
    purchaseDetails.putCharSequenceArrayListExtra("items", yourArrayList);
    startActivityForResult(purchaseDetails,0);

Pass there Array List of your Custom Data Type.

Upvotes: 1

Dan
Dan

Reputation: 1547

If you want to do this in-memory, three solutions come to my mind:

  1. Make your data parcelable as described, e.g., by @takecare. See also http://developer.android.com/reference/android/os/Parcelable.html
  2. Use JSON to serialize your data. See, e.g., http://developer.android.com/reference/org/json/JSONTokener.html
  3. Use a singleton class as a holder for your data. You can also use the application object. See, e.g., Singletons vs. Application Context in Android?

Upvotes: 0

Usama Sarwar
Usama Sarwar

Reputation: 9020

You need to have look at this

http://developer.android.com/reference/android/os/Parcelable.html

Make your Model Parcelable. An example is given in the link.

Upvotes: 0

takecare
takecare

Reputation: 1903

Make your custom item parcelable and then put the array as a Parcelable array in a Bundle, to pass it to the activity.

Upvotes: 0

Related Questions