android how to save an object to file?

断了今生、忘了曾经 提交于 2019-12-12 07:54:42

问题


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


回答1:


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.




回答2:


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




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/3625496/android-how-to-save-an-object-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!