I’m writing an Android app that uses Simple XML to parse XML directly into class instances. Simple XML works wonders, but a problem occurs when using polymorphism. My application stores and retrieves surveys. A survey contains a list of questions, and questions can be of various types. There are text questions, numeric questions, list questions […]
This article was posted by Independent Software, a website and database application development company based in Maputo, Mozambique. Our website offers regular write-ups on technical and design issues, ranging from details at code level to 3D Studio Max rendering. Read more about Independent Software's philosophy, or get in touch with Independent Software.
I’m writing an Android app that uses Simple XML to parse XML directly into class instances. Simple XML works wonders, but a problem occurs when using polymorphism. My application stores and retrieves surveys. A survey contains a list of questions, and questions can be of various types. There are text questions, numeric questions, list questions etc. Polymorphism is used to implement all these question types.
The following XML snippet illustrates this:
<Title>What is your name?</Title
<Title>How old are you?</Title>
The survey contains a list of question instances, and upon saving the XML, Simple XML has added an attribute to each question stating what the actual Question class is (e.g. class=”SingleLineQuestion”).
The problem is this: loading a survey into memory actually works perfectly on Android 1.5, but fails on Android 2.1 and higher. It produces a ClassNotFound exception:
in loader dalvik.system.PathClassLoader@4001b605
What is happening? Studying the source of Simple XML shows that the required SingleLineQuestion question is instantiated using a ClassLoader. This ClassLoader may run in a different thread context than the main code, and therefore it cannot find the required class to load. This may happen when Simple XML gets called through an synchronous request in order to avoid the application from blocking.
In order to make sure that Simple XML has access to the correct class loader, you can do this:
Serializer serializer = new Persister();
Did this article help you out? Please help us find more time to write useful guides & articles like this by donating a buck or two. It'll keep us coffee-fueled. Thanks!