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);
I just made a class to handle this with Generics, so it can be used with all the object types that are serializable:
public class SerializableManager {
/**
* Saves a serializable object.
*
* @param context The application context.
* @param objectToSave The object to save.
* @param fileName The name of the file.
* @param The type of the object.
*/
public static void saveSerializable(Context context, T objectToSave, String fileName) {
try {
FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(objectToSave);
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Loads a serializable object.
*
* @param context The application context.
* @param fileName The filename.
* @param The object type.
*
* @return the serializable object.
*/
public static T readSerializable(Context context, String fileName) {
T objectToReturn = null;
try {
FileInputStream fileInputStream = context.openFileInput(fileName);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
objectToReturn = (T) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return objectToReturn;
}
/**
* Removes a specified file.
*
* @param context The application context.
* @param filename The name of the file.
*/
public static void removeSerializable(Context context, String filename) {
context.deleteFile(filename);
}
}
Complete code with error handling and added file stream closes. Add it to your class that you want to be able to serialize and deserialize. In my case the class name is CreateResumeForm. You should change it to your own class name. Android interface Serializable is not sufficient to save your objects to the file, it only creates streams.
// Constant with a file name
public static String fileName = "createResumeForm.ser";
// Serializes an object and saves it to a file
public void saveToFile(Context context) {
try {
FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Creates an object by reading it from a file
public static CreateResumeForm readFromFile(Context context) {
CreateResumeForm createResumeForm = null;
try {
FileInputStream fileInputStream = context.openFileInput(fileName);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
createResumeForm = (CreateResumeForm) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return createResumeForm;
}
Use it like this in your Activity:
form = CreateResumeForm.readFromFile(this);
I use SharePrefrences:
package myapps.serializedemo;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create the SharedPreferences
SharedPreferences sharedPreferences = this.getSharedPreferences("myapps.serilizerdemo", Context.MODE_PRIVATE);
ArrayList friends = new ArrayList<>();
friends.add("Jack");
friends.add("Joe");
try {
//Write / Serialize
sharedPreferences.edit().putString("friends",
ObjectSerializer.serialize(friends)).apply();
} catch (IOException e) {
e.printStackTrace();
}
//READ BACK
ArrayList newFriends = new ArrayList<>();
try {
newFriends = (ArrayList) ObjectSerializer.deserialize(
sharedPreferences.getString("friends", ObjectSerializer.serialize(new ArrayList())));
} catch (IOException e) {
e.printStackTrace();
}
Log.i("***NewFriends", newFriends.toString());
}
}