简体   繁体   中英

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

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.

Try this code

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

使您的自定义项可分区,然后将该数组作为Parcelable数组放入Bundle中,以将其传递给活动。

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.

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

  1. Make your data parcelable as described, eg, by @takecare. See also http://developer.android.com/reference/android/os/Parcelable.html
  2. Use JSON to serialize your data. See, eg, 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, eg, Singletons vs. Application Context in Android?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM