应用关闭后,如何保存自定义对象的ArrayList?

问题描述:

我已经在这里寻找答案了,但没有一个适用于我的特殊情况.我有一个arrayList

I already looked for an answer here but none applied to my particular case. I have an arrayList

ArrayList<GridItem> gridItems = new ArrayList<>();

用户可以通过与应用交互来向其中添加条目.我知道SharedPreferences不适用于对象,并且我无法让gson工作.

To which the user can add entries through interacting with the app. I understand that SharedPreferences doesn't work with objects and I can't get gson to work.

我想将数组列表保存在onPause中,并在onCreate中查找一个预先存在的保存列表.这是正确的方法吗?

I would like to save the arraylist in onPause and look for a preexisting saved list in onCreate. Is this the correct approach?

我应该澄清一下,每个条目都是由两个字符串组成的.这是obj构造函数:

I should clarify that each entry is made of two string. This is the obj constructor:

public GridItem(String Name, String Path){
        mName = Name;
        mPath = Path;
    }

所以每个条目基本上都是这样的:

so each entry is basically like this:

gridItems.add("a name", "/sdcard/emulated etc etc")

所以我设法使其正常运行,这是许多代码的混合体. 首先,在onCreate中,我会初始化ArrayList,如果有一些要还原的数据,它将完成工作,否则它将创建一个empy ArrayList.

So I managed to get it working, It was a mixture of a lot of code. First of all in the onCreate i initialize the ArrayList, and if there is some data to restore it does the work, otherwise it creates an empy ArrayList.

In onCreate
    // Create an ArrayList of GridItem objects
            gridItems = new ArrayList<>(); // Now gridItems = []


            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
            Gson gson = new Gson();
            String json = sharedPrefs.getString(TAG2, null); //Retrieve previously saved data
            if (json != null) { 
                Type type = new TypeToken<ArrayList<GridItem>>() {}.getType();
                gridItems = gson.fromJson(json, type); //Restore previous data
            }
    //Initialize the view
    //NOTE if you pass a null ArrayList<GridItem> the app will crash 
            gridAdapter = new GridItemAdapter(this, gridItems); 
//etc etc

在暂停时,我将实际出现在屏幕上的ArrayList放在json形式中.然后我保存该json值并在OnCreate中使用

In on pause i take the ArrayList actually present on screen and place it in json form. Then I save that json value and use it in OnCreate

在暂停状态

//Set the values
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
        SharedPreferences.Editor editor = sharedPrefs.edit();
        Gson gson = new Gson();

        String json = gson.toJson(gridItems); //Convert the array to json

        editor.putString(TAG2, json); //Put the variable in memory
        editor.commit();