user2234
user2234

Reputation: 1302

NotSerializableException: How can i save ClipData to a File?

I want to save Clipboard data to a file. This is the code in my Activity class:

ClipData clip = mClipboard.getPrimaryClip();

FileOutputStream fos;
ObjectOutputStream os;
try {
    fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    os = new ObjectOutputStream(fos);
    os.writeObject(clip);
    os.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

I get this exception:

06-26 20:20:03.556: W/System.err(24228): java.io.NotSerializableException: android.content.ClipData 06-26 20:20:03.556: W/System.err(24228): at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1364) 06-26 20:20:03.556: W/System.err(24228): at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671) 06-26 20:20:03.556: W/System.err(24228): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517) 06-26 20:20:03.556: W/System.err(24228): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)

As ClipData is an Android class, how can I remove this exception by Serializing ?

Thanks, Sneha

Upvotes: 0

Views: 165

Answers (1)

Olsavage
Olsavage

Reputation: 1108

Only primitive types can be serialized. ClipDate not implements Serializable interface. So, you can't do this. But you can create your own object. It should implement Serializable interface and contain fields with primitive types, such as String. You can fill them with necessary data from ClipDate object and serialize your object. Then you can deserialize your object and restore initial ClipDate oject.

Upvotes: 2

Related Questions