How to put a List in intent

后端 未结 5 1907
无人共我
无人共我 2020-11-29 11:28

I have a List in one of my activities and need to pass it to the next activity.

private List selectedData;  

I tried putting

相关标签:
5条回答
  • 2020-11-29 11:57

    You have to instantiate the List to a concrete type first. List itself is an interface.

    If you implement the Parcelable interface in your object then you can use the putParcelableArrayListExtra() method to add it to the Intent.

    0 讨论(0)
  • 2020-11-29 12:02

    This is what worked for me.

    //first create the list to put objects
    private ArrayList<ItemCreate> itemsList = new ArrayList<>();
    
    //on the sender activity
         //add items to list where necessary also make sure the Class model ItemCreate implements Serializable
         itemsList.add(theInstanceOfItemCreates);
    
            Intent goToActivity = new Intent(MainActivity.this, SecondActivity.class);
                            goToActivity.putExtra("ITEMS", itemsList);
                            startActivity(goToActivity);
    
        //then on second activity
        Intent i = getIntent();
                receivedItemsList = (ArrayList<ItemCreate>) i.getSerializableExtra("ITEMS");
                Log.d("Print Items Count", receivedItemsList.size()+"");
                for (Received item:
                     receivedItemList) {
                    Log.d("Print Item name: ", item.getName() + "");
            }
    

    I hope it works for you too.

    0 讨论(0)
  • 2020-11-29 12:10

    Like howettl mentioned in a comment, if you make the object you are keeping in your list serializeable then it become very easy. Then you can put it in a Bundle which you can then put in the intent. Here is an example:

    class ExampleClass implements Serializable {
        public String toString() {
            return "I am a class";
        }
    }
    
    ... */ Where you wanna create the activity /*
    
    ExampleClass e = new ExampleClass();
    ArrayList<ExampleClass> l = new ArrayList<>();
    l.add(e);
    Intent i = new Intent();
    Bundle b = new Bundle();
    b.putSerializeable(l);
    i.putExtra("LIST", b);
    startActivity(i);
    
    0 讨论(0)
  • 2020-11-29 12:19

    i think ur item should be parcelable. and you should use arraylist instead of list. then use intent.putParcelableArrayListExtra

    0 讨论(0)
  • 2020-11-29 12:21

    Everyone says that you can use Serializable, but none mentioned that you can just cast the value to Serializable instead of list.

    intent.putExtra("selectedData", (Serializable) selectedData);
    

    Core's lists implementations already implement Serializable, so you're not bound to a specific implementation of list, but remember that you still can catch ClassCastException.

    0 讨论(0)
提交回复
热议问题