android SharedPreferences 的问题,读不到数据。

Android 码拜 9年前 (2015-11-12) 1635次浏览
		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不行?

这是getString的源码

    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
     */
解决方案:40分
用你的代码稍加修改,测试一切正常:

        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"));//输出:修改的结果,正常

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明android SharedPreferences 的问题,读不到数据。
喜欢 (0)
[1034331897@qq.com]
分享 (0)