Search code examples
javaandroidpersistenceserializable

Porting java application to android - is it possible to make Serializable work?


I'm attempting to port a java application to android. The application uses Serializable to store data. There's an array list of users, and each user has various other elements(all of which also implement serializable). In the java app, saving all data was simply a matter of calling a method that writes the serialized user list to a text file. This doesn't seem to work with Android.

It's not a file not found or IO exception - I took care of that already.

Any ideas on how to get around this?

public boolean loadUsers()
    {
        File newFile = new File("sdcard/download/users.txt");
        FileInputStream fileIn = null;
    try 
    {
        fileIn = new FileInputStream(newFile);
        ObjectInputStream inStream = new ObjectInputStream(fileIn);
        users = (ArrayList<User>)inStream.readObject();
        fileIn.close();
        return true;
    } 
    catch (FileNotFoundException e) 
    {
        System.err.println("File not found exception...");
    }
    catch (IOException e)
    {
        System.err.println("Error occurred reading the file, aborting...");
    }
    catch (Exception e)
    {
        System.err.println("Unexpected exception...");
    }
    return false;
}

I've figured it out - I changed the package names, so the old serialized file isn't being read properly for that reason. Everything works fine otherwise.


Solution

  • A ClassNotFoundException when you are trying to deserialize objects most likely means that you don't have classes on your classpath for the objects in the serial stream. You need to add the relevant JAR file (or whatever) to the classpath. The full exception message / stacktrace will tell you which class it is missing ...

    (This is not an Android-specific problem. The serialized object stream does not contain the bytecodes for the classes. The JVM needs to have those bytecodes before it can reassemble usable objects from the stream.)


    I've figured it out - I changed the package names, so the old serialized file isn't being read properly for that reason.

    That's right. When you change the package name, the class becomes a different class ... as far as the JVM is concerned.