Say I have some simple class and once it's instantiated as an object I want to be able to serialize its contents to a file, and retrieve it by loading that file at some later time... I'm not sure where to start here, what do I need to do to serialize this object to a file?
public class SimpleClass { public string name; public int id; public void save() { /* wtf do I do here? */ } public static SimpleClass load(String file) { /* what about here? */ } }
This is probably the easiest question in the world, because this is a really simple task in .NET, but in Android I'm pretty new so I'm completely lost.
The Serialization is a process of changing the state of an object into a byte stream, an object is said to be serializable if its class or parent classes implement either the Serializable or Externalizable interface and the Deserialization is a process of converting the serialized object back into a copy of an object.
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
Saving (w/o exception handling code):
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(this); os.close(); fos.close();
Loading (w/o exception handling code):
FileInputStream fis = context.openFileInput(fileName); ObjectInputStream is = new ObjectInputStream(fis); SimpleClass simpleClass = (SimpleClass) is.readObject(); is.close(); fis.close();
I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:
Option1:
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(this); os.close();
Option2:
SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE); SharedPreferences.Editor ed=mPrefs.edit(); Gson gson = new Gson(); ed.putString("myObjectKey", gson.toJson(objectToSave)); ed.commit();
Option 2 is twice quicker than option 1
The option 2 inconvenience is that you have to make specific code for read:
Gson gson = new Gson(); JsonParser parser=new JsonParser(); //object arr example JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray(); events=new Event[arr.size()]; int i=0; for (JsonElement jsonElement : arr) events[i++]=gson.fromJson(jsonElement, Event.class); //Object example pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With