How to deserialize Activity object in a background thread?

385 Views Asked by At

Possible Duplicate:
RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I have a problem with using Java Serialization mechanism in Android. It works well when invoked from the UI thread, but when I try to use it from some background thread I get:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Because of project nature I cannot deserialize everything in UI thread (also it should be possible to do it in background, so the UI will not stop responding).

BTW. Same thing happens when I try to deserialize something in background using SimpleXML.

So now we do deserialization (both XML and Java serialization) from UI thread which cannot be used everywhere.

Can anyone shed some light on this issue?

EDIT:

I'm using the following code to deserialize an object, it works well when called from UI thread.

public Object getObject(String key) throws InvalidClassException {
    Object result;
    try {
        FileInputStream fileIn = context.openFileInput(getPath(key));
        ObjectInputStream in = new ObjectInputStream(fileIn);
        result = in.readObject();
        in.close();
        fileIn.close();
    } catch (InvalidClassException e) {
        throw new InvalidClassException(e.getMessage());
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    return result;
}

EDIT 2

As mentioned in EJP comment below, I'm deserializing an Activity object. So I'm changing my questuion to: How to deserialize Activity object in a background thread? Not deserializing this object is an option that I'd rather avoid, because of performance issues (XML deserializes in about 4s while binary deserialization is less then 0.5s). I know that it would be possible to redesign our application, but due to project constraints, and it's extreme and unnecessary complexity, that's not really an option. Every bigger change is extremely painful.

So when issue is little clearer - does anyone have some ideas?

Thanks for any suggestions.

2

There are 2 best solutions below

2
On

Try and call Loooper.Prepare(); before your code and Looper.Loop(); after, workd for me.

Something like :

Looper.Prepare();
//your code
Looper.Loop();
2
On

you cannot do ui operations in any other thread all ui operations should be on mainthread

you can use this

   runOnUiThread(new Runnable() {

        @Override
        public void run() {
            code here

        }
    });