Sunday, July 4, 2010

[android-developers] android serializable does not work for subtypes?

Hi, I stored subtypes into an ArrayList, and when I tried to serialize
the ArrayList, I get NotSerializable exceptions. (See sample code
below). I tried the same logic in Java, and it works fine.

Is this an Android implementation issue, or prehaps I left out
something?

Thanks and regards

------------------------------------------

package com.test_serializable;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

public class test_serializable extends Activity {
/** Called when the activity is first created. */

private ArrayList<basetype> data=null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

data=new ArrayList<basetype>();

// populate ArrayList with some data

typeA i=new typeA();
i.base=0;
i.a=1;
data.add(i);

typeB j=new typeB();
j.base=0;
j.b=2;
data.add(j);
}


@Override
public void onPause() {
super.onPause();
//serialize to file
try{
FileOutputStream fos = openFileOutput("datafile",
Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
fos.close();
} catch (Exception e){
Toast t=
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG);
t.show();
}
}

class basetype implements Serializable {
int base;
}

class typeA extends basetype {
int a;
}

class typeB extends basetype {
int b;

}
}

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment