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



我是Android Studio的新手,并学习如何创建共享的Preference变量。我一直坚持下去,更新sharedPreference中字符串的值时,当我执行以下代码下方时,会增加NullPointerException。任何帮助都感激不尽。预先感谢。

这是我的设置

@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");
    }
}

这是MainAttivity

@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)

您不应在varAcrossApp = this.getSharedPreferences(SP, Context.MODE_PRIVATE);

之前致电varAcrossApp.getInt

这是可以/可以在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

最新更新