且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-20 13:28:55

所以我设法使其正常运行,这是许多代码的混合体. 首先,在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();