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.
Related
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;
}
}
}
};
Excuse me because 3 of my simple question, but I need your help. I want to have a counter (with using shared preference) in my app like this:
At the first, there are 2 buttons, START and RESET. If RESET is
clicked, the counter starts from 0.
Also if START is clicked, the counter starts from shared preference data.
Start counting
At last time, I want to save counter in share preference. (but I don't know its better to save it in BACK btn or CLICK btn)
My problem is in share preference part. Please help me how can I do this? Thanks a lot!
Edit: this is my code
public class CountActivity extends Activity {
private Button click;
private int count,savedCount;
private String count_text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counting);
click= (Button) findViewById(R.id.vow_counting);
final Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/Far_Homa.ttf");
final SharedPreferences sharedPreferences=getSharedPreferences("counters", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor=sharedPreferences.edit();
AlertDialog.Builder fBuilder=new AlertDialog.Builder(VowCountActivity.this);
fBuilder.setMessage("please choose");
fBuilder.setCancelable(false);
fBuilder.setPositiveButton("start from beging", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
count = sharedPreferences.getInt("counter", 0);
click.setText("0");
click.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/Far_Homa.ttf"));
dialogInterface.cancel();
}
});
fBuilder.setNegativeButton("countinue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
count = sharedPreferences.getInt("counter",savedCount);
editor.putInt("counter",savedCount).commit();
dialogInterface.cancel();
}
});
fBuilder.show();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count++;
count_text=Integer.toString(count);
click.setText(count_text);
click.setTypeface(typeface);
savedCount = sharedPreferences.getInt("savedCounter", count);
vibrate(500);
}
});
}
// vibrate
public void vibrate(int duration) {
Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibs.vibrate(duration);
}
To get value on start button you can define this function and have value for shared preferences
public static int getIntPreferences(String key) {
SharedPreferences settings = context.getSharedPreferences(SP_FILE_NAME, 0);
return settings.getInt(key, 0);
}
Now to reset your shared preferences value you can use the following function
public static void updatePreferences(String key, int value) {
SharedPreferences settings = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(key, value);
editor.commit();
}
Use
SharedPreferences preferences = getSharedPreferences("PROFILE", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
edit.putString("yourPreferenceName", yourPreferenceObject);
edit.commit();
for saving preference
and
SharedPreferences preferences = this.getSharedPreferences("PROFILE", Context.MODE_PRIVATE);
String string = preferences.getString("yourPreferenceName", "defaultReturn");
for receiving your sharedPreferences
.get and .put with return type
Try this:
SharedPreferences preferences = getSharedPreferences("counterStat", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int counter = preferences.getInt("counter", 0);
// counter = counter + 1; start counting
edit.putInt("counter", counter).commit();
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putInt("counter", 0).commit();
}
});
Dialog back:
int counter = preferences.getInt("counter", 0);
edit.putInt("savedCounter", counter).commit();
Dialog cancel:
int counter = preferences.getInt("counter", 0);
edit.putInt("savedCounter", counter).commit();
edit.putInt("counter", 0).commit();
Then you can use: int savedCounter = preferences.getInt("savedCounter", 0); anywhere
Here is how to add an entry to SharedPrefs, and save to disk.
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", "Adam");
editor.commit();
Here is how to read a saved value from SharedPrefs.
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
String name = settings.getString("name", null);
i want to store button favourite state in the viewpager which i m developing so that users can always look back the images that they have book-marked as favourite. The button state is stored, however, once i reopen the application, the button state has not changed. Is it because the activity has destroyed? How to store the state of button in the viewpager?
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
showProgress();
imageView = (ImageView) findViewById(R.id.btn_favourite);
imageView.setColorFilter(Color.argb(255, 192, 192, 192));
imageView.setOnClickListener(new View.OnClickListener() {
Boolean stateBtn= sharedPreference.getBtnState(context);
#Override
public void onClick(View v) {
// Boolean stateBtn= sharedPreference.getBtnState(context);
if(!stateBtn) {
sharedPreference.save(context, mUrl);
sharedPreference.saveBtnState(context, stateBtn);
Toast.makeText(context,
"Added to Favourite!",
Toast.LENGTH_SHORT).show();
imageView.setColorFilter(Color.argb(255, 249, 0, 0));
}
else
{
sharedPreference.saveBtnState(context, stateBtn);
imageView.setColorFilter(Color.argb(255, 192, 192, 192));
}
}
});
View photoRow = inflater.inflate(R.layout.item_image, container,
false);
ImageView image = (ImageView) photoRow.findViewById(R.id.img_flickr);
// added imageloader for better performance
StaggeredDemoApplication.getImageLoader().get(imageArrayList[position],
ImageLoader.getImageListener(image, R.drawable.bg_no_image, android.R.drawable.ic_dialog_alert), container.getWidth(), 0);
((ViewPager) container).addView(photoRow);
stopProgress();
return photoRow;
}
Here is the code of shared preference
public class SharedPreference {
public static final String PREFS_NAME = "AOP_PREFS";
public static final String PREFS_STATE="AOP_BTN";
public static final String PREFS_KEY = "AOP_PREFS_String";
public static final String PREF_BTN_KEY = "AOP_PREF_BTN";
public SharedPreference() {
super();
}
public void save(Context context, String text) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putString(PREFS_KEY, text); //3
editor.commit(); //4
}
public String getValue(Context context) {
SharedPreferences settings;
String text;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
text = settings.getString(PREFS_KEY, null);
return text;
}
public void clearSharedPreference(Context context) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.clear();
editor.commit();
}
public void removeValue(Context context) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.remove(PREFS_KEY);
editor.commit();
}
public void saveBtnState(Context context, Boolean stateBtn) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_STATE, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putBoolean(PREF_BTN_KEY, stateBtn);//added state for button
editor.commit(); //4
}
public boolean getBtnState(Context context)
{
SharedPreferences prefs = context.getSharedPreferences(PREFS_STATE, Context.MODE_PRIVATE);
boolean switchState = prefs.getBoolean(PREF_BTN_KEY, false);
return switchState;
}
}
no because you are calling wrong preference . you have to use PREFS_STATE instead of PREFS_NAME and also use PREF_BTN_KEY instead of PREFS_NAME . This is because while saving button state you are using preference with key PREFS_STATE and put boolean value with PREF_BTN_KEY .
public boolean getBtnState(Context context)
{
SharedPreferences prefs = context.getSharedPreferences(PREFS_STATE, Context.MODE_PRIVATE);
boolean switchState = prefs.getBoolean(PREF_BTN_KEY, false);
return switchState;
}
Change The getBtnState method
public boolean getBtnState(Context context)
{
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
boolean switchState = prefs.getBoolean(PREF_BTN_KEY, false);
return switchState;
}
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:
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();
}