Android store radiogroup id in sharedpreferences and load it - android

In my App i want to open a dialog window with a radiogroup with some items (each item should be an activity ) the user can choose from. The chosen item/ID should get stored in the sharedpreferences. The ID load every App start and open the chosen item/activity.
Can someone tell me how to do that Please ?

There are many samples but ok, I'll give an example:
You can define 2 methods under your activity:
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int selectedRadioID = sharedPreferences.getInt("SELECTED_RADIO", 0);
if(selectedRadioID > 0) {
// you got previously selected radio
RadioButton rb = (RadioButton)findViewById(selectedRadioID);
rb.setSelected(true);
}
}
private void savePreferences(String key, int radioId) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putInt(key, radioId);
editor.commit();
}
Use this methods on your activities onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadSavedPreferences();
RadioGroup rg = findViewById(R.id.your_radio_group_over_your_radios);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
savePreferences("SELECTED_RADIO", checkedId);
}
});
}
You should improve this code, but this will give you the idea.

Related

Radiogroup value doesn't save in sharedpreference in android

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);

SharedPreferences Android - Saving and editing one string only using two activities

I have a single string which the user will edit and will be displayed back to him when he uses the app. He can edit the string at any time. I am familiar with SQLite databases, but because for this purpose I am using only one string/one record, I felt SharedPreferences would be better. However, after following two different tutorials, I am unable to get it so save the data. In both cases I have needed to amend the tutorial code because I will be using two activities, one to view the code, the other to edit it. I was unable to find a tutorial for using sharedpreferences for two activities. Below is the code.
Class to view the code:
public class MissionOverviewActivity extends Activity {
TextView textSavedMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_view);
textSavedMem1 = (TextView)findViewById(R.id.textSavedMem1);
LoadPreferences();
textSavedMem1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
return;
}});
};
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
textSavedMem1.setText(strSavedMem1);
}
}
Class to edit the code and return to the view page
public class MissionDetailActivity extends Activity {
EditText editText1;
Button buttonSaveMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_edit);
editText1 = (EditText)findViewById(R.id.editText1);
buttonSaveMem1 = (Button)findViewById(R.id.buttonSaveMem1);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
viewStatement();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
protected void viewStatement() {
Intent i = new Intent(this, MissionOverviewActivity.class);
startActivity(i);
}
}
If any body could answer this question, or point me in the direction of a sharedpreferences tutorial that uses two classes (for edit and displaying), It would be greatly appreciated!
Thanks
getPreferences(int) is private for Activity, you want to share the same SharedPreference between activities you should use this way:
SharedPreferences prefs = this.getSharedPreferences(
"yourfilename", Context.MODE_PRIVATE);
and use the same method when you want to reload it. here the doc for getPrerences(int)

how to save some value in sharedpreferences and get that in next activity

I'm creating a Quiz App, I ask some questions and give options in the form of radio buttons, now I want to store value of of answer (plus on right answer and minus on wrong one) in SharedPreferences and show that result in other activity. I have searched and found this answer here
I used that but still I'm unable to get my desired results
My code Looks Like :
Main Activity which saves some value in SharedPreferences:
public class MainActivity extends Activity {
private SharedPreferences saveScore;
private SharedPreferences.Editor editor;
RadioGroup group;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radioGroup1);
radioButton = (RadioButton) group.findViewById(group.getCheckedRadioButtonId());
saveScore = getPreferences(MODE_PRIVATE);
}
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
editor = saveScore.edit();
editor.putInt("score", -1);
editor.commit();
}else{
editor = saveScore.edit();
editor.putInt("score", 1);
editor.commit();
}
Intent intent = new Intent (MainActivity.this, NextActivity.class);
startActivity(intent);
}}
this is the Next Activity which tries to get values from SharedPreferences:
public class NextActivity extends Activity{
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
preferences = this.getSharedPreferences("score", MODE_WORLD_WRITEABLE);
int value = preferences.getInt("score", 0);
String score = "Your Score is : " + value;
UIHelper.displayScore(this, R.id.tvScore, score );
}}
does any one know how to that?
You should change the line
saveScore = getPreferences(MODE_PRIVATE);
To
saveScore = getSharedPreferences("score",Context.MODE_PRIVATE);
Store the value when navigating to nextActivity during onPause() as below:
#Override
protected void onPause()
{
super.onPause();
// Store values between instances here
SharedPreferences preferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourStringKeyValue", "StringValue"); // value to store
// Commit to storage
editor.commit();
}
and get the data with that key in next Activity's onCreate as below:
SharedPreferences preferences = getSharedPreferences("sharedPrefs", 0);
String name= preferences.getString("YourStringKeyValue","");
try this,
public class DataStorage {
private static String KEY;
public static SharedPreferences savedSession;
public void saveID(Context context, String msessionid) {
// TODO Auto-generated method stub
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("SESSION_UID", msessionid);
editor.commit();
}
public String getID(Context context) {
savedSession = context.getSharedPreferences(KEY, Activity.MODE_PRIVATE);
return savedSession.getString("SESSION_UID", "");
}
}
Edit:
DataStorage mdata = new DataStorage();
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
mdata.saveId(Mainactivity.this,1);
}else{
mdata.saveId(Mainactivity.this,-1);
}
And then get value from NextActivity.
DataStorage mdata = new DataStorage();
mdata.getId(NextActivity.this);
You're using the wrong preference file, the getPreference function on Activity returns a file private to that Activity. You need to use the named file version- getSharedPreferences(name, mode)

Shared Prefference is not saving the data

I am storing the status of togglebutton using a sharedpreffrence.
I am putting "ON" if toggle button is checked and "OFF" if toggle button is unchecked.
But when I am retriveing the status , it always returns "ON"
Here is the code
SharedPreferences.Editor shfEditMessageSMS;
SharedPreferences shfResponderMessage;
shfResponderMessage=getSharedPreferences("MESSAGE", Context.MODE_PRIVATE);
shfEditMessageSMS=shfResponderMessage.edit();
toggleStatus=(ToggleButton)findViewById(R.id.toggleButtonStatus);
toggleStatus.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
if(((ToggleButton)v).isChecked())
{
shfEditMessageSMS.putString("SMSRESPONDERONOFF", "ON");
shfEditMessageSMS.commit();
showNotification("ON");
}
else
{
shfEditMessageSMS=shfResponderMessage.edit();
shfEditMessageSMS.putString("SMSRESPONDERONOFF", "OFF");
shfEditMessageSMS.commit();
showNotification("OFF");
String SMSResponderOnOrOff=shfResponderMessage.getString("SMSRESPONDERONOFF", "NONE");
Log.i("SMS Responder on click "+SMSResponderOnOrOff," ");
}
}
});
As you can see in the code that if toggle button in unchecked i am doing
shfEditMessageSMS.putString("SMSRESPONDERONOFF", "OFF");
shfEditMessageSMS.commit();
but when I am retrieving and printing using log
String SMSResponderOnOrOff=shfResponderMessage.getString("SMSRESPONDERONOFF", "NONE");
Log.i("SMS Responder on click "+SMSResponderOnOrOff," ");
It always shows "ON" in the logs.
What could be the problem.
thanks.
i have implement the Same thing in my application. Might Help you out to Solve your Problem.Though Could Not able to Find out the Mistake you have done in your Code. Refere below code below.
boolean on;
public SharedPreferences spref;
final String PREF_NAME="preferences";
ToggleButton tb;
#Override protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fb_intermidiate);
spref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.toggleButton1);
on = spref.getBoolean("On", true); //default is true
if (on = true)
{
tb.setChecked(true);
} else
{
tb.setChecked(false);
}
back = (Button)findViewById(R.id.button_back);
//back.setText(R.string.back_button_in_settings);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
}); }
public void onToggleClicked(View view) {
on = ((ToggleButton) view).isChecked();
if (on) {
Toast.makeText(this, "On : Notification will be Enabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
} else {
Toast.makeText(this, "Off : Notification will be Disabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor =spref.edit();
editor.putBoolean("On", false); // value to store
editor.commit();
} }
I had a similar problem but with saving a String array. I "solved" the problem by incrementing a variable on each save.
public void saveProfileList(Context context) {
SharedPreferences sharedprefs = context.getSharedPreferences(PREFS_NAME,Activity.MODE_PRIVATE);
Editor editor = sharedprefs.edit();
editor.putStringSet("vpnlist", profiles.keySet());
// For reasing I do not understand at all
// Android saves my prefs file only one time
// if I remove the debug code below :(
int counter = sharedprefs.getInt("counter", 0);
editor.putInt("counter", counter+1);
editor.apply();
}
There seems to be a bug somewhere in the android code that does not always detect the sharedpreferences as changed.
I have a vague recollection that it can take a while for the value to be read back correctly. You can solve that by encapsulating the value and store it in a variable, from where you also retrieve it. You should also consider using apply() instead of commit() since it does not interrupt the UI thread. Thus, I propose something like:
public class Preferences {
private SharedPreferences mPrefs;
private static final String KEY = "SMSRESPONDERONOFF";
private String mValue;
public Preferences(SharedPreferences prefs) {
mPrefs = prefs;
}
public String getValue() {
if (mValue == null) {
mValue = mPrefs.getString(KEY, "NONE");
}
return mValue;
}
public void setValue(String value) {
mValue = value;
mPrefs.edit().putString(KEY, value).apply();
}
}

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