3

i have problem to save my arraylist. I want to save my arraylist when application destroy or change intent or change orientation:

public class AuditContainer implements Serializable {
    private Paint mPaint;
    private Path mPath;
    private int x,y;
    private String text;
    boolean is_text;

First i tried saving in file, but Paint class isn't Serializable class. Second i try with onSaveInstanceState(Bundle outState) / onRestoreInstanceState(Bundle savedInstanceState) but i could not save Arraylist and third i try with database but there isnt any types of Paint, Path ... If anyone have got suggestion for me, i will be very happy.

4

4 回答 4

3

If Paint and Path are classes under your control, then make them serializable too. If they are not completely relevant or you can determine them externally when you read the object back, then you can make the fields transient.

于 2013-09-02T06:52:22.963 回答
3

You have three choices:

A. Modify Paint to implement Serializable.
B. Mark the field as not for serialization using the transient keyword:

private transient Paint mPaint;

C. Write your own Serializable wrapper for Paint that keeps Serializable copies of the key fields, and delegates functionality to a private transient Paint, and can re-initialize the Paint instance after deserialization.

于 2013-09-02T06:52:50.467 回答
1

To omit the serialization of non-serializable fields, mark them as transient:

public class AuditContainer implements Serializable {
    private transient Paint mPaint;
    private transient Path mPath;
    private int x,y;
    private String text;
    boolean is_text;
}

Probably there's data on Paint mPaint and Path mPath fields that you still want to store on serialization and retrieve on deserialization processes, for this you have to implement writeObject and readObject methods:

private void writeObject(ObjectOutputStream out)
    throws IOException {
    //default serialization of the object
    out.defaultWriteObject();
    //start manual serialization
    out.writeInt(mPaint.getX());
    out.writeInt(mPaint.getY());
    out.writeObject(mPath.getPath());
}

private void readObject(ObjectInputStream in)
    throws IOException {
    //default serialization of the object
    in.defaultReadObject();
    //start manual deserialization
    int x = in.readInt();
    int y = in.readInt();
    String path = (String)in.readObject();
    //initialize your fields...
    //note: this code maybe won't work, you should adapt it to your needs
    mPaint = new Paint(x, y);
    mPath = new Path(path);
}
于 2013-09-02T06:57:46.260 回答
1

You can use third party like XStream.It allows use to save object to xml, and it not need that object must be Serializable. We had similair problem in our company (class that cannot be modified and must be saved) and XStream helped us. Please look at: http://x-stream.github.io/tutorial.html for simple tutorial.

于 2013-09-02T10:22:14.397 回答