SharedPreferences不存储值

时间:2013-11-19 19:39:45

标签: android sharedpreferences

大家好我有一个字符串我试图存储到SharedPreferences:

这是我用来存储字符串的方法:

全球大战:

private ArrayList<String> mListEmailAddresses;

方法:

public void setEmailAddressList(String emailAddress){
    emailAddress.replaceAll(",", "");
    mListEmailAddresses.add(emailAddress);
    SharedPreferences prefs = getSharedPreferences("invitefriends", 0);
    StringBuilder str = new StringBuilder();
    for (int i = 0; i < mListEmailAddresses.size(); i++) {
        str.append(mListEmailAddresses.get(i).toString()).append(",");
    }
    LogUtils.log("emails: " + str.toString());
    String theString = str.toString();
    prefs.edit().putString("emails", theString);
    prefs.edit().commit();

}

每次调用此方法时,都会使用添加到列表中的新电子邮件更新str.toString方法。例如“email1 @ gmail.com,email2 @ yahoo.co.uk,email3 @ hotmail.co.uk”将成为形成的字符串。日志正确显示此字符串。然后我将theString放在关键字“电子邮件”下,每当视图重新启动时,它都会刷新,如下所示:

    SharedPreferences prefs = getSharedPreferences("invitefriends", 0);
    String savedString = prefs.getString("emails", "");
    LogUtils.log("saved emails: " + savedString);
    StringTokenizer st = new StringTokenizer(savedString, ",");
    mListEmailAddresses = new ArrayList<String>();
    for (int i = 0; i < st.countTokens(); i++) {
        String strEmail = st.nextToken().toString();
         mListEmailAddresses.add(strEmail);
    }

问题是此处的日志显示已保存的电子邮件是一个空字符串。我究竟做错了什么?多谢你们。

1 个答案:

答案 0 :(得分:6)

您正在对编辑器的其他实例进行提交。请尝试以下代码

SharedPreferences.Editor editor = prefs.edit();
editor.putString("emails", theString);
editor.commit();