Saving state of CheckBoxes - android

Please help me! Checkbox does not save state after restarting the app
I have a ListView with CheckBoxes and I want that when user selects any check box and closes the application, and again opens the application, the same CheckBoxes should be selected. i.e I have to save the state of the CheckBoxes
// custom BaseAdapter class
...
boolean [] itemChecked;
//getView ...
//getSharedPreferences
sharedPrefs = context.getSharedPreferences(PACKAGE_NAME, Context.MODE_PRIVATE);
//Click ckeckbox
viewHolder.check_task.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME , false));
viewHolder.check_task.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//SharedPreferences
SharedPreferences.Editor editor = context.getSharedPreferences(PACKAGE_NAME , Context.MODE_PRIVATE).edit();
if (viewHolder.check_task.isChecked()) {
//if value is false
itemChecked[i] = true;
viewHolder.check_task.setChecked(true);
//put True
editor.putBoolean(PACKAGE_NAME, true);
editor.apply();
} else {
//if value is false
itemChecked[i] = false;
viewHolder.check_task.setChecked(false);
//put False
editor.putBoolean(PACKAGE_NAME, false);
editor.apply();
}}}); return myView; }

You are always setting the last checked box state in shared preferences since you are using the same key each time. If you want to set multiples you would have to define a new key for each boolean using something like editor.putBoolean(PACKAGE_NAME + index, true); then retrieve it using the same logic. This will result in each index having an entry in shared preferences. Another approach would be to use GSON to save the entire array in onPause and restore it when the app is relaunched.

Related

Cant remember the state of toggle button in a listview

I want to remember the state of the toggle button in a listview whenever i pressed the toggle button.
I tried using shared preferences to remember the toggle button state based on the item position but it did not work. However i think theres a problem doing so as if i delete one of the item from the listview, the position might get changed.
// getting the toggle button state using shared preference
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
Boolean runstopChecked = sharedPreferences.getBoolean("pref_runstop", false);
viewHolder.tbtnJobRunStop.setChecked(runstopChecked);
// Saving the position and toggle button state
viewHolder.tbtnJobRunStop.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("pref_runstopposition", position);
if(isChecked)
{
runJobId = dataModel.getJobId();
editor.putBoolean("pref_runstop", true);
editor.apply();
Intent statusIntent = new Intent(getContext(), RefreshJobService.class);
statusIntent.putExtra("id", runJobId);
getContext().startService(statusIntent);
} else
{
stopJobId = dataModel.getJobId();
editor.putBoolean("pref_runstop", false);
editor.apply();
stopJob stopjob = new stopJob();
stopjob.execute();
Intent i = new Intent("stopjob");
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(i);
i.putExtra("stopJobId",stopJobId);
getContext().sendBroadcast(i);
}
}
});
I think your approach is wrong you should create another ArrayList in which you will store all the clicked buttons position in the listview. And, in onBindViewHolder method, you have to check if the ArrayList contains a particular position, if yes set the button state pressed or unpressed.
Hope it helps!
pass a List of models to your listview and the model will contain the values and checked tag
public class MyPojo{
private String myValue="";
private boolean isChecked = false;
// set your getter and setter here
}
in your viewHolder of your listview check if the item.isChecked true make toggle on else false when the toggle checked set isChecked of the current position as true else set false if you want to save the status of your list better to use DB maybe Room or ObjectBox because sharedPrefernce use for only one value

using sharedpreferences to remember textview hidden after it's clicked

I have a textview that when user clicks it, I want it to be invisible. But I want it to stay invisible, even after user has reloaded the app, using "sharedpreferences". How to get shared preferences working and then recalled correctly?
This is my code for storing the preference when user clicks the textview:
textView.setVisibility(View.INVISIBLE);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("was_clicked", true);
editor.commit(); // commit changes
So I understand this will store a true/false boolean in shared preferences called" was_clicked".
But now how do I have it checked for "true" in the onCreate method of the activity and then have it set TextView to view.INVISIBLE if was_clicked = true?
Check out this article. But to answer your question specifically
if (getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE).getBoolean("was_clicked", false))
textView.setVisibility(View.INVISIBLE);
You can check the value using this method:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean wasClicked = pref.getBoolean("was_clicked",false);
if (wasClicked){
textView.setVisibility(View.INVISIBLE);
}else {
textView.setVisibility(View.VISIBLE);
}
In your onCreate method you should create preferences and read from them like this:
static final String PREFERENCES_NAME = "MyPref";
static final String WAS_CLICKED_NAME = "was_clicked";
#Override
void onCreate()
{
SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE);
boolean invisible = preferences.getBoolean(WAS_CLICKED_NAME, false); // 2nd argument is the default value
if (invisible)
{
textView.setVisibility(View.INVISIBLE);
}
}
getBoolean method will read value of "was_clicked" preference. 2nd argument will be returned if you haven't yet put value "was_clicked" to shared preferences, so you can return false if you haven't put this preference to show the textView.

how to save state of dynamically created checkbox in android

i am creating number of check boxes dynamically and i have done some logic to select only one at a time . now i just want to save the state of the selected checkbox and when i come back from the next screen it should be selected. below i have given the code for checkbox
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
if (hash.size() > 0) {
hash.get("1").setChecked(false);
}
hash.put("1", buttonView);
selAnyone = true;
} else {
hash.clear();
selAnyone = false;
}
Edit:
Whenever you are navigating to the current activity to the next activity , save the id of selected check box like this
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("checkboxid","1");
editor.commit();
or simply send it via Intent
yourintent.putExtra("checkboxid","1"); // selected checkbox id
And then
If you are using the intent instead of sharedpreferences put the same extra when navigating back to the current screen.
First using SharedPreferences:
In the onCreate of your Activity check whether pref contains checkbox id or not
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name",null); // if the preference doesn't exist it returns null
if(name!=null)
{
int checkedid=Integer.parseInt(name);
checkbox[checkid].setChecked(true);
}
Same logic follows for the intent extra also check for checkboxid , if it doesn't exist don't check anything, if it exists check the checkbox with assoicated id
Use SharedPreferences
Example:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("checkboxid","1");
editor.commit();
Get like this
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name","checkboxid");

Shared Preference & Spinner Not Maintaining State

I have a spinner like this:
// Spinner 1
final Spinner plan = (Spinner) dialog.findViewById(R.id.spinner1);
strings = getResources().getStringArray(R.array.paymentplan);
sAdapter = new SpinnerAdapter(this,
android.R.layout.simple_spinner_item, strings);
sAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
plan.setAdapter(sAdapter);
// plan.setAdapter(spinner1Adapter);
plan.setSelection(prefsDisplay.getInt("spinnerSelection1", 0));
plan.setOnItemSelectedListener(new MyOnItemSelectedListenerPlan());
When user clicks, I want it to save state:
public void onClick(View v) {
Editor editor2 = prefsPlan.edit();
int selectedPosition1 = plan.getSelectedItemPosition();
editor2.putInt("spinnerSelection1", selectedPosition1);
editor2.commit();
}
It saves the position in SharedPref, but the spinner goes back to default. Anyone see something here?
you are storing spinnerSelection
editor1.putInt("spinnerSelection", selectedPosition);
an accessing spinnerSelection1
prefsDisplay.getInt("spinnerSelection1", 0)
make them consistent.
Update
when you are accessing plan.getSelectedItemPosition(). then spinner is visible? I guess NO.
try to put a public variable for selected position. And update selected position in your MyOnItemSelectedListenerPlan. And then store that position in shared preferences. I guess it solve your problem.
to Save:
int selectedPosition = yourSpinner.getSelectedItemPosition()
editor.putInt("spinnerSelection", selectedPosition);
editor.commit();
to Load:
yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
if you are array used it should changed like this
String selectedString = yourArray[yourSpinner.getSelectedItemPosition()];
editor.putString("spinnerSelection", selectedString);
editor.commit();
checking array[i] against the value stored in prefs.if you use an
ArrayList instead this part could be done without the loop by calling
ArrayList.indexOf(prefs.getString("spinnerSelection", "");
when you commit show all above array item gone. show no one into
array.
Try below code and first save position of current selected item into one integer variable on onItemSelectedListener() using below code and after that store this variable value into shared preferences.
For Store value into one Variable.
int index;
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// Here Position is Item Index
index = position;
}
For Store Value into shared preferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt("SelectedIndex", index);
prefsEditor.commit();
And see below link for more information
Android Spinners
Android Shared Preferences
after saving to the preferences, you have to set the selected item to the spinner for further uses
as
int pos = prefsDisplay.getInt("spinnerSelection", "0");
display.setSelection(pos);
but you are using spinnerSelection1. so By default if there is no matching in the preferences. the default value will return. so Here 0 is returned and spinner is set to first position

How can I get SharedPreferences of a PreferenceActivity from another class in android?

I'm new at android. I have a little idea over sharedPreference. Some tutorials say to add preferences in a xml file, but I need to add preferences dynamically. So I done that from a java class(my settings page).
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
CheckBoxPreference checkboxPref = new CheckBoxPreference(this);
checkboxPref.setKey("1");
checkboxPref.setTitle("SomeRandomStuff");
root.addPreference(checkboxPref);
Now, Now I need to get title of all selected checkbox (true) from that settings page to show which option been selected.
How can I do that?
thank you.
you can use a regular checkbox and sharedPreferences. Just add it's state like this
// global variables
SharedPreferences data;
public static String filename = "prefs";
// setup the SharedPreferences in onCreate()
data = getSharedPreferences(filename, 0);
// set the SharedPreference based on checkbox state
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
switch (arg0) {
case R.id.checkBox1:
boolean checked = checkBox1.isChecked();
SharedPreferences.Editor e = dataAddHS.edit();
e.putBoolean("preferenceName", checked);
e.commit();
break;
}
then when you need to pull the preference state, just do
boolean checked = data.getBoolean("preferenceName", false);
then you can use an if statement to see if checked is true or false, etc.
From what you're saying, it sounds like all you need is a default value for the preferences you will be working with. To be specific, you may have a bunch of checkbox-preferences that you want to use. When you read them, you can use the getBoolean method to get their values.
Note that the getBoolean method takes a second argument, which is the default value to return.
This means that you don't have to set the preferences dynamically. You use getBoolean to read the preferences and if the preferences have not been set by the user, a default value that you specify will be returned.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.getBoolean("whether_user_wants_setting1", false);

Categories

Resources