无法获取.edit()和.apply()来更新值

时间:2019-06-24 04:11:31

标签: java android

我是Android Studio的新手,正在学习如何创建SharedPreference变量。我被困住了,当我执行以下代码时,更新SharedPreference中字符串的值会引发NullPointerException。任何帮助都感激不尽。预先感谢。

这是我的SettingPage

@Override //Creating the setting page
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.settingpage);

    setMinsBar = findViewById(R.id.numMinsBar);
    setTimeEnterButton = findViewById(R.id.setTimeButton);
    musicYesSwitch = findViewById(R.id.musicSwitch);
    soundYesSwitch = findViewById(R.id.soundSwitch);
    minsLeftTV = findViewById(R.id.minsLeftTV);
    timerEndsTV = findViewById(R.id.timerEndsTV);

    varAcrossApp = this.getSharedPreferences(SP, Context.MODE_PRIVATE);


    //Setting on click listener for the enter button for the time set
    setTimeEnterButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            timeInInt = Integer.parseInt(setMinsBar.getText().toString());
            saveData();

        }
    });

    }


public void saveData(){ //Declaring method saveData
    varEditor = varAcrossApp.edit();
    varEditor.putInt(timeInStringSP, timeInInt);
    varEditor.putBoolean(musicYesSP, musicYesSwitch.isChecked());
    varEditor.putBoolean(soundYesSP, soundYesSwitch.isChecked());

    varEditor.apply();

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

public void loadData(){ //Declaring method loadData

    finalTimeInMins = varAcrossApp.getInt(timeInStringSP, 0);
    musicYes = varAcrossApp.getBoolean(musicYesSP, false);
    soundYes = varAcrossApp.getBoolean(soundYesSP, false);
}


public void updateView() {
    minsLeftTV.setText(finalTimeInMins);

    if (musicYes = true) {
        timerEndsTV.setText("-Turn off music");
    } else if (soundYes = true) {
        timerEndsTV.setText("-Change sound profile to 'Sound'");
    } else if (musicYes && soundYes) {
        timerEndsTV.setText("-Turn off music /n-Change sound profile to 'Sound'");
    } else {
        timerEndsTV.setText("-Do nothing");
    }
}

这是MainActivity

@Override //Creating the app here
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homepage);

    startButton = findViewById(R.id.startButton);

    SettingPage settingPage = new SettingPage();
    settingPage.loadData();
    settingPage.updateView();
}

错误代码和堆栈跟踪如下:

Process: com.example.sleep, PID: 6935
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sleep/com.example.sleep.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7319)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
     Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference
        at com.example.sleep.SettingPage.loadData(SettingPage.java:77)
        at com.example.sleep.MainActivity.onCreate(MainActivity.java:25)
        at android.app.Activity.performCreate(Activity.java:7783)
        at android.app.Activity.performCreate(Activity.java:7772)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3235)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7319) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)

1 个答案:

答案 0 :(得分:0)

您不应该在varAcrossApp.getInt之前致电varAcrossApp = this.getSharedPreferences(SP, Context.MODE_PRIVATE);

这是应该/可以在Android中使用共享首选项的方式。

class SettingsSpDao { // shared preferences data access object
    private static final String SP = "SP";
    private static final String MUSIC_YES = "music_yes";

    public static boolean isMusicYes(Context context) {
        // you can initialize sp beforehand so you don't have to pass in context but I prefer it this way, so I don't have to initialize it before using it 
        SharedPreferences sp = context.getSharedPreferences(SP, Context.MODE_PRIVATE); 
        return sp.getBoolean(MUSIC_YES , false);
    }

    // add your methods here
}

// call it anywhere as long as you can pass a context, such as Activity.
musicYes = SettingsSpDao.isMusicYes(this); // in your case `this` since it's in an Activity