android how to save an object to file?

前端 未结 3 2103
醉话见心
醉话见心 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:35

    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

    0 讨论(0)
  • 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<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();
            }
    }
    
    0 讨论(0)
  • 2021-02-15 16:57

    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.

    0 讨论(0)
提交回复
热议问题