Android: get checkbox value from another activity with shared preferences, nullPointerException

32 views Asked by At

I am trying to access the value of a checkbox (MainActivity2) from another activity (MainActivity) with sharedPreferences.

Since I want to save the checkbox status, I am using sharedPreferences anyway. Therefore I have a boolean-method getBooleanFromPref(key), which gives the correct output in MainActivity2. However, when I call this method in MainActivity, I get a nullPointerException. My question: Can anybody explain me, why I am getting a nullpointerExpection? Here's my code: MainActivity:

public class MainActivity extends AppCompatActivity {
    private Button buttonResult, buttonActivity2;
  
private TextView tv_cb;
  
private MainActivity2 mainActivity2 = new MainActivity2();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        buttonResult = findViewById(R.id.btn_result);
        buttonActivity2 = findViewById(R.id.btn_goToAct2);
        tv_cb = findViewById(R.id.tv_cb);
    
    
        buttonActivity2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), MainActivity2.class));
            }
        });
    
        buttonResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_cb.setText(String.valueOf(mainActivity2.getBooleanFromPref("checkedCB")));
            }
        });
    }
}

MainActivity2:

public class MainActivity2 extends AppCompatActivity {
    private CheckBox checkBox;
  
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
  
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
    
        checkBox = findViewById(R.id.checkBox);
        button = findViewById(R.id.btn_back);
    
        //--------------------------------------Shared Prefs-----------------------------------------------
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = preferences.edit();
    
        //--------------------------------------Shared Prefs for Checkbox----------------------------------------------------------
        if (preferences.contains("checkedCB") && preferences.getBoolean("checkedCB", false) == true) {
            checkBox.setChecked(true);
        } else {
            checkBox.setChecked(false);
        }
    
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (checkBox.isChecked()) {
                    editor.putBoolean("checkedCB", true);
                    editor.apply();
                    checkBox.setChecked(true);
                } else {
                    editor.putBoolean("checkedCB", false);
                    editor.apply();
                    checkBox.setChecked(false);
                }
            }
        });
    
          button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity2.this, "Checkbox-Status: " + String.valueOf(getBooleanFromPref("checkedCB")), Toast.LENGTH_SHORT).show();
                startActivity(new Intent(getApplicationContext(), MainActivity.class));
            }
        });
    }
    
    public boolean getBooleanFromPref(String key){
        return preferences.getBoolean(key, false);
    }
}

P.S.: The boolean method getBooleanFromPref is working fine within Mainactivity2.

So far i tried different ways to access the checkbox value from MainActivity2: I created a getter-method in MainActivity2 for the checkbox value. When I call this method from Activity, I don't get the current value of the checkbox. When I use an intent, it's the same problem. I also changed the manifest-value for android-backup: android:allowBackup="false"

The nullPointerException happens, when I try to access the getBooleanFromPref-method from MainActivity:

java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.content.SharedPreferences.getBoolean(java.lang.String, boolean)' on a null object reference
        at com.example.checkbox_test.MainActivity2.getBooleanFromPref(MainActivity2.java:66)
        at com.example.checkbox_test.MainActivity$2.onClick(MainActivity.java:38)
        at android.view.View.performClick(View.java:7441)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1211)
1

There are 1 answers

0
Mc_Android On

In MainActivity2 I have changed the definition of sharedPreferences:

//-----------------------Shared Prefs---------------------

preferences = getSharedPreferences("KEY", 0);
editor = preferences.edit();

As well as in MainActivity:

buttonResult.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SharedPreferences pref = getSharedPreferences("KEY", 0);
        boolean a = pref.getBoolean("checkedCB", false);
        tv_cb.setText(String.valueOf(a));
    }
});