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
Related
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.
I am trying to save the state of a checkbox while using SharedPreferences. I have spend hours on this problem...which I sure is easy to solve. I have been following the tutorial here
However, I do not understand what setSilent is and what I have to change it to within my own code. setSilent has been changed to checked in the below code based on one of the answers. I have searched through stackoverflow a lot and found loads of related answers but nothing has worked and the setSilent (sometimes a different name) error is always persistent. I have posted my code below.
SuikodenFragment.java -- The error is here.
Boolean checked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.suikoden_main_activity1, container, false);
// you can use findViewById() using the above 'view'
// get the listview
expListView = (ExpandableListView) view.findViewById(R.id.suikodenList1);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
checked = true;
return view;
}
public void onStart() {
super.onStart(); // Always call the superclass method first
SharedPreferences settings = getActivity().getSharedPreferences(suikodenprefs, Context.MODE_PRIVATE);
boolean isChecked = settings.getBoolean("Tick the Box", checked);
checked(isChecked);
//if(isChecked)
//checkBox.setChecked(true);
}
The code below is placing the checkbox state which might help understand my problem.
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
CheckBox checkBox = (CheckBox) expListView.findViewById(R.id.checkboxTick);
checkBox.setOnCheckedChangeListener(this);
if (isChecked)
// Add the tick to the box
//Log.d(TAG, "Tick the box");
checked = true;
else
// Remove the tick in the box
//Log.d(TAG, "Untick the box");
checked = false;
}
#Override
public void onStop(){
super.onStop();
SharedPreferences settings = getActivity().getSharedPreferences(suikodenprefs, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("Tick the Box",checked).commit();
}
I really hope someone can help with this. It may seem like a stupid problem but if it can be solved then I can complete a huge section of my app. The following link is the closest to my own code...but when i implement their solution, checkBoxView flags up as an error Android saving state of checkbox if exit app. I am a beginner so I apologise...thanks in advance!
You need to create a class variable which gets changed in your onCheckedChangedListener and then save it in shared preferences in your onStop() method.
At the top of your activity declare a Boolean variable, lets call it checked.
Boolean checked;
It's good practice to initialize a variable so do that in you onCreate method.
checked = true;
In your onCheckedChanged method set the value of 'checked' to true or false depending on the state.
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
CheckBox checkBox = (CheckBox) expListView.findViewById(R.id.checkbox_tick);
checkBox.setOnCheckedChangeListener(this);
if (isChecked)
checked = true;
else
checked = false;
}
In your onStop method save the value of your checked variable.
#Override
public void onStop(){
super.onStop();
SharedPreferences settings=getActivity().getSharedPreferences(suikodenprefs,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("Tick the box",checked).commit();
}
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");
I am using ToggleButtons in a listview, and I set the state of togglebutton from the webservice data, now I changed the state of togglebutton, but it is reset to previous when I scrolling the listview.
I used the following in my adapter class.
tbtnStatus=(ToggleButton)view.findViewById(R.id.togglebtn);
tbtnStatus.setTag(new Integer(position));
tbtnStatus.setOnCheckedChangeListener(null);
tbtnStatus.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
String update_status;
String current_status=buttonView.getText().toString();
if(current_status.equals("ON"))
{
update_status="NO";
}
else
{
update_status="YES";
}
String res=UrltoValue.getValuefromUrl(DataUrls.updateindividualstaus+"?pilotid="+DataUrls.pilotid+"&friendid="+friendid[position]+"&status="+update_status);
}
});
State of your toggle button will be cleared to it's default value from webservice data each time when you sroll it out of the screen, because views of all not currently visible rows are deleted and will be recreated with default values. You need to save state of you toggle button. For example, you can save it in object associated with this row if you use ArrayAdapter<Object>.
save your position of View when u check the toggle button of that respective view...and in getView() write this code
if(yourposition==position)
tbtnStatus.setChecked(true);
Suppose you clicked 3rd position toggle..save 3 as yourposition and when u will scroll getView gets called and will satify the condition checking your toggle to yes
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);