Help passing an ArrayList of Objects to a new Activity

前端 未结 10 2144
眼角桃花
眼角桃花 2020-11-28 08:53

I have an arraylist of objects. ie ArrayList.

I want to pass this to a new Activity. I tried to use putParcelableArrayList but it has issues with the object. I remov

相关标签:
10条回答
  • 2020-11-28 09:06

    1) Make sure the object you want to parcel has correctly implemented Parcelable

    2) Use this argument in putParcelableArrayList: new ArrayList<>(list)

    Example:

        protected void onSaveInstanceState(Bundle outstate) {
            super.onSaveInstanceState(outstate);
            outstate.putParcelableArrayList("myObjects", new ArrayList<>(myListOfObjects));
        }
    
    0 讨论(0)
  • 2020-11-28 09:07

    what helped me was: setting all values while writing to the parcel. In case any value is NULL, I am setting deafult value for that particular property. Null values were getting set for few parameters, and thats why this error was being thrown.

    0 讨论(0)
  • 2020-11-28 09:14

    Very Easy way, try the following:

    bundle.putSerializable("lstContact", (Serializable) lstObject);
    lstObj = (List<Contacts>) bundle.getSerializable("lstContact");
    

    and also you will need to implement your Contact class from Serializable interface. ex :

    public class Contact implements Serializable{
       ...
       ...
       ...
    }
    
    0 讨论(0)
  • 2020-11-28 09:14

    I was struggling with same issue and found a much better approach of putting my array in Global Class that can be accessed across all activities. Thanks to this post for describing how to use global variables that can be accessed across multiple activities.

    My global class is

    public class GlobalClass extends Application{ public MyObject[] objArray }

    Android Manifest Change

    android:name=".GlobalClass"
    

    Accessed in multiple activities as

    GlobalClass g = (GlobalClass)getApplicationContext();
    g.objArray[0].x = 100;
    int x = g.objArray[0].x;
    

    For Better understanding please go through the post.

    0 讨论(0)
  • 2020-11-28 09:17

    When I had to do that I simply put the ArrayList of objects into the extras bundle (it has to be an ArrayList, List is not Serializable apparently). Then all you have to do then is ensure the objects inside the list are serializable also.

    0 讨论(0)
  • 2020-11-28 09:18

    Looking at the documentation for putParcelableArrayList it looks like your ObjectName needs to extend the 'Parcelable' interface in order for this to work. The error you get seems to indicate this as well.

    I would look here: http://developer.android.com/reference/android/os/Parcelable.html

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