I have following code:
This is in onCreate - I am trying to set default value of a radio button here, which will be the pre selected value on radio button.
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
RadioGroup rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroupQuestions);
int selectedOption = rg_numberOfQuestions.getCheckedRadioButtonId();
rb_NumberOfQuestions = (RadioButton) findViewById(selectedOption);
rg_numberOfQuestions.setOnCheckedChangeListener(this);
final RadioGroup rg_numbersBetween = (RadioGroup) findViewById(R.id.radioGroupNumbersBetween);
selectedOption = rg_numbersBetween.getCheckedRadioButtonId();
rb_NumbersBetween = (RadioButton) findViewById(selectedOption);
rg_numbersBetween.setOnCheckedChangeListener(this);
#Override
public void onCheckedChanged(RadioGroup rg, int i) {
switch (rg.getCheckedRadioButtonId())
{
case R.id.rb_0to10:
savePref("rb_0to10", rg.getCheckedRadioButtonId());
break;
case R.id.rb_0to25:
savePref("rb_0to25", rg.getCheckedRadioButtonId());
break;
case R.id.rb_0to50:
savePref("rb_0to50", rg.getCheckedRadioButtonId());
break;
case R.id.rb_15:
savePref("rb_15", rg.getCheckedRadioButtonId());
break;
case R.id.rb_25:
savePref("rb_25", rg.getCheckedRadioButtonId());
break;
case R.id.rb_50:
savePref("rb_50", rg.getCheckedRadioButtonId());
break;
}
}
private void savePref(String key, int value) {
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
editor = pref.edit();
editor.putInt(key, value);
editor.commit();
}
Above code works first time it gets the default value of first radio button. But no matter what other radio button i select it is not working it is not saving the button click value it just gets first radio button always.
You can see the value itself in DDMS :
Here is the image for Debugging and see the values in Shared Pref :
And
you can pull and push files also in any location... To see Values in
Shared pref click that file
on Top right side there is 2 icon of mobile with pink Arrow from there
u can push and pull Shared pref Files
Try this code of snippet.. It works perfect...
OnCreate Method code :
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroup1);
rb_1 = (RadioButton) findViewById(R.id.radioOne);
rb_1.setOnCheckedChangeListener(this);
rb_2 = (RadioButton) findViewById(R.id.radioTwo);
rb_2.setOnCheckedChangeListener(this);
rb_3 = (RadioButton) findViewById(R.id.radioThree);
rb_3.setOnCheckedChangeListener(this);
int selected_radio_button = pref.getInt("radio", 0);
if(selected_radio_button!=0)
{
RadioButton button = (RadioButton) findViewById(selected_radio_button);
button.setChecked(true);
}
And the listener code :
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
Editor editor = pref.edit();
editor.putInt("radio", buttonView.getId());
editor.commit();
}
}
It seem Initialization of share-preference is not correct. can you just try below code#
private void savePref(String key, int value) {
pref = getSharedPreferences("ANYNAME",Context.MODE_PRIVATE);
editor = pref.edit();
editor.putInt(key, value);
editor.commit();
}
Related
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.
I am developing a game on Android, I have a background music that stop with a switch and that is in an other activity, that of the parameters. The music is in the main menu.
I would like to know how to save the state of the switch (checked or not checked) by going from the main menu to the parameters
This the code for my switch :
buttonmusique = (Switch) findViewById(R.id.switchMusique);
buttonmusique.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("bouton", String.valueOf(buttonmusique.isChecked()));
// If the music is playing
if (isChecked) {
Intent music = new Intent();
music.setClass(Parametres.this, BackgroundMusic.class);
startService(music);
musicBoolean = true;
buttonmusique.setText("Musique On"); //To change the text near to switch
Log.d("You are :", "Checked");
} else {
Intent music = new Intent();
music.setClass(Parametres.this, BackgroundMusic.class);
stopService(music);
musicBoolean = false;
// Resume the music player
buttonmusique.setText("Musique OFF"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
});
Put it in your create method: (+adapt to your situation)
final SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
CheckBox checkbox = (CheckBox) findViewById(R.id.myCheckBox);
checkbox.setChecked(sharedPreferences.getBoolean("mycheckbox", true));
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
sharedPreferences.edit().putBoolean("mycheckbox", b).apply();
}
});
You can save it in SharedPreferences.
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
Save sound settings
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(getString(R.string.sound_enabled), isChecked);
editor.commit();
To get sound settings use:
boolean soundEnabled = prefs.getBoolean(getString(R.string.sound_enabled), false);
// Set switch state
buttonmusique.setChecked(soundEnabled);
Load status:
boolean switch_status = PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean("switch_status", false);
Save status:
SharedPreferences.Editor sped = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
sped.putBoolean("switch_status", value);
sped.commit();
Use shared preferences or a database to store the state of your switch. It is essential that you depend on the lifecycle methods of Activity/fragment.
The following might help you:
......
.....
#Override
public void onClick(View v)
{
if (toggle.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("state_to_save", true);
editor.commit();
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("state_to_save", false);
editor.commit();
}
}
The final Code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
.......
......
SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyle", MODE_PRIVATE);
toggle.setChecked(sharedPrefs.getBoolean("state_to_save", true));
}
I have want to checkble radiobutton value in my second activity.
i have also use RadioGroup and sharedpreference.
but first Radiobutton value get in my second activity. so sharedpreference not saving the radiobutton value.
please show this code and help me how can i get?
rg = (RadioGroup) findViewById(R.id.radiotype);
rbtn=((RadioButton)rg.findViewById(getSelectedValue()));
if(rbtn!=null){
rbtn.setChecked(true);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
savePreferences(RemainderType_Toggle, checkedId);
}
});
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
TypeToggleValue = sharedPreferences.getInt(RemainderType_Toggle, R.id.radionoti);
if (TypeToggleValue == R.id.radionoti)
{
rbtn.setChecked(true);
}
else
{
rbtn.setChecked(false);
}
}
private int getSelectedValue(){
SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this);
return pref.getInt(RemainderType_Toggle, -1);
}
private void savePreferences(String key, int value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
SecondAcityvity.java
here i want the selected radiobutton value.
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
TypeToggleValue = sharedPreferences.getInt(RemainderType_Toggle, R.id.radioalarm);
Log.d("TypeToggleValue", String.valueOf(TypeToggleValue));
You do not need to refer your RadioButton in reference to your RadioGroup. Simply you can access it without reference.
Change your below line
rbtn=((RadioButton)rg.findViewById(getSelectedValue()));
as below
rbtn=(RadioButton)findViewById(R.id.radioButton);
I have following code in settings.java:
public static int numberOfQuestions = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
final RadioGroup rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroupQuestions);
rg_numberOfQuestions.setOnCheckedChangeListener(this);
RadioButton rbtn = ((RadioButton) rg_numberOfQuestions.findViewById(pref.getInt("NQ", 0)));
if(rbtn!=null)
rbtn.setChecked(true);
}
public void onCheckedChanged(RadioGroup rg, int i) {
switch (rg.getCheckedRadioButtonId())
{
case R.id.rb_0to10:
numbersBetween = 10;
break;
case R.id.rb_0to25:
numbersBetween = 25;
break;
case R.id.rb_0to50:
numbersBetween = 50;
break;
}
if(rg.getCheckedRadioButtonId() == R.id.rb_0to10 || rg.getCheckedRadioButtonId() == R.id.rb_0to25 || rg.getCheckedRadioButtonId() == R.id.rb_0to50)
{
savePref("NB", rg.getCheckedRadioButtonId());
}
}
This is code to save and access preference:
private void savePref(String key, int value) {
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
editor = pref.edit();
editor.putInt(key, value);
editor.commit();
}
private void savePref(String key, Boolean value) {
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
editor = pref.edit();
editor.putBoolean(key, value);
editor.commit();
}
}
If i am in settings numberOfQuestions variable gets updated and it works fine in my other view called main.java. But lets say i open main.java directly and not open setting first numberOfQuestions does not have right value. Is there easier way to transfer shared preference value to other view? Or do i need to write all cases in main.java also?
You don't need to do anything special, you can use the same shared preferences from each part of your app in the same way.
You can move the methods to access shared preferences to:
a parent class for all your activities
a static methods in a helper class (you would have to pass context as parameter in this case and be careful not to create a reference to this context to avoid memory leaks).
You can use
numberOfQuestions = getSharedPreferences(Constants.NUM_OF_QUESTIONS, 0);
to initialize its value. then access it anywhere in your application
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.