Home » Android » android how to save an object to file?

android how to save an object to file?

Posted by: admin June 15, 2020 Leave a comment

Questions:

Does someone know how to save and restore an object to a file on android ?

How to&Answers:

Open a file using openFileOutput() ( http://developer.android.com/guide/topics/data/data-storage.html#filesInternal ), than use an ObjectOutputStream ( http://download.oracle.com/javase/1.4.2/docs/api/java/io/ObjectOutputStream.html ) to write your object to a file.

Use their evil twin openFileInput() and ObjectInputStream() to reverse the process.

Answer:

It depends if You want to save file on internal or external media. For both situation there are great samples on Android DEV site: http://developer.android.com/guide/topics/data/data-storage.html – this should definetly help

Answer:

See here for a code example : android how to save a bitmap – buggy code

Answer:

Here is a tested example of @yayay’s suggestion. Note that using readObject() returns an Object, so you will need to cast, although the compiler will complain that it is an unchecked cast. I can still run my code fine though. You can read more about the casting issue here.

Just make sure that your class (in my case, ListItemsModel) is serializable, because the writeObject() will serialize your object, and the readObject() will deserialize it. If it is not (you get no persistence and the logcat throws a NotSerializableException), then make sure your class implements java.io.Serializable, and you’re good to go. Note, no methods need implementing in this interface. If your class cannot implement Serializable and work (e.g. 3rd party library classes), this link helps you to serialize your object.

private void readItems() {

        FileInputStream fis = null;
        try {
            fis = openFileInput("groceries");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            ObjectInputStream ois = new ObjectInputStream(fis);
            ArrayList<ListItemsModel> list = (ArrayList<ListItemsModel>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
}

private void writeItems() {

        FileOutputStream fos = null;
        try {
            fos = openFileOutput("groceries", Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(itemsList);
        } catch (IOException e) {
            e.printStackTrace();
        }
}