2016-07-10 10 views
-2

設定アクティビティを作成しましたが、SharedPreferencesでスイッチボタンを保存したいのですが、エラーが発生しましたタイトル)私が活動を開始したとき:nullオブジェクトリファレンスで仮想メソッド 'void android.widget.Switch.setChecked(boolean)'を呼び出そうとしました

エラーが

ライン13にあるコード:

public class SettingsActivity extends Activity { 

    private Switch switchPushNotifications; 

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

     getActionBar().setHomeButtonEnabled(true); 
     getActionBar().setDisplayHomeAsUpEnabled(true); 

     SharedPreferences sharedPreferences = getSharedPreferences("Settings", MODE_PRIVATE); 
     switchPushNotifications.setChecked(sharedPreferences.getBoolean("getPushNotifications", true)); 



     switchPushNotifications = (Switch) findViewById(R.id.switchPush); 
     switchPushNotifications.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       if (isChecked) { 
        Log.d("PN", "Push Notifications are currently ON"); 
        Pushbots.sharedInstance().setPushEnabled(true); 
        Pushbots.sharedInstance().register(); 

        SharedPreferences.Editor sharedPreferencesEditor = getSharedPreferences("Settings", MODE_PRIVATE).edit(); 
        sharedPreferencesEditor.putBoolean("getPushNotifications", true); 
        sharedPreferencesEditor.commit(); 


       } 
       else { 
        Log.d("PN", "Push Notifications are currently OFF"); 
        Pushbots.sharedInstance().setPushEnabled(false); 
        Pushbots.sharedInstance().unRegister(); 

        SharedPreferences.Editor sharedPreferencesEditor = getSharedPreferences("Settings", MODE_PRIVATE).edit(); 
        sharedPreferencesEditor.putBoolean("getPushNotifications", false); 
        sharedPreferencesEditor.commit(); 

       } 
      } 
     }); 

    } 

} 

ありがとう!

switchPushNotifications.setChecked(sharedPreferences.getBoolean("getPushNotifications", true)); 

switchPushNotifications = (Switch) findViewById(R.id.switchPush); 

あなたが最初にそれを初期化し、それを使用する必要があります。

答えて

0

あなたがする必要があるのは、スワップの2行(その順序を変更)です。この方法では、まだnullのメソッドにアクセスしようとしており、NullPointerExceptionです。

関連する問題

 関連する問題