Problem with saving checkedtextview state, it misbehaves with multiple items - java

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"));
}

Related

SharedPreferences integer addition

I have a code... Its excellent save data and load data, but... When i reset application, my score loading, but when i click button for +5 score, my score reset and set 5. I am want that addition +5, but its dont work...
I understand that the problem of addition, because save and load working excellent, but addition doesnt work.
Sorry for my bad English :)
int mCounts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appli);
Settings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
int mCounts = Settings.getInt(APP_PREFERENCES_SCORE, 1);
score = (TextView) findViewById(R.id.score);
score.setText(String.valueOf(mCounts));
}
public void five(View view) {
score.setText(String.valueOf(mCounts += 5)+"");
}
public void onPause() {
super.onPause();
SharedPreferences.Editor editor = Settings.edit();
editor.putInt(APP_PREFERENCES_SCORE, mCounts);
editor.apply();
}
Try this code in your button:
public void five(View view) {
score.setText(String.valueOf(mCounts += 5)+"");
SharedPreferences.Editor editor = Settings.edit();
editor.putInt(APP_PREFERENCES_SCORE, mCounts);
editor.apply();
}
Problem is here:
int mCounts = Settings.getInt(APP_PREFERENCES_SCORE, 1);
Remove int. it will work

Saving data in application

I have made an application. It's a button that shows the time you have pressed it. Every time I "kill" the application, the timer starts at 0 again (naturally). How can I make the application save the time the button is pressed, so when the application is killed, and then you open it, the timer is at that time you stopped.I have red some about how this is done, and I think it has something to do with SharedPreferences.
My code:
public class MainActivity extends ActionBarActivity {
Button button1;
Chronometer chromo;
protected long time;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1=(Button)findViewById(R.id.button1);
chromo=(Chronometer)findViewById(R.id.chromo);
button1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
chromo.setBase(SystemClock.elapsedRealtime()+time);
chromo.start();
}
else if( event.getAction() == MotionEvent.ACTION_UP){
time =chromo.getBase()-SystemClock.elapsedRealtime();
chromo.stop();
}
return true;
}
});
}}
Saving in SharedPreferences :
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
// We use an editor to insert values in SharedPreferences
Editor editor = prefs.edit();
// Saving the values
editor.putLong("myTime", time);
// Committing the changes
editor.commit();
Retrieving saved values :
long savedValue = 0l;
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
if (prefs.contains("hello")){
savedValue = sharedpreferences.getLong("myTime", 0l));
}
EDIT :
public class MainActivity extends ActionBarActivity {
Button button1;
Chronometer chromo;
protected long time = 0;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1=(Button)findViewById(R.id.button1);
chromo=(Chronometer)findViewById(R.id.chromo);
prefs = getSharedPreferences("prefs", Context.MODE_PRIVATE);
long savedValue = prefs.getLong("my_chrono", 0);
if(savedValue == 0)
chromo.setBase(SystemClock.elapsedRealtime());
else
chromo.setBase(SystemClock.elapsedRealtime() + savedValue);
button1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
chromo.start();
}
else if( event.getAction() == MotionEvent.ACTION_UP){
time =chromo.getBase()-SystemClock.elapsedRealtime();
chromo.stop();
prefs.edit().putLong("my_chrono", time).apply();
}
return true;
}
});
}}
============================================================================
To use the shared preferences, initialize this in you onCreate
SharedPreferences prefs = getSharedPreferences("the_package_of_your_app", Context.MODE_PRIVATE);
Then, try to get the saved value
int my_saved_value = prefs.getInt("the_package_of_your_app.my_int_1", 0);
if(my_saved_value != 0)
//your value of your timer was saved, do what's needed with it
else
//there was no value saved, or the timer was at 0
Now you have to save that value when needed (when the timer is stopped, or the application is closed)
prefs.edit().putInt("the_package_of_your_app.my_int_1", my_value).apply();
To elaborate on #2Dee's answer:
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
// We use an editor to insert values in SharedPreferences
Editor editor = prefs.edit();
// Saving the values
editor.putLong("myTime", time);
// Committing the changes
editor.commit();
can go into the
protected void onDestroy();
method. This method can be overloaded in an Activity to be called as the activity is destroyed (killed, closed, etc) so that any data may be saved (which is what you want to do).
Likewise,
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
time = sharedpreferences.getLong("myTime", 0l);
can go into the
protected void onCreate(Bundle savedInstanceState);
method. This method is called when the activity is first created. This will set your time to the saved value (defaulting to 0 if there is none).
If for some reason these need to be called at different times (such as later or earlier in the Activity's lifecycle) you can read more about it here.
If you like this answer, please upvote 2Dee's answer as well. Some of the code is literally copy/pasted from there.
Happy Coding! Leave a comment if you have more questions.

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();

Android SharedPreferences is reset to default values. After restarting app

Sometimes after restarting the app resets the sharedpreferences on devices with API level > 13.
The sharedpreferences are set at the beginning of the app (first activity of the app).
code:
Public void saveCountry(Context context, String countryCode) {
SharedPreferences settingsActivity = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settingsActivity.edit();
editor.putString("key_country", countryCode);
editor.commit();
setDefaultChannels(context);
}
public String getCountry(Context mContext) {
SharedPreferences settingsActivity = mContext.getSharedPreferences("preferences", Context.MODE_PRIVATE);
String country = settingsActivity.getString("key_country", null);
return country;
}
I dont know what im doing wrong and why it is happening. I noticed this specially after receiving a push-notification to a detailactivity.
Are you calling the saving methods at the beginning of your app like this?
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saveCountry();
Because if you are, you are calling it every time at startup, so the country will be overridden with whatever data countryCode equals at startup, which could be nothing. So maybe you should have some code that only calls that on first run.
Here is how I have it implemented in my app.
boolean firstRun;
final SharedPreferences firstRunPref = getSharedPreferences(PREFS_NAME, 0);
firstRun = firstRunPref.getBoolean("firstRun", true);
if(firstRun==true){
saveCountry();
SharedPreferences.Editor editor3 = firstRunPref.edit();
editor3.putBoolean("firstRun", false);
editor3.commit();
}

Categories