SharedPreferences not saving boolean - java

I am unable to save a boolean value using SharedPreferences. The value is always true for some reason. This is how the value is saved:
settings = getSharedPreferences("UserConfigs", MODE_PRIVATE);
b1 = settings.getBoolean("Gravity", false);
editor = settings.edit();
action_G.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!b1) {
action_G.setImageResource(R.drawable.ic_align_right);
txt.setGravity(Gravity.RIGHT);
editor.putBoolean("Gravity", true);
editor.commit();
} else {
action_G.setImageResource(R.drawable.ic_align_center);
txt.setGravity(Gravity.CENTER);
editor.putBoolean("Gravity", false);
editor.commit();
}
b1 = !b1;
}
});
What is wrong?
EDIT:
change code but pref not saving ?
settings = getSharedPreferences("UserConfigs", MODE_PRIVATE);
editor = settings.edit();
action_G.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (settings.getBoolean("Gravity", false)) {
editor.putBoolean("Gravity", false).apply();
action_G.setImageResource(R.drawable.ic_align_center);
txt.setGravity(Gravity.CENTER);
} else {
editor.putBoolean("Gravity", true).apply();
action_G.setImageResource(R.drawable.ic_align_right);
txt.setGravity(Gravity.RIGHT);
}
}
});

If you need to use a variable from the context of your activity in an anonymous class it needs to be declared final.
Therefore, the b1 variable that is initialized before the onClickListener is not changed after the onClickListener is called.Since, the reference to the inner b1 is not the same as the global b1.
So, Instead of using b1 use settings.getBoolean("Gravity", false); directly.

It happens because on every click in the end you convert your b1 into !b1(b1 != b1) means on every click in there are "Gravity" is saved only as "true".

Related

Problem with saving checkedtextview state, it misbehaves with multiple items

I made an activity consisting of CheckTextView's and TextView's. When the user checks the box, I want to save that state when the user leaves the activity or closes the app.
I added onClickListener to every CTV.
Then I try to save it in onPause and onResume methods. I can't troubleshoot this problem as the checkboxes work when I save just a few of them it works (it varies but it works with 1-5 of them) but when I add all of them they are not saved when I go back to the activity.
//this will always work and will save the state of the boxes
protected void onPause() {
super.onPause();
save(ctv1.isChecked());
save(ctv2.isChecked());
save(ctv3.isChecked());
}
protected void onResume() {
super.onResume();
ctv1.setChecked(load());
ctv2.setChecked(load());
ctv3.setChecked(load());
}
//when I add all of them, they are always either checked or unchecked
//it doesn't matter what combination of them I try, it seems that it is //always working with a couple of CTV's but fails with more than 5-6 of them
//this is how my onClickListener looks like
CheckedTextView ctv1 = (CheckedTextView) findViewById(R.id.ctvFOX1);
ctv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ctv1.isChecked()) {
ctv1.setChecked(false);
}
else {
ctv1.setChecked(true);
}
}
});
//save and load methods
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.apply();
}
private boolean load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", false);
}
Because you only use one key to save the CheckedTextView's value!
private void save(final boolean isChecked, String key) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.apply();
}
private boolean load(String key) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(key, false);
}
protected void onPause() {
super.onPause();
save(ctv1.isChecked(), "check1");
save(ctv2.isChecked(), "check2");
save(ctv3.isChecked(), "check3");
}
protected void onResume() {
super.onResume();
ctv1.setChecked(load("check1"));
ctv2.setChecked(load("check2"));
ctv3.setChecked(load("check3"));
}

How to save states of multiple dynamically generated checkboxes in a list view? (Android Java)

I have an Activity that looks like this - the length of the list view is dynamic and can change;
Now, I have declared and initialized checkboxes based on the length of the array.
I need to save the states of these boxes when the user clicks on "Save". How do I achieve this? I wrote the following code, but I get no input, i.e. even though the checkboxes are initialized, I don't think the activity knows which checkbox declaration is for which checkbox on the activity. Please help - thanks!
cbs = new CheckBox[length];
for (int i=0;i<length;i++){
cbs[i] = new CheckBox(ThisActivity.this);
}
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoOnBtnClick(v);
}
});
}
public void DoOnBtnClick (View v) {
for(int i = 0; i < cbs.length; i++){
if(cbs[i].isChecked()){
selectedCheckboxes.add(toInt(cbs[i].getTag()));
Log.e("GET TAG",Integer.toString(toInt(cbs[i].getTag())));
}
}
}
you can use sharedPreferences to store and retrieve checkbox state data
Initialize variables first:
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Now in your onCreate() after all checkbox are initialized use setOnCheckedChangeListener
Now you can load data from sharedpreferences using this:
public void Load_checklist() {
SharedPreferences shared = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
for(int i = 0; i < cbs.length; i++){
if (shared.getString(Integer.toString(i), "").equals("1")) {
cbs[i].setChecked(true);
}else{
cbs[i].setChecked(false);
}
}
}
finally your onCreate method should look like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_name);
int array_length=jArray.length(); //checkbox size
//layout where you want to dynamically add checkboxes
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.lyout);
Load_checklist();
for(int c=0; c<jArray.length();c++){
CheckBox chk=new CheckBox(this);
chk.setId(c++);
chk.setText("Click to add values");
chk.setTextColor(Color.GRAY);
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
String s="x"+buttonView.getId();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
switch(buttonView.getId()){
case 1: // do something on 1st checkbox
if (isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Integer.toString(c), "1");
editor.commit();
} else {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Integer.toString(c), "0");
editor.commit();
}
break;
case 2: //do something on 2nd checkbox
break;
//And SO ON for all checkboes
}
}
});
linearLayout.addView(chk);
}
}
N.B: If SetId(Int) is not working then you can use setTag(int) instead.
If a CheckBox's Tag should represent its index in the list, you should set that tag when you are instantiating them.
for (int i=0;i<length;i++){
cbs[i] = new CheckBox(ThisActivity.this);
cbs[i].setTag(i);
}
I would not recommend this approach if you expect to have a variable amount of checkboxes due to the performance implications. Instead, consider using a RecyclerView with a backing list of model objects representing the state of your checkboxes.
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html

Save variable in SharedPreferences based on which button is clicked

Im trying to make an EULA for my app, but there is a different EULA for the different countries we work with.
my idea was that i save a String in SharedPreferences like ZA for South Africa and KE for Kenya. So if you click the South Africa button, it will save the string in SharedPreferences as ZA and the same for Kenya. Once the button has been clicked it the new activity will then load the appropriate EULA by pulling the ZA or KE string from the SharedPreferences. This is what i have at the moment:
Country_select.java
public class country_select extends Activity {
private static final String TAG = "Logs";
public static final String PREFS_NAME = "PrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country_select);
final Button za_button = (Button) findViewById(R.id.btn_za);
Button ke_button = (Button) findViewById(R.id.btn_ke);
Log.i(TAG, "created buttons");
za_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "ZA");
editor.commit();
}
});
Log.i(TAG, "set button settings for ZA");
ke_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "KE");
editor.commit();
}
});
Log.i(TAG, "set button settings for KE");
}
I may have this totally incorrect but on the layout file there are 2 buttons, one for KE and one for ZA.
I would like it, when the new activity is loaded to read SharedPreferences whether it has ZA or KE? Is what i have done here correct?
Thank you
I think you're better off with using IntentExtras, in your first activity upon clicking the country button store the value inside a variable and when you want to start the new activity pass the data as an intent extra:
Intent intent= new Intent(getActivity(), NewActivity.class);
intent.putExtra("country", countryCode);
startActivity(intent);
And then inside the new activity you can retrieve the value like this:
String countryCode = getIntent().getExtras().getString("country");
In order to maintain Shared preference across the application i use it this way
, take a look
I saved a AppPrefes class as a seprate class in the package
public class AppPrefes {
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPrefes(Context context, String Preferncename) {
this.appSharedPrefs = context.getSharedPreferences(Preferncename,
Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
/****
*
* getdata() get the value from the preference
*
* */
public String getData(String key) {
return appSharedPrefs.getString(key, "");
}
public Integer getIntData(String key) {
return appSharedPrefs.getInt(key, 0);
}
/****
*
* SaveData() save the value to the preference
*
* */
public void SaveData(String Tag, String text) {
prefsEditor.putString(Tag, text);
prefsEditor.commit();
}
public void SaveIntData(String key, int value) {
prefsEditor.putInt(key, value);
prefsEditor.commit();
}
/**
* delete all AppPreference
*/
public void deleteAll() {
this.prefsEditor = appSharedPrefs.edit();
this.prefsEditor.clear();
this.prefsEditor.commit();
}
In your Activity or Fragment were you would like to get or save data just use it like this
Decalre an object for the AppPrefes class
AppPrefes appPref;
Initialize in onCreate
appPref = new AppPrefes(getActivity(), "type name of your preference");
To save data to the preference use
appPref.SaveData("tag_name", "value to be saved);
To get data from the preference
appPref.getData("tag_name");
You can also save Integer values and clear all preference values if necessary just call the apporopriate methods.
Yes, the storing part is correct. Now you will need to access the stored value in your new activity.
Example-
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String storedCountry = sharedpreferences.getString("Country_Selected"); // could be null value if there is no value stored with Country_Selected tag.

Saving the checked button state when back button pressed or app exited with SharedPreferences and onCheckChangeListener

I am trying to make an android app that allows users to block apps for a specific period of time. So I have a listview of installed apps in a fragment with a switch button next to it.
I want it to stay checked when the user checks its or unchecks it after they press back and exit the app.
I am trying to achieve this using setOnCheckedChangeListener and Shared Preferences; however; I am having trouble saving the button state in my BaseAdapter class.
holder.ck1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (holder.ck1.isChecked()) {
//itemChecked[position] = true;
b = true;
holder.ck1.setChecked(b);
Log.i("This is", " checked: " + position);
SharedPreferences.Editor editor = context.getSharedPreferences("com.ibc.android.demo.appslist.app", Context.MODE_PRIVATE).edit();
editor.putBoolean("checkBox1", b);
editor.commit();
} else {
//itemChecked[position] = false;
b= false;
holder.ck1.setChecked(b);
Log.i("This is", " not checked: " + position);
SharedPreferences.Editor editor = context.getSharedPreferences("com.ibc.android.demo.appslist.app", Context.MODE_PRIVATE).edit();
editor.putBoolean("checkBox1", b);
editor.commit();
}
}
});
sharedPrefs = context.getSharedPreferences("PACKAGE_NAME", Context.MODE_PRIVATE);
holder.ck1.setChecked(sharedPrefs.getBoolean("checkBox1",false));
// I think that maybe instead of false I should put the boolean b I defined in the method but I am not sure how to get it .
return convertView;
}
How I do I modify this to reach to desired result?
I think whenever the activity created it automatically calls onCheckedChange and your SharedPreferences overwrite by default values. so I think you can use onStop to update the SharedPreferences.
holder.ck1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b)
{
SharedPreferences.Editor editor = context.getSharedPreferences("PACKAGE_NAME", Context.MODE_PRIVATE).edit();
editor.putBoolean(pakagename, b);
editor.commit();
}
});
sharedPrefs = context.getSharedPreferences("PACKAGE_NAME", Context.MODE_PRIVATE);
holder.ck1.setChecked(sharedPrefs.getBoolean(pakagename,false));
return convertView;
}
pakagename holds the package name of that particular listitem. Otherwise if you are targeting above api level 11, you can use a set in sharedpreferences to store all the checked package names. This is the easy way. Otherwise you can save the list of checked applications in a database.
I have achieved the requested feature. Check my code:
final SharedPreferences sharedPreferences = getSharedPreferences("conditionCheck", MODE_PRIVATE);
switchCompat.setChecked(sharedPreferences.getBoolean("switchCondition",false));
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences sharedPreferences = getSharedPreferences("conditionCheck", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (switchCompat.isChecked()) {
Toast.makeText(getApplicationContext(), "Checked Condition True", Toast.LENGTH_LONG).show();
editor.putBoolean("switchCondition",switchCompat.isChecked());
editor.commit();
} else {
Toast.makeText(getApplicationContext(), "Checked Condition False", Toast.LENGTH_LONG).show();
editor.putBoolean("switchCondition",switchCompat.isChecked());
editor.commit();
}
}
});

Sharedpreferences toggle state?

I have a toggle that change the brightness in my device from manual to authomatic. It works but the state of button doesn't save.. There are two things i need right now.
1) Save the button state using sharedpreferences
2) Check when i open the application which kind of brightness there is in the phone.
This is the toggle in my onCreate:
autoBrightToggle = (ToggleButton)v.findViewById(R.id.luminosita);
autoBrightToggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (autoBrightToggle.isChecked()) {
setAutoBrightness(true);
} else {
setAutoBrightness(false);
}
}
});
and the method:
void setAutoBrightness(boolean value) {
if (value) {
Settings.System.putInt(getActivity().getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
} else {
Settings.System.putInt(getActivity().getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
}
}
i tryied in this way but not works:
sPrefdata = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
ToggleButton autoBrightToggle = (ToggleButton) findViewById(R.id.brightoggle); //Dichiaro il toggle
boolean togglebrightness = sPrefdata.getBoolean("DATA", false); a
if (togglebrightness ) //if (tgpref) may be enough, not sure
{
autoBrightToggle .setChecked(true);
}
else
{
autoBrightToggle .setChecked(false);
}
and so in the onClick
SharedPreferences sPref = getSharedPreferences(PREFS_NAME, 0);
Editor editor = sPref.edit();
editor.putBoolean("DATA", true); //or false
editor.apply();
but doesn't work. Doesn't save the state and the method stops works. How can i solve? And how can i check which is the actual brightness?
Try the snippet given below, I've used it to save strings in shared preferences.
SharedPreferences.Editor ed = getSharedPreferences("DATA", 0).edit();
ed.putBoolean("DATA", true);
ed.commit();

Categories