按下后退按钮时,SwitchCompat状态发生变化

时间:2015-01-26 06:23:10

标签: java android toggle sharedpreferences back-button

我在ActionBar中有一个SwitchCompat小部件。

当按下后退按钮并“重新打开”应用程序时,SwitchCompat会丢失状态,从开启到关闭。

我正在实现前台,但这并不妨碍SwitchCompat更改状态。

我尝试使用SharedPreferences但应用程序崩溃。

MainActivity.java

SwitchCompat switchService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

switchService = (SwitchCompat) findViewById(R.id.toggleButton);

    LoadPreferences();
}

private void SavePreferences(){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("state", switchService.isEnabled());
    editor.apply();   // I missed to save the data to preference here,.
}

private void LoadPreferences(){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    Boolean  state = sharedPreferences.getBoolean("state", false);
    switchService.setEnabled(state);
}

@Override
public void onBackPressed() {
    SavePreferences();
    super.onBackPressed();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    MenuItem item = menu.findItem(R.id.toggle_ButtonL);
    MenuItemCompat.getActionView(item).findViewById(R.id.toggleButton);
    switchService = (SwitchCompat) MenuItemCompat.getActionView(item);
    switchService.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if (isChecked) {
                // Creates SMSMonitorService intent
                Intent SMSMonitorIntent = new Intent(MainActivity.this, SMSMonitorService.class);
                // Start SMSMonitorService
                startService(SMSMonitorIntent);
                Log.i(DEBUG_TAG, "SMSMonitor Started");

            } else {
                // Creates SMSMonitorService intent
                Intent SMSMonitorIntent = new Intent(MainActivity.this, SMSMonitorService.class);
                // Stop SMSMonitorService
                stopService(SMSMonitorIntent);
                Log.i(DEBUG_TAG,"SMSMonitor Stopped");
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.toggle_off), Toast.LENGTH_SHORT).show();
            }
        }
    });

    return true;
}

logcat的:

01-25 23:41:07.995    1341-1341/com.test.wikitext E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.test.wikitext, PID: 1341
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.wikitext/com.test.wikitext.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SwitchCompat.setEnabled(boolean)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SwitchCompat.setEnabled(boolean)' on a null object reference
        at com.test.wikitext.MainActivity.LoadPreferences(MainActivity.java:249)
        at com.test.wikitext.MainActivity.onCreate(MainActivity.java:73)
        at android.app.Activity.performCreate(Activity.java:5933)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)    
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)  

(继续)

如何保存SwitchCompat的状态,当按下后退按钮时,这不会失去现状?

2 个答案:

答案 0 :(得分:1)

我知道我迟到了,但这可能有助于其他人

嗨,就像你一直在寻找答案,答案就在你的问题中,只需更换以下代码

在OnCreateOptionsMenu中更改代码

MenuItem item = menu.findItem(R.id.toggle_ButtonL);
MenuItemCompat.getActionView(item).findViewById(R.id.toggleButton);
switchService = (SwitchCompat) MenuItemCompat.getActionView(item);

MenuItem item = menu.findItem(R.id.toggle_ButtonL);
 switchService = (SwitchCompat)MenuItemCompat.getActionView(item).findViewById(R.id.toggleButton);

这样就可以了。现在我们可以摆脱那个NullPointerException

答案 1 :(得分:0)

您必须删除

switchService = (SwitchCompat) findViewById(R.id.toggleButton);

LoadPreferences();

来自onCreate方法,因为SwitchCompat不在您的布局中且位于actionBar上。然后在

之后拨打LoadPreferences();
 switchService = (SwitchCompat) MenuItemCompat.getActionView(item);