有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在SharedReferences中存储hashmap的java问题

我使用以下两种方法在共享首选项中存储自定义对象的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) 个答案