值没有进入共享首选项,总是默认值即将到来

时间:2014-08-06 11:09:01

标签: android sharedpreferences

我使用以下代码

在sharedpreferences中存储一个值
                 SharedPreferences sp;
       sp = getApplicationContext().getSharedPreferences("myshare",
                                 MODE_PRIVATE);
                 Editor e = sp.edit();
                 e.putString("a","unni");
                 e.commit();

这是在AddBluetooth活动中

现在我从另一个名为Dashboard Activity的活动中检索该值,该活动使用以下代码

  SharedPreferences sp;
  sp = getApplicationContext().getSharedPreferences("myshare",
                 MODE_PRIVATE);
  String aa =sp.getString("a","me");

但它只返回默认值,我该如何解决此问题

3 个答案:

答案 0 :(得分:0)

如果您在preferences.xml中定义偏好设置,则需要使用SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

来访问它

答案 1 :(得分:0)

  // declare this class variable in class from where u will put the string u wanna store in shared pref 

    //class variables

        SharedPreferences pref;
        SharedPreferences.Editor editor;
    -------------------

    //in oncrete method
    // declare this in oncreate method 

            pref = getSharedPreferences("testapp", MODE_PRIVATE);
            editor = pref.edit();

    // the varibale u wanna put use the below statements 
    // for string use putString
    // for boolean as u need use putBoolean 
    // have a look at the various option it offers..


    editor.putString("selected", "nil");
    editor.commit();


    // here is the statement use this statement in class where u wanna retireve ur strings
    // use getBoolean for Boolean variables 

    pref.getString("selected", "nil")

    // here in sceond parameter in above statement is : if the value u r requesting for that is specified in first parameter is not present then it will return the //value which is your second parameter..

Pull Ur Shared-Pref: 转到数据 - >数据 - > Ur包 - >拉SharedPref文件[DDMS]

答案 2 :(得分:0)

实际上对我来说,上面的代码片段在API 19中不起作用,但对于较低版本,它的工作原理。所以我用了,

 SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
             SharedPreferences.Editor editor=saved_values.edit();
                 editor.putString("newCEAAddress", address);    
                 editor.commit();

获取价值

  SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    DEVICE_ADDRESS=saved_values.getString("newCEAAddress", "nil");