简体   繁体   中英

Storing ArrayList with custom object

I'm trying to save ArrayList with a custom object in it. Problem is that the ArrayList is in my singleton. My singleton "Choices" holds ArrayList<Choice> list; and the "Choice" has 4 different types of variables.

I don't know how to access my ArrayList from my activity because the below code didn't work. getMyList() method returns list.

SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(Choices.getInstance().getMyList());
    editor.putString("list", json);
    editor.commit();

When I'm retrieving the list I tried something like this but it didn't work.

    String json = prefs.getString("list", "");
    Type type = new TypeToken<Choice>() {}.getType();
    ArrayList<Choice> savedList = gson.fromJson(json, type);

Any help or suggestions would help a lot.

How about this while retrieval :

String json = prefs.getString("list", "");
ArrayList<Choice> savedList = (ArrayList<Choice>) jsonToList(json,
                    new TypeToken<ArrayList<Choice>>() {
                    }.getType());

public static Object jsonToList(String jsonString, Type type) {
        return new Gson().fromJson(jsonString, type);
    }

In retrieving code change
Type type = new TypeToken<Choice>() {}.getType();
to
Type type = new TypeToken<List<Choice>>() {}.getType() ; as you need to parse though a list of your custom object.

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