SharedPreferences 上的空指针异常

null pointer exception on SharedPreferences

用户第一次打开我的应用程序时,可能无法创建 SharedPreferences。 所以我想检查 SharedPreferences 是否有值,如果它没有值(即 SharedPreferences 尚未创建)然后创建它并设置它的值。

这是我的代码:

public static final String PROTECT_STATE = "PROTECT";

@SuppressWarnings("null")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // set/check preference 

    SharedPreferences  protectState = null;
    Editor protectEditor;        

    String isprotectStateSet=protectState.getString("protect_state", "off");
    if(isprotectStateSet == "off"){
        protectState = getSharedPreferences(PROTECT_STATE, Context.MODE_PRIVATE);
        protectEditor=protectState.edit();
        protectEditor.putString("protect_state", "on");
        protectEditor.commit();

        Toast.makeText(getApplicationContext(), "set", Toast.LENGTH_SHORT).show();
    }

我在下一行收到空指针异常。

String isprotectStateSet=protectState.getString("protect_state", "off");

您需要先打开 SharedPreferences 才能阅读它们。

移动

  protectState = getSharedPreferences(PROTECT_STATE, Context.MODE_PRIVATE);

这条线以上

  String isprotectStateSet=protectState.getString("protect_state", "off");

替换

SharedPreferences  protectState = null;
Editor protectEditor; 

SharedPreferences  protectState = PreferenceManager.getDefaultSharedPreferences(this);
Editor protectEditor = protectState.edit(); 

更新:

isprotectStateSet == "off"

错了。阅读 this

因为您将 protectState 设置为 null 那么您正试图从它 getString 当它为 null 时,这是 SharedPreferences protectState = null;