how to deal with multiple buttons in sharedpreferences - android

I have 21 togglebuttons and was wondering how to save state of each individual one using sharedpreferences?
i've tried with this:
button = (ToggleButton)findViewById(R.id.btn1);
SharedPreferences sharedPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
button.setChecked(sharedPrefs.getBoolean(PREFS_NAME, true));
but how to make it store values for all buttons and can i do it in PREFS_NAME for all of them?
ok so i created xml file with those buttons:
<ToggleButton
android:textOff="1"
android:textOn="*"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="#+id/tB1" />
and activity with this code:
int [] viewIds = new int [] {R.id.tB1, R.id.tB2, ...
String [] stringIds = new String [] {"R.id.tB1" ...
ToggleButton button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.randd_screen);
for(int i =0; i<viewIds.length;i++)
{
Log.d(TAG, "inside loop");
Log.d(TAG, "Run no.:" + i);
button =(ToggleButton)findViewById(viewIds[i]);
Log.d(TAG, "button = " + button);
Log.d(TAG, "from stringIds[i] " + stringIds[i]);
SharedPreferences sharedPrefs = getSharedPreferences("PREFS_NAME", MODE_PRIVATE);
button.setChecked(sharedPrefs.getBoolean(Integer.toString(viewIds[i]), false));
}
}
now, how to create onClick method which would update each button value as well as save and load it?
Update 2
so that how my activity look like now but it does not preserve checked buttons. am i missing something or done something wrong?
int [] viewIds = new int [] {R.id.tB1, R.id.tB2, ...
String [] stringIds = new String [] {"R.id.tB1", ...
ToggleButton button;
}
button = (ToggleButton)findViewById(R.id.tB2);
SharedPreferences sharedPrefs = getSharedPreferences("PREFS_NAME", MODE_PRIVATE);
button.setChecked(sharedPrefs.getBoolean(stringIds[1], true));
}
ToggleButton.OnCheckedChangeListener listener = new ToggleButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton v, boolean isChecked) {
Log.d(TAG, "in onCheckChanged()");
int [] viewIds = new int[2];
int index;
for(index = 0; index < viewIds.length; index++) {
if (v.getId() == viewIds[index]) {
getSharedPreferences("PREFS_NAME", MODE_PRIVATE)
.edit()
.putBoolean(stringIds[index], isChecked)
.apply();
break;
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.randd_screen);
for(int i =0; i<viewIds.length;i++)
{
Log.d(TAG, "inside loop");
Log.d(TAG, "Run no.:" + i);
button =(ToggleButton)findViewById(viewIds[i]);
Log.d(TAG, "button = " + button);
Log.d(TAG, "from stringIds[i] " + stringIds[i]);
SharedPreferences sharedPrefs = getSharedPreferences("PREFS_NAME", MODE_PRIVATE);
button.setChecked(sharedPrefs.getBoolean(stringIds[i], false));
button.setOnCheckedChangeListener(listener);
}
}

You will need to store state for all of them.
SharedPreferences sharedPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
button = (ToggleButton)findViewById(R.id.btn1);
button.setChecked(sharedPrefs.getBoolean(PREFS_BUTTON1, true));
button = (ToggleButton)findViewById(R.id.btn2);
button.setChecked(sharedPrefs.getBoolean(PREFS_BUTTON2, true));
button = (ToggleButton)findViewById(R.id.btn3);
button.setChecked(sharedPrefs.getBoolean(PREFS_BUTTON3, true));
//...
You could make it much cleaner by implementing a list of IDs and their preference key. You could then loop through them, setting buttons as required.
Updated Question
Do not use the generated integer resource as a SharedPreferences identifier Integer.toString(viewIds[i]). You creating a String array for that purpose. Use that instead stringIds[i].
You can create a listener and apply the same listener to every ToggleButton. In that listener you check which button recieved the call and set the appropriate preference.
ToggleButton.OnCheckedChangeListener listener = new ToggleButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton v, boolean isChecked) {
int index;
for(index = 0; index < viewIds.length; index++) {
if (v.getId() == viewIds[index]) {
getSharedPreferences("PREFS_NAME", MODE_PRIVATE)
.edit()
.putBoolean(stringIds[index], isChecked)
.apply();
break;
}
}
}
};

Related

checkboxes getting checked in android

I am trying to check a checkbox and keep its state to checked until it gets unchecked but as soon as I close the dialog containing the checkboxes and come back to it, all the checkboxes are checked instead of the selected one. I have tried the following way
private void saveCheckboxState(int index1, int index2, boolean isChecked)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("checkbox" + index1 + index2, isChecked);
editor.apply();
}
private boolean getCheckboxState(int index1, int index2)
{
SharedPreferences prefs = PreferenceManager. getDefaultSharedPreferences(this);
return prefs.getBoolean("checkbox" + index1 + index2, false);
}
boolean checkbox_success;
case R.id.menu_checkboxes:
Dialog s_dialog = new Dialog(this);
s_dialog.setContentView(R.layout.s_dialog);
checkbox_layout = s_dialog.findViewById(R.id.checkbox_layout);
layoutParams.setMargins(20,20,20,20);
s_dialog.show();
title = s_dialog.findViewById(R.id.dialog_title);
title.setText("select option ");
for (int i = 0; i < 5; i++) {
CheckBox checkBox = new CheckBox(this);
checkBox.setId(groupIndex);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
checkbox_success = true;
boolean success = db.update(String.valueOf(items.getId())
);
}
});
checkbox_layout.addView(checkBox);
}
}
Is there any way I can get it to check only the selected items? Thanks for help.
> This is what I suggest you do.
Create an Int variable and assign a value == 1 to it when checkBox is Checked, so when Dialog is recreated/created you check if isChecked == 0 or 1 and change the status of the checkBox based on the result, view the code below.
var isChecked: Int = 0
Dialog.....//isCreated
if(isChecked == 1)
//set checkBox isChecked = true
else //set checkBox isChecked = false
CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
boolean checked = PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean("checkBox1", false);
checkBox1.setChecked(checked);
Try this method using sharedPreference.
Will give an example how to save checkbox states in shared preferences and to read them back.
Code is only for one loop.
You have to realise that if you have two loops you should use two indexes to store a state.
private void saveCheckboxState(int index, boolean isChecked)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("checkbox" + index, isChecked);
editor.commit();
}
private boolean getCheckboxState(int index)
{
SharedPreferences prefs = PreferenceManager. getDefaultSharedPreferences(context);
return prefs.getBoolean("checkbox" + index, false);
}
At building your dialog call getCheckboxState().
Call saveCheckboxState() in the on change handler.
For two loops you only have to adapt the functions with another index.
For instance it would become private void saveCheckboxState(int index1,int index2, boolean isChecked)` then.
I suggest you code the functions for two indexes and post your code here.

How save state of checkbox? if is enabled or disabled

I'm making an app that have a lot of checkbox. I wanted save the states of these but only could save if these are checked, but now I want save if is enabled or disabled, since some checkbox active states to other checkbox. How can i do that?
...
if (view.equals(contador11)){
if(contador11.isChecked()){
contador14.setEnabled(true);
}else{
contador14.setEnabled(false);
}
}
if (view.equals(contador12)){
if(contador12.isChecked()){
contador13.setEnabled(true);
contador26.setEnabled(true);
}else{
contador13.setEnabled(false);
contador26.setEnabled(false);
}
}
if (view.equals(contador7)){
if(contador7.isChecked()){
contador15.setEnabled(true);
}else{
contador15.setEnabled(false);
}
}
...
I'm not following your code exactly, but assuming you want to save all of them at the same time, you could save code by just putting them in a list or something. Here's an example.
private SharedPreferences prefs;
private CheckBox[] contadors;
private CheckBox contador1, contador2, contador3, contador4, contador5, contador6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
contador1 = (CheckBox) findViewById(R.id.contador1);
contador2 = (CheckBox) findViewById(R.id.contador2);
contador3 = (CheckBox) findViewById(R.id.contador3);
contador4 = (CheckBox) findViewById(R.id.contador4);
contador5 = (CheckBox) findViewById(R.id.contador5);
contador6 = (CheckBox) findViewById(R.id.contador6);
}
public void clickContador(View view) { // Just for testing
CheckBox contador = (CheckBox) view;
view.setEnabled(false);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveContadors();
}
#Override
protected void onResume() {
super.onPostResume();
contadors = new CheckBox[]{contador1, contador2, contador3, contador4, contador5, contador6};
loadContadors();
}
private void saveContadors() {
SharedPreferences.Editor editor = prefs.edit();
for (int i = 0; i < contadors.length; i++)
editor.putBoolean("contador" + i, contadors[i].isEnabled());
editor.apply();
}
private void loadContadors() {
for (int i = 0; i < contadors.length; i++)
contadors[i].setEnabled(prefs.getBoolean("contador" + i, true));
}
<CheckBox
android:id="#+id/contador1"
android:onClick="clickContador"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
To put the state of your CheckBox, we can use SharedPreferences:
CheckBox contador = (CheckBox) findViewById(R.id.contador1);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
if (contador.isChecked()) {
prefs.edit().putBoolean("key", true).commit(); // put true value
}else{
prefs.edit().putBoolean("key", false).commit(); // put false value
}
To get the value you saved back:
boolean myContador = prefs.getBoolean("key", false);
if (myContador == true) {
// do your thing
}else{
// the value is false, do something
}

android sharedPreferences to set and retrieve boolean value

I want to save boolean values and then compare them in an if-else block. but when run my application, nothing is displayed.
my Code is here:
prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = prefs.edit();
boolean init = false;
if (init) {
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor.putBoolean("init", true).commit();
}
});
} else {
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
So my question is why shared preferences is not working? please help me.
This is how you need to work with shared preferences.
The senerio I am about to show is to check if this particular activity is running for the first time or not.
Here is what you do in your on create method:
//SharePrefernces
SharedPreferences appIntro = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Check if the Application is Running for the First time
appIntro = getSharedPreferences("hasRunBefore_appIntro", 0); //load the preferences
Boolean hasRun = appIntro.getBoolean("hasRun_appIntro", false); //see if it's run before, default no
//If FirstTime
if (!hasRun) {
//code for if this is the first time the application is Running
//Display Activity
super.onCreate(savedInstanceState);
setContentView(R.layout.app_intro_activity);
//Button to send Confirmation back
Button btn_ok = (Button) findViewById(R.id.appintro_btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Save information that this application has run for the first time
SharedPreferences settings = getSharedPreferences("hasRunBefore_appIntro", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean("hasRun_appIntro", true);
edit.commit(); //apply
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
});
}//End of if(firstTime)
else {
//code if the Application has run before
super.onCreate(savedInstanceState);
//Navigate Directly to MainActivity
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
}//End of OnCreate()
you are checking always false value of init and it does not enter into your if statement,So prefs will not updated.instead do it as
boolean init = prefs.getBoolean("init",false);
and check it as
if(!init)
i.e. change
boolean init = false;
if (init) {
to
boolean init = prefs.getBoolean("init",false);
if(!init)
You are not using SharedPreferences values in above code . You might need to do like this :
SharedPreferences prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean prefValue = prefs.getBoolean("init", false);
if(!prefValue)
{
// add value in SharedPreferences
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor = prefs.edit();
editor.putBoolean("init", true).commit();
}
});
}
else{
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
The key is : You need to check the preference values first and accordingly code
You can also use SharedPreferences like this:
/* In your onCreate method */
SharedPreferences sp = getSharedPreferences(MyPrefs, Context.MODE_PRIVATE);
if (!sp.getBoolean("first", false)) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("first", true);
editor.apply();
Intent intent = new Intent(this, IntroActivity.class); // Call the one tie launch java class
startActivity(intent);
}

how to get sharedpreferences from a radiogroup to anotrher activitys

I have two activities (settings, prayers)
in the settings activity I put three radio buttons inside a radio group every radio button will let the colors changed in the prayers activity
settings.class
public class SettingsActivity extends Activity {
RadioGroup rg;
TextView textCheckedID, textCheckedIndex;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
rg = (RadioGroup) findViewById(R.id.radios);
rg.setOnCheckedChangeListener(rgOnCheckedChangeListener);
textCheckedID = (TextView) findViewById(R.id.checkedid);
textCheckedIndex = (TextView) findViewById (R.id.checkedindex);
LoadPreferences();
}
OnCheckedChangeListener rgOnCheckedChangeListener = new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton checkedRadioButton = (RadioButton)rg.findViewById(checkedId);
int checkedIndex = rg.indexOfChild(checkedRadioButton);
textCheckedID.setText("checkedID = " + checkedId);
textCheckedIndex.setText("checkedIndex = " + checkedIndex);
SavePreferences(KEY_SAVED_RADIO_BUTTON_INDEX, checkedIndex);
}
};
private void SavePreferences(String key, int value) {
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton) rg.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
}
}
and in the prayers activity the textcolor and the background of the layout should change colors to one of the selected choice in the settings activity
prayers.class
SharedPreferences sharedPreferences = getSharedPreferences(
"com.e_orthodoxy.orthodox_prayers", MODE_PRIVATE);
int colors = sharedPreferences
.getInt("KEY_SAVED_RADIO_BUTTON_INDEX", 0);
if (colors == 0) {
textview.setTextColor(getResources().getColor(R.color.Vanilla));
linear.setBackgroundColor(getResources().getColor(R.color.Maroon));
textview.setShadowLayer(0, 0, 0,
(getResources().getColor(R.color.Maroon)));
} else if (colors == 1) {
textview.setTextColor(Color.BLACK);
linear.setBackgroundColor(Color.WHITE);
textview.setShadowLayer(0, 0, 0, Color.BLACK);
} else if (colors == 2) {
textview.setTextColor(Color.WHITE);
linear.setBackgroundColor(Color.BLACK);
textview.setShadowLayer((float) 1.5, 2, 2, Color.WHITE);
}
where is my fault
any help???
You are writing and reading from two different SharedPreferences:
In SettingsActivity:
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
In prayers:
SharedPreferences sharedPreferences = getSharedPreferences(
"com.e_orthodoxy.orthodox_prayers", MODE_PRIVATE);
Notice the first parameter i.e., the name of the SharedPreference file.

How to save the state of rediobutton throughout the application in android?

I have two radio groups and each group has two radiobuttons.
the default value is true (i.e. checked ) for first radiobutton in each group.
When user cliks on any radiobutton and when user comeback from other activities the selections made on these radiogroups/radiobuttons are gone...
how can I save/restore radiogroup/radiobutton selection state ??
here is my java code..for one radiogroup..
final RadioButton radioOn = ( RadioButton )findViewById(
R.id.rbOn );
final RadioButton radioOff = ( RadioButton )findViewById(
R.id.rbOff );
radioOn.setChecked( true );
radioOn.setOnClickListener( auto_lock_on_listener );
radioOff.setOnClickListener( auto_lock_off_listener );
please help.
You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
super.onSaveInstanceState(savedInstanceState);
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate and also onRestoreInstanceState where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
You'd usually use this technique to store instance values for your application (selections, unsaved text, etc.).
Try to save your radio group state by using SharedPreferences
RadioGroup rG1 = (RadioGroup)findViewById(R.id.radioGroup1);
int rG1_CheckId = rG1.getCheckedRadioButtonId();
SharedPreferences rG1Prefs = getSharedPreferences("rG1Prefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = rG1Prefs.edit();
prefsEditor.putInt("rG1_CheckId", rG1_CheckId);
prefsEditor.commit();
and put this lines for get back the checked radio button id.
SharedPreferences rG1Prefs = this.getSharedPreferences("rG1Prefs", MODE_WORLD_READABLE);
rG1Prefs.getInt("rG1_CheckId", null);
and by using this id checked the radio button.
you can store into the SharedPreference
simple example
SharedPreferences settings = getSharedPreferences("on_off", 0);
boolean silent = settings.getBoolean("onoff", false);
////// to set the value use editor object from the SharedPreferences
Editor editor = settings.edit();
editor.putBoolean("onoff", true);
editor.commit(); // to save the value into the SharedPreference
Use this code -
mFillingGroup.check(whichFilling);
mAddMayoCheckbox.setChecked(addMayo);
mAddTomatoCheckbox.setChecked(addTomato);
/**
* We also want to record the new state when the user makes changes,
* so install simple observers that do this
*/
mFillingGroup.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
// As with the checkbox listeners, rewrite the
// entire state file
Log.v(TAG, "New radio item selected: " + checkedId);
recordNewUIState();
}
});
CompoundButton.OnCheckedChangeListener checkListener
= new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// Whichever one is altered, we rewrite the entire UI state
Log.v(TAG, "Checkbox toggled: " + buttonView);
recordNewUIState();
}
};
mAddMayoCheckbox.setOnCheckedChangeListener(checkListener);
mAddTomatoCheckbox.setOnCheckedChangeListener(checkListener);
}
/**
* Handy helper routine to write the UI data to a file.
*/
void writeDataToFileLocked(RandomAccessFile file,
boolean addMayo, boolean addTomato, int whichFilling)
throws IOException {
file.setLength(0L);
file.writeInt(whichFilling);
file.writeBoolean(addMayo);
file.writeBoolean(addTomato);
Log.v(TAG, "NEW STATE: mayo=" + addMayo
+ " tomato=" + addTomato
+ " filling=" + whichFilling);
}
And, this can help you to do whatever you need.
Use Shared Preferences, To save your radio button's state, Or you can use Application Variables (Variable which is declared globally static in that activity and you can use it in any activity)
But I think Shared Preferences is good..
Look at Android - Shared Preferences
Look at this example How to save login info to Shared Preferences Android(remember details feature)
EDIT:
public class Test extends Activity {
private SharedPreferences prefs;
private String prefName = "MyPref";
private SharedPreferences.Editor editor;
private static final String CHECK_STATE = "checkBox_State";
private boolean check_state;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
//---getting the SharedPreferences object....
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
editor = prefs.edit();
radioOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
check_state = true;
} else {
check_state = false;
}
}
});
// storing in shared preferences...
editor.putBoolean(CHECK_STATE, check_state );
editor.commit();
}
});
}

Categories

Resources