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:

<Survey>
  <Questions>
    <Question class="SingleLineQuestion">
      <Title>What is your name?</Title
      <MaxLength>50</MaxLength>
    </Question>
    <Question class="NumericQuestion">
      <Title>How old are you?</Title>
      <Minimum>10</Minimum>
      <Maximum>80</Maximum>
    </Question>
  </Questions>
</Survey>

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:

java.lang.ClassNotFoundException: SingleLineQuestion
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:

Thread.currentThread().setContextClassLoader(context.class.getClassLoader());
Serializer serializer = new Persister();
...

Happy coding!