Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

android - "BadParcelableException: ClassNotFoundException when unmarshalling <myclass>" while using Parcel.read method that has a ClassLoader as argument

Given a custom class org.example.app.MyClass implements Parcelable, I want to write a List<MyClass> to a Parcel. I did the marshalling with

 List<MyClass> myclassList = ...
 parcel.writeList(myclassList);

whenever I try to unmarshall the class with

 List<MyClass> myclassList = new ArrayList<MyClass>();
 parcel.readList(myclassList, null);

there is an "BadParcelableException: ClassNotFoundException when unmarshalling org.example.app.MyClass" exception.

What is wrong here? Why is the class not found?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't unmarshall a custom class (i.e. one provided by your application and not by the Android framework) with the framework class loader that is used when you give null as the ClassLoader argument. Use the application class loader:

parcel.readList(myclassList, getClass().getClassLoader());

Whenever a Parcel.read*() method also has a ClassLoader as an argument (e.g. Parcel.readList(List outVal, ClassLoader loader)) and you want to read an application class from a Parcel, use the application class loader that can be retrieved with getClass().getClassLoader().

Background: Android comes with two class loaders: the system class loader, that is able to load all system classes but the ones provided by your application; and the application class loader, which has set the system class loader as its parent and therefore is able to load all classes. If you give null as the class loader, Parcel.readParcelableCreator() will use the framework class loader, causing a ClassNotFoundException.

Thanks to alexanderblom for providing the hint that led me on the right track.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...