80,349
社区成员
发帖
与我相关
我的任务
分享
SharedPreferences share = getSharedPreferences("name", 0);
Editor e = share.edit();
//方法a,在第一句输出的时候读不到数据。
String a = "abc_cc";
System.err.println(share.getString(a, "默认结果"));//此句似乎没有执行,没有任何输出,错误...
//但是第二次执行的时候,会正常输出。
e.putString(a, "修改的结果");
e.commit();
System.err.println(share.getString(a, "默认结果"));//输出:修改的结果,正常
//方法b,一切正常
System.err.println(share.getString("abc_cc", "默认结果"));//输出:默认结果,正常
e.putString("abc_cc", "修改的结果");
e.commit();
System.err.println(share.getString("abc_cc", "默认结果"));//输出:修改的结果,正常
//求解,为什么方法a不行?
String getString(String key, String defValue);
/**
* Retrieve a set of String values from the preferences.
*
* <p>Note that you <em>must not</em> modify the set instance returned
* by this call. The consistency of the stored data is not guaranteed
* if you do, nor is your ability to modify the instance at all.
*
* @param key The name of the preference to retrieve.
* @param defValues Values to return if this preference does not exist.
*
* @return Returns the preference values if they exist, or defValues.
* Throws ClassCastException if there is a preference with this name
* that is not a Set.
*
* @throws ClassCastException
*/
SharedPreferences share = getSharedPreferences("name", 0);
//方法a,在第一句输出的时候读不到数据。
String a = "abc_cc";
System.err.println(share.getString(a, "默认结果1"));//此句似乎没有执行,没有任何输出,错误...
//但是第二次执行的时候,会正常输出。
Editor e = share.edit();
e.putString(a, "修改的结果2");
e.commit();
System.err.println(share.getString(a, "默认结果3"));//输出:修改的结果,正常
//方法b,一切正常
System.err.println(share.getString("abc_cc", "默认结果4"));//输出:默认结果,正常
e.putString("abc_cc", "修改的结果5");
e.commit();
System.err.println(share.getString("abc_cc", "默认结果6"));//输出:修改的结果,正常