android how to save an object to file?

前端 未结 3 2092
醉话见心
醉话见心 2021-02-15 16:01

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

3条回答
  •  再見小時候
    2021-02-15 16:44

    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 list = (ArrayList) 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();
            }
    }
    

提交回复
热议问题