如何在Android中使用共享首选项?

时间:2013-11-28 09:50:11

标签: java android

我正在Android中使用SQLite实现切换按钮。我想在共享首选项中保存切换按钮值,并在SQLite中存储共享首选项值。当我运行应用程序时,我有切换按钮的Null Pointer Exception。

我不知道如何在共享prefs中存储布尔值。这是我的代码和日志猫。

这是我的Toggle ButtonCode

toggleButton_Addto_Contacts = (ToggleButton) findViewById(R.id.toggleButton_Add_To_Contacts);

toggleButton_Addto_Contacts.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub


        if(isChecked)
        {
            System.out.println("Toggle Button Is On");

            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("YES",  true); // value to store
            strBooleanValue=sharedPref.getBoolean("YES",true);
            strToggleVlaue=String.valueOf(strBooleanValue);
            System.out.println("Toggle Button Value Is =" + strToggleVlaue);
            editor.commit();

        }
        else
        {

                System.out.println("Toggle Button Is Off");
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("NO",  false); // value to store
                strBooleanValue=sharedPref.getBoolean("NO", false);
                strToggleVlaue=String.valueOf(strBooleanValue);
                System.out.println("Toggle Button Value Is =" + strToggleVlaue);
                editor.commit();

        }
    }
});



11-28 15:13:26.054: E/AndroidRuntime(707): FATAL EXCEPTION: main
11-28 15:13:26.054: E/AndroidRuntime(707): java.lang.NullPointerException
11-28 15:13:26.054: E/AndroidRuntime(707):  at com.lead_management_project.New_Lead_Activity5$5.onCheckedChanged(New_Lead_Activity5.java:172)
11-28 15:13:26.054: E/AndroidRuntime(707):  at android.widget.CompoundButton.setChecked(CompoundButton.java:124)
11-28 15:13:26.054: E/AndroidRuntime(707):  at android.widget.ToggleButton.setChecked(ToggleButton.java:69)
11-28 15:13:26.054: E/AndroidRuntime(707):  at android.widget.CompoundButton.toggle(CompoundButton.java:86)
11-28 15:13:26.054: E/AndroidRuntime(707):  at android.widget.CompoundButton.performClick(CompoundButton.java:98)
11-28 15:13:26.054: E/AndroidRuntime(707):  at android.view.View$PerformClick.run(View.java:9080)
11-28 15:13:26.054: E/AndroidRuntime(707):  at android.os.Handler.handleCallback(Handler.java:587)
11-28 15:13:26.054: E/AndroidRuntime(707):  at android.os.Handler.dispatchMessage(Handler.java:92)
11-28 15:13:26.054: E/AndroidRuntime(707):  at android.os.Looper.loop(Looper.java:123)
11-28 15:13:26.054: E/AndroidRuntime(707):  at android.app.ActivityThread.main(ActivityThread.java:3683)
11-28 15:13:26.054: E/AndroidRuntime(707):  at java.lang.reflect.Method.invokeNative(Native Method)
11-28 15:13:26.054: E/AndroidRuntime(707):  at java.lang.reflect.Method.invoke(Method.java:507)
11-28 15:13:26.054: E/AndroidRuntime(707):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-28 15:13:26.054: E/AndroidRuntime(707):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-28 15:13:26.054: E/AndroidRuntime(707):  at dalvik.system.NativeStart.main(Native Method)

4 个答案:

答案 0 :(得分:1)

尝试改变如下,

    if(isChecked)
            {
                System.out.println("Toggle Button Is On");

                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("YES",  true); // value to store
                editor.commit();
                strBooleanValue=preferences.getBoolean("YES",true);
                strToggleVlaue=String.valueOf(strBooleanValue);
                System.out.println("Toggle Button Value Is =" + strToggleVlaue);


            }
 else
        {

                System.out.println("Toggle Button Is Off");
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("NO",  false); // value to store
                editor.commit();
                strBooleanValue=preferences.getBoolean("NO", false);
                strToggleVlaue=String.valueOf(strBooleanValue);
                System.out.println("Toggle Button Value Is =" + strToggleVlaue);


        }

答案 1 :(得分:0)

您没有在代码中的任何位置初始化preferencessharedPref,而您正在获得NullPointerException

在下面的代码中也有不对的地方: -

editor.putBoolean("YES",  true); // value to store
strBooleanValue=sharedPref.getBoolean("YES",true);

您必须先致电commit(),然后尝试访问您在偏好设置中输入的值。

答案 2 :(得分:0)

请参阅以下答案

   creating sharedpreferences
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
    Editor editor = pref.edit();

    Storevalues
    editor.putBoolean("key_name", true); // Storing boolean - true/false
    editor.putString("key_name", "string value"); // Storing string
    editor.putInt("key_name", "int value"); // Storing integer
    editor.putFloat("key_name", "float value"); // Storing float
    editor.putLong("key_name", "long value"); // Storing long

   editor.commit(); // commit changes

  retrive from shared preference

    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
   pref.getString("key_name", null); // getting String
   pref.getInt("key_name", null); // getting Integer
   pref.getFloat("key_name", null); // getting Float
   pref.getLong("key_name", null); // getting Long
  pref.getBoolean("key_name", null); // getting boolean

答案 3 :(得分:0)

setContentView之后只需调用loadSavedPreferences()

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setting);
         loadSavedPreferences();
          //remaining code
 }

并在onCheckedChanged

中调用savePreferences(布尔切换)
   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    // TODO Auto-generated method stub
      savePreferences(Boolean toggle);
  if(isChecked)
    {
        System.out.println("Toggle Button Is On");
        System.out.println("Toggle Button Value Is =" + strToggleVlaue);


    }
    else
    {

            System.out.println("Toggle Button Is Off");
            System.out.println("Toggle Button Value Is =" + strToggleVlaue);


    }
}
 });


private void loadSavedPreferences() {
            SharedPreferences sharedPreferences =PreferenceManager.getDefaultSharedPreferences(this);
            strToggleVlaue==getBoolean("Checked_State",true);
        }

  private void savePreferences(Boolean toggle) {

            SharedPreferences sharedPreferences  PreferenceManager.getDefaultSharedPreferences(this);
            Editor editor = sharedPreferences.edit();
            editor.putBoolean("Checked_State",toggle);
             editor.commit();

        }

注意:为共享首选项编写一个单独的方法来加载和保存,以便将来在您希望保存任何其他值时可以轻松修改这些函数。