Reputation: 971
In my mainActivity I'm trying to read the value of a checkbox in another activity. I however seem to get the opposite of what the value actually is. I suspect the problem is that I'm trying to get the value before I've opened the activity containing the checkbox.
In my mainActivity I have a
public boolean checkValue;
that I want to give the value of the checkbox in the other activity like this
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkValue = SettingsActivity.getCheckValue();
}
which I later use like this
public class JSONTask extends AsyncTask<String, String, String >{
...
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
checkValue = SettingsActivity.getCheckValue();
if(checkValue != true) {
TextView1.setVisibility(View.VISIBLE);
}
else{
TextView1.setVisibility(View.INVISIBLE);
}
The other activity looks like this
public class SettingsActivity extends AppCompatActivity {
private static CheckBox checkBox1;
public static boolean checkStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
checkBox1 = (CheckBox) findViewById(R.id.checkBox);;
loadSavedPreferences();
savePreferences("CheckBox_Value", checkBox1.isChecked());
checkStatus = checkBox1.isChecked();
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", true);
if (checkBoxValue) {
checkBox1.setChecked(true);
} else {
checkBox1.setChecked(false);
}
}
private void savePreferences(String key, boolean value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
@Override
public void onDestroy(){
super.onDestroy();
savePreferences("CheckBox_Value", checkBox.isChecked());
}
public static Boolean getCheckValue(){
return checkStatus;
}
I suspect a solution could be to initialize the settingActivity before opening it in the app, not sure if this is possible though.
Upvotes: 0
Views: 73
Reputation: 11749
Your assumption is correct. If you call getCheckValue before creating your activity, you are just going to get the default value of your static variable checkStatus. Usually you don't want to mix your logic with your UI. Why not getting the correct value directly from your shared preference? You are already doing that in loadSavedPreferences().
Instead of calling checkValue = SettingsActivity.getCheckValue();
Call:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
ceckValue = sharedPreferences.getBoolean("CheckBox_Value", true);
Upvotes: 2