I'm aware of the performance differences between Parcelable (fast) and Serializable (slow). However, I need to store certain application information persistently, not just within one lifecycle, thus onSaveInstanceState and associated methods utilising Parcelable objects aren't appropriate.
So I turned my attention to Serializable. Primarily I have AbstractList types to store - which is fine, since they implement Serializable. However, many of the types I store inside these are Parcelable but not Serializable, e.g. RectF.
I thought "no problem", since I can easily generate a Parcel via Parcelable.writeToParcel(parcel, flags) then call marshall() on it to create a byte[] which I can serialize and deserialize. I figured I'd use generics; create a SerializableParcelable<Parcelable> implements Serializable class, allowing a one-fit solution for all Parcelable types I wish to serialize. Then I would e.g. store each RectF inside this wrapper within ArrayList, and lo-and-behold the list and its Parcelable contents are serializable.
However, the API docs state that marshall() mustn't be used for persistent storage:
public final byte[] marshall ()
Returns the raw bytes of the parcel.
The data you retrieve here must not be placed in any kind of persistent storage (on local disk, across a network, etc). For that, you should use standard serialization or another kind of general serialization mechanism. The Parcel marshalled representation is highly optimized for local IPC, and as such does not attempt to maintain compatibility with data created in different versions of the platform.
So now I'm stuck. I can either ignore this warning and follow the route I've outlined above, or else circumvent the issue by extending each individual Parcelable I want to serialize and creating bespoke serialization methods, which seems extremely wasteful of time and effort.
Does anyone know of a 'correct' shortcut to serialize a Parcelable object without using marshall()? Or should I plough on without heeding the warning specified? Perhaps an SQLite database is the way to go, but I'm unsure and would like your advice.
Many thanks.
For any object you need to serialize you can use objectOutPutStream .By using this you can write objects into the file system of the device.So this can used to save Parcelable objects also.
Below is the code to save object to File System.
public static void witeObjectToFile(Context context, Object object, String filename) {
ObjectOutputStream objectOut = null;
FileOutputStream fileOut = null;
try {
File file = new File(filename);
if(!file.exists()){
file.createNewFile();
}
fileOut = new FileOutputStream(file,false);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
// do nowt
}
}
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e) {
// do nowt
}
}
}
}`
Inorder to read the Object use ObjectInputStream . Find the below code.
public static Object readObjectFromFile(Context context, String filename) {
ObjectInputStream objectIn = null;
Object object = null;
FileInputStream fileIn = null;
try {
File file = new File(filename);
fileIn = new FileInputStream(file);//context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e) {
// Do nothing
}catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
// do nowt
}
}
if(fileIn != null){
try {
fileIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return object;
}`
Regards,
Sha
Related
I am trying to save in cache response from server for certain time.
There are tne next data for saving in cache: I have a List<ProgrammeItem> which I am getting from server. While user is working, he can download up to ~230 List<ProgrammeItem> (but it is unreal to reach this, estimated is 10-50).
ProgrammeItem oblect including strings, int, int[].
That is how I am saving and getting the last downloaded List<ProgrammeItem>:
//saving / getting Programme items
public boolean saveObject(List<ProgrammeItem> obj) {
final File suspend_f=new File(android.os.Environment.getExternalStorageDirectory(), "test");
FileOutputStream fos = null;
ObjectOutputStream oos = null;
boolean keep = true;
try {
fos = new FileOutputStream(suspend_f);
oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
} catch (Exception e) {
keep = false;
Log.e("catching exception ", "" + e.getMessage() + ";;;" + e);
} finally {
try {
if (oos != null) oos.close();
if (fos != null) fos.close();
if (keep == false) suspend_f.delete();
} catch (Exception e) { /* do nothing */ }
}
return keep;
}
public List<ProgrammeItem> getObject(Context c) {
final File suspend_f=new File(android.os.Environment.getExternalStorageDirectory(), "test");
List<ProgrammeItem> simpleClass= null;
FileInputStream fis = null;
ObjectInputStream is = null;
try {
fis = new FileInputStream(suspend_f);
is = new ObjectInputStream(fis);
simpleClass = (List<ProgrammeItem>) is.readObject();
} catch(Exception e) {
String val= e.getMessage();
} finally {
try {
if (fis != null) fis.close();
if (is != null) is.close();
} catch (Exception e) { }
}
return simpleClass;
}
That is how I am saving and getting object in activity:
PI = new ProgrammeItem();
List<ProgrammeItem> programmeItems = new ArrayList<>();
...
//filling programmeItems with data from server
...
boolean result = PI.saveObject(programmeItems); //Save object
ProgrammeItem m = new ProgrammeItem();
List<ProgrammeItem> c = m.getObject(getApplicationContext()); //Get object
The question is: how can I save a lot of my objects instead of only one?
I think I should done something like public boolean addObjectsInCache(List<ProgrammeItem> obj) for adding objects, not overriding them.
And change get method into public List<ProgrammeItem> getObject(Context c, String id), where id will be unique identifier, which will includes into every ProgrammeItem in the every List<ProgrammeItem>.
Am I right? And how I can achieve this? Maybe you will show me the other way to work with objects and cache?
You can use SharedPreference instead, while having a local database Android Room can also be an option. SharedPreference basically is stored in your device's cache while the local database is stored in your device's data hence in our apps we have clear cache and clear data function.
Additional Resources:
StackOverFlow: How Android SharedPreferences save/store object
Object based preference library: https://github.com/ShawnLin013/PreferencesManager I would suggest you go with this one, since it can easily save you time saving list based object and retrieving them. You can also add more to the persisted list object when needed.
Secured Preferences: https://github.com/scottyab/secure-preferences
An option could be to use Room database with inMemoryDatabaseBuilder:
db = Room.inMemoryDatabaseBuilder(context, ProgrammeDatabase::class.java)
.build()
if it all can fit in memory.
I'm working on an app which stores small amounts of data in /data/data/my_app/files using this code:
private void buildFileFromPreset(String fileName) {
fileName = fileName.toLowerCase();
StandardData data = StandardData.getInstance();
String[] list = data.getDataByName(fileName);
FileOutputStream fos = null;
try {
fos = openFileOutput(fileName, Context.MODE_PRIVATE);
PrintWriter writer = new PrintWriter(fos);
for (int i = 0; i < list.length; i++) {
writer.println(list[i]);
}
writer.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
All works fine when the app gets started, in the onCreate() function of the main activity, I want to check if the files that were created last time are still present:
private String getAppFilesDir() {
ContextWrapper c = new ContextWrapper(this);
return c.getFilesDir().toString();
}
which returns something like:
/data/user/0/my_app/files
I've read some older posts (2012) suggesting this method must work but it doesn't, probably since jellybean.
So my question:
How can I check if the files I created using FileOutputStream and PrintWriter in a previous session still exist?
I hope I provided enough info for you guys to answer (:
I still have not found a solution for this specific problem.
Instead I am now using SQLite so I don't have to worry about these kinds of things.
Greetings,
I have a game, and i want to save the objects ( creatues ) that move on canvas to a bundle so that when someone pauses/leaves the app, the objects can stay where they were.
I have looked at the LunarLanding game where they save the coordinates of the space shuttle into bundles and read from them and i want to do same ( if there is no better way ) but i have objects of a custom type and i am not sure how to save them and read from the bundle.
I could do the save of all the parts of the object individually and put them back together, but i have a lot of objects and that would just be ugly code to do all that.
It would be just great if i could save an object to a bundle, but so far i had no luck searching the internet on how to do so.
I was also thinking about implementing Parcelable to my object, but i want to know if there is any other way.
Any suggestions?
Thanks!
Basically you have 2 options
1 - Implement Serializable, really simple to implement, but has a bad drawback which is performance.
2 - Implement Parcelable, very fast, but you need to implement the parser method (writeToParcel()), which basically you have to serialize manually, but afterwards bundle will call it automatically for you and will produce a much more performatic serialization.
Technically, the onSaveInstanceState() method is called mostly only on orientation change if I remember correctly. If you want to make persistent data, you should use the onPause() or onStop() callback, and serialize the game state.
The ways you can do that is either by storing the state in a SQLite database (seems overkill), or make it so that you can serialize the object that keeps track of the entities via implementing the Serializable interface, and save the object to a file.
Serialization:
#Override
public void onPause()
{
super.onPause();
FileOutputStream out = null;
try
{
out = openFileOutput("GameModelBackup",Context.MODE_PRIVATE);
try
{
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(gm);
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
}
catch(FileNotFoundException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
finally
{
try
{
if(out != null) out.close();
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
}
}
Deserialization:
#Override
public void onResume()
{
super.onResume();
FileInputStream in = null;
try
{
in = openFileInput("GameModelBackup");
ObjectInputStream oos = new ObjectInputStream(in);
try
{
gm = (GameModel)oos.readObject();
}
catch(ClassNotFoundException e)
{
gm = null;
}
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
finally
{
try
{
if(in != null) in.close();
}
catch(IOException e) {}
}
}
At first I have strong Java knowledege, but however just started with Android.
My Android app is downloading some fairly complex data (texts, dates, images) which I am saving in a custom object. The data need to be refresh from time to time. However usually the data downloaded will not change.
In order to keep the data in memory I am using the Application Object. Unfortunately, it looks like the application object instance is destroyed when the app is killed.
Hence, I was wondering if it would be of good practice to serialize and save my custom object (which is contained in the application object) in the internal storage during onPause(). Obviously, I would then first read from the file in onResume() before reloading from the internet. The idea is also to enable offline viewing.
In longer term the plan is to move the code downloading the date in a background service. As there seems to be many different ways to keep application state in Android, I would like to be be sure that this is the correct way to go.
Try using those methods class to save the Object(s) (implements serialize) you need:
public synchronized boolean save(String fileName, Object objToSave)
{
try
{
// save to file
File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/file.file");
if (file.exists())
{
file.delete();
}
file.getParentFile().mkdirs();
file.createNewFile();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(objToSave);
oos.close();
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return false;
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
}
public synchronized Object load(String fileName)
{
try
{
File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/file.file");
if (!file.exists())
{
return null;
}
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
savedObj = ois.readObject();
ois.close();
return savedObj;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return null;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
You'll need to cast the Object you load().
CONTEXT is an Activity or ApplicationContext to get access to the cachedir.
Your could use Environment.getExternalStorageState() instead to get a directory path. DOn't forget to add it "/filename".
I'm getting odd warnings in my reading of a ArrayList of Serializable objects. Here is the code:
public void loadBoard() {
FileInputStream fis = null;
ObjectInputStream is;
try {
fis = this.openFileInput(saveFile);
is = new ObjectInputStream(fis);
// Build up sample vision board
if (mVisionBoard == null) {
mVisionBoard = new ArrayList<VisionObject>();
} else {
mVisionBoard.clear();
}
ArrayList<VisionObject> readObject = (ArrayList<VisionObject>) is.readObject();
mVisionBoard = readObject;
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (StreamCorruptedException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
}
}
and the warning I'm getting is (on readObject line):
"Type safety: unchecked cast from Object to ArrayList"
The few examples I've read indicate that this is the correct code for reading an ArrayList of serializable objects. The code I made to write the arraylist isn't giving me any warnings. Am I doing something wrong here?
kind of late but it will help someone...
the reason of the warning is because of the return of the method readObject...
see:
public final Object readObject()
it returns actually an object
and if you just by mistake read and deserialize a lets say String object ant try to cast that into an array list then you will get a runtime execption (the reason must be obvious)
in order to avoid that predictable failure you can check the type of the returned object before the cast...
that is why you get the warning:
"Type safety: unchecked cast from Object to ArrayList<VisionObject>"