0
I happen to want to leave the Checkbox except as agreed the user marks or not. Then I called a method to make the internet check in case the Checkbox is marked, and soon after the Checkbox was mentioned in the onResume to be updated mainly the internet check in case the user leaves and returns the application, only when mentioned the onResume undo the checked option, see only:
checkBox = (CheckBox) findViewById(R.id.checkNetwork);
checkBox.setChecked(getFromSP("checkBox"));
checkBox.setOnCheckedChangeListener(this);
checkBox2 = (CheckBox) findViewById(R.id.checkAlertDownload);
checkBox2.setChecked(getFromSP("checkBox22"));
checkBox2.setOnCheckedChangeListener(this);
checkBox3 = (CheckBox) findViewById(R.id.checkAutoInstall);
checkBox3.setChecked(getFromSP("checkBox33"));
checkBox3.setOnCheckedChangeListener(this);
...
private boolean getFromSP(String key) {
SharedPreferences preferences = getApplicationContext
().getSharedPreferences("PROJECT_NAME", Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key, boolean value) {
SharedPreferences preferences = getApplicationContext
().getSharedPreferences("PROJECT_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
switch (buttonView.getId()) {
case R.id.checkNetwork:
saveInSp("checkBox", isChecked);
checkConnection();
break;
case R.id.checkAlertDownload:
saveInSp("checkBox22", isChecked);
break;
case R.id.checkAutoInstall:
saveInSp("checkBox33", isChecked);
break;
}
}
private void checkConnection(){
boolean isConnected = myNet.isConnected();
showSnackBar(isConnected);
}
private void showSnackBar(boolean isConnected){
String message;
int color;
if (isConnected) {
message = "Good! Connected to internet";
color = Color.WHITE;
} else {
message = "Sorry! Not connected to internet";
color = Color.RED;
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
@Override
protected void onResume(){
super.onResume();
checkBox.setChecked(getFromSP("Key");
MyApplication.getInstance().setConnectivityListener(this);
}
@Override
public void onNetworkConnectionChanged(boolean isConnected){
showSnackBar(isConnected);
}
}
I think it’s because in onResume is calling the method getFromSP, where you’re returning to false - No options checked in case I change to true - The Checkbox mentioned in onResume is always marked. Can someone help me? I’ve been racking my brain for a long time. Thank you very much!
In onResume you use the code 'checkbox.setChecked(getFromSP("Key");' but you do not save anything with "Key". You must use the same key (key) you used to save Boolean. In your example you save only with the keys "checkbox", "checkBox22" and "checkBox33".
– Rafael Neiva
And ideally you would create a constant in your class to define these keys and not pass any string directly. ;)
– Rafael Neiva