简体   繁体   中英

Save an Arraylist of two different types in shared preferences

I currently have an arraylist of a certain type which I'm trying to save in shared prefernces.

I have a class called WinClass. I have classes called LoggedInWin and UserWin, both inheriting the WinClass class. There's an arraylist winClasses which has objects of both types. I currently have a code that saves the ArrayList in shared prefernces successfully, but only saves WinClass objects. That means that if my Arraylist has items of Winclass, LoggedInWin and UserWin, it will only save the objects of WinClass. I have looked and my code and changed the part where it loads the data type to load only objects of LoggedInWin. It has in-fact this time only saved LoggedInWin objects. That left me wondering how can I have the arraylist saved with all of its objects saved with it (all types included).

The code where I save the arraylist:

    private void saveData() {
        SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(winClasses);
        editor.putString("task list", json);
        editor.apply();
    }

    private void loadData() {
        SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString("task list", null);
        Type type = new TypeToken<ArrayList<LoggedInWin>>() {}.getType();
        winClasses = gson.fromJson(json, type);

        if (winClasses == null) {
            winClasses = new ArrayList<>();
        }
    }

Ended up solving it. Here's how (in case anyone needs it in the future) Saved one Arraylist of one type (LoggedInWin) Saved anoher Arraylist of the other type (UserWin) Put them both in a third arraylist (WinClass). Then the WinClass arraylist was saved. Pretty simple solution but didn't think about it straight away

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM