Android, How to use readTypedList method correctly in a Parcelable class?

前端 未结 4 1419
粉色の甜心
粉色の甜心 2020-12-13 18:55

I have two Activities, in the first one, I instanciate an ArrayList of Object myObject. In the second activity, i need to get this Arraylist. I\'ve found a tutorial : http:/

相关标签:
4条回答
  • 2020-12-13 18:58

    Hopefully, you've figured this out by now. But for anyone else who stumbles upon this one. The NullPointerException you were getting was caused by the ArrayList never being initialized.

    This would fix it:

    private Chapitre(){
        listVideo = new ArrayList<Video>();
    }
    
    private Chapitre(Parcel source) {
        // Call the above constructor
        this();
    
        numero = source.readInt();
        titre = source.readString();
        description = source.readString();
        nbVideo = source.readInt();
        source.readTypedList(listeVideo, Video.CREATOR);
    }
    
    0 讨论(0)
  • 2020-12-13 18:58

    Another solution: use createTypedArrayList instead of readTypedList which requires a non-null List object reference

    0 讨论(0)
  • 2020-12-13 19:02

    Also consider initializing the object with an immutable empty list.

    private ArrayList<Video> listevideo = Collections.emptyList()

    More details here: Collections.emptyList() vs. new instance

    0 讨论(0)
  • 2020-12-13 19:06

    Also keep in mind that you have to read and write parcelable object attribute in the same order! I also 2 hours because the unmarshalling was not in the same order of the marshalling.

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