在sharedpreferences中存储hashmap的问题

时间:2015-07-03 13:26:25

标签: java android arraylist hashmap sharedpreferences

我使用以下两种方法在我的共享首选项中存储自定义对象的ArrayList。

 public ArrayList<BetDisplayer> getallopenbets() {
    allopenbets = new Gson().fromJson(pref.getString(ALL_OPEN_BETS, null), ALL_OPEN_BETS_TYPE);
    if (allopenbets == null) {
        allopenbets = new Gson().fromJson(pref.getString(ALL_OPEN_BETS, null), ALL_OPEN_BETS_TYPE);
        if(allopenbets == null){
            allopenbets = new ArrayList<BetDisplayer>();
        }
    }
    return allopenbets;
}
public void setallopenbets (ArrayList<BetDisplayer> listwriter) {
    this.allopenbets = listwriter;
    editor.putString(ALL_OPEN_BETS, new Gson().toJson(listwriter));
    editor.commit();
}

哪里

    public static final String ALL_OPEN_BETS = "all_open_bets";

    private static final Type ALL_OPEN_BETS_TYPE = new  TypeToken<ArrayList<BetDisplayer>>() {}.getType();

这完全没问题。我尝试使用相同的逻辑来使用以下两种方法存储HashMap<String,String>但是它似乎不起作用,因为当我调用getfinalteams时,我得到一个空的hashmap,即使我在正确设置它之前。

 public HashMap<String,String> getFinalteams() {
    finalteams = new Gson().fromJson(pref.getString(FINALTEAMS, null), FINAL_TEAMS_TYPE);
    if (finalteams == null) {
        finalteams = new Gson().fromJson(pref.getString(FINALTEAMS, null), FINAL_TEAMS_TYPE);
        if(finalteams == null){
            finalteams = new HashMap<>();
        }
    }
    return finalteams;
}
public void setFinalteams (HashMap<String,String> listwriter) {
    this.finalteams = listwriter;
    editor.putString(FINALTEAMS, new Gson().toJson(listwriter));
    editor.commit();
}

哪里

    public static final String FINALTEAMS = "finalteams";

    private static final Type FINAL_TEAMS_TYPE = new TypeToken<HashMap<String,String>>() {}.getType();

0 个答案:

没有答案
相关问题