How to save the state of rediobutton throughout the application in android? - 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();
}
});
}

Related

Loading SharedPreferences in another activity

Here's the problem. In my second class, I'm trying to load the SharedPreferences. Below I'll also include my first class.
//set label for journal questions
public TextView journalQuestionLabel;
public int counter = 0;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_journal);
//TODO: Send saved preferences here
preferences = getSharedPreferences("grammarOption", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
}
When I test it, my debug log always prints -1. It won't load my shared preferences. What am I doing wrong?
I've tried the other answers on here and every tutorial, but they aren't working. Here is my code to set up and save my spinner preferences. I've checked this and it's working.
private void setupSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
final ArrayAdapter grammarSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.array_grammar_options,
android.R.layout.simple_spinner_dropdown_item);
// Specify dropdown layout style - simple list view with 1 item per line
grammarSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//Apply the adapter to the spinner
grammarChoiceSpinner.setAdapter(grammarSpinnerAdapter);
//Create shared preferences to store the spinner selection
SharedPreferences preferences = getApplicationContext().getSharedPreferences
("Selection", MODE_PRIVATE);
editor = preferences.edit();
// Create the intent to save the position
grammarChoiceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//receive the string of the option and store it
int grammarOptionPosition = grammarChoiceSpinner.getSelectedItemPosition();
//put the string in the editor
editor.putInt("grammarOption", grammarOptionPosition);
editor.commit();
//make a toast so the user knows if it's not "select"
if (grammarOptionPosition != 0) {
Toast.makeText(getApplicationContext(), "Choice saved.",
Toast.LENGTH_SHORT).show();
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mGrammar = 0;
}
});
}
Here it's called in onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
//find the spinner to read user input
grammarChoiceSpinner = (Spinner) findViewById(R.id.spinner);
setupSpinner();
You are passing wrong String in getSharedPreferences(String, int).
preferences = getSharedPreferences("Selection", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
Give this a try.
I hope it helps.
Make sure your SharedPreference key is same in both the class or even throughout the whole App.
While saving do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
preferences.edit().putInt("grammerOption", 1).apply();
While Getting data from prefs do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
int option = preference.getInt("grammerOption", -1);
PS,
Key for preference(which is MY_PREFS here) must be the same.

How can i access shared preferences from another view

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

Android store radiogroup id in sharedpreferences and load it

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.

Load preferences in another activity?

I stored a value in my MainActivity called "tgpref".
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); //value to save
editor.commit();"
In my onCreate i have
public SharedPreferences preferences;
---
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = getPreferences(MODE_PRIVATE);
I want to display the value in my widget so i try to write in the onUpdate in widget provider class this
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean tgpref = preferences.getBoolean("tgpref", false)
if (tgpref == true) {
remoteViews.setTextViewText(R.id.battery, "Risp on");
} else {
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
If the toggle button in the MainActivty is clicked i want that in my widget appears "Risp on" else "Risp off". Right now displays only "Risp off" so i don't know how i can do. Any helps? Nothing happen i can't load the value
it looks good, so i guess your button doesn`t trigger the value change?!
MainActiviy
private Boolean mTgpref;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
//get value from shared preferences and update ui
prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
mTgpref = prefs.getBoolean("tgpref", false);
setYourText();
}
private void setYourTextAndStoreToSharedPref(){
Log.i("TEST","mTgpref -> " + mTgpref); //check value
if(mTgpref){
remoteViews.setTextViewText(R.id.battery, "Risp on");
}
else
{
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
prefs.edit().putBoolean("tgpref", mTgpref).commit();
//UPDATE YOUR WIDGET HERE
}
//function called on switch button click
private void onSwitchClickButtonClick(){
mTgpref = !mTgpref; //toggle Boolean
setYourText();
}
EDIT
Sorry, I misunderstood your main problem. After updating SharedPreferences, you should follow the steps described here: http://developer.android.com/guide/topics/appwidgets/index.html#UpdatingFromTheConfiguration

android getsharedPreferences not sure how to show hide other activities

I decided to use sharedPreferences so I could store the value of a togglebutton on my activity Preferences. On my main activity I want to hide a twitter button when the user clicks the twitter button in the Preferences activity.
private SharedPreferences prefs;
private String prefName = "MyPref";
private ToggleButton timer, twitter;
// this is the key used to set the timer to visible or hidden
private static final String TIMER_KEY = "timekey";
private static final String TWITTER_KEY= "tweet";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences);
timer = (ToggleButton)findViewById(R.id.timer_pref);
twitter =(ToggleButton)findViewById(R.id.twitter_pref);
timer.setChecked(true);
twitter.setChecked(true);
// Toast.makeText(Preferences.this, timer, Toast.LENGTH_SHORT).show();
Button b = (Button) findViewById(R.id.home_btn);
b.setOnClickListener(new View.OnClickListener()
{
// now add the new screen
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get the shared perference data
Intent i = new Intent(Preferences.this, AndroidGUIActivity.class);
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
prefs = getSharedPreferences("MyPref", 0 );
SharedPreferences.Editor editor = prefs.edit();
if (timer.isChecked() == true)
{
editor.putBoolean("twitterButtonStatus", true);
}
else if(timer.isChecked() == false)
{
editor.putBoolean("twitterButtonStatus", false);
}
// now save the value that is passed to the editor.putBoolean function
// the twitter data hase been saved
editor.commit();
// now store the variable so that it can be copied to another activity
Bundle b = new Bundle();
}
});
There is no need to transfer Preferences through activities using intent.
You can access your "shared"Preferences from any activity.
You just put the button status with a string key inside:
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("twitterButtonStatus", buttonStatus);
And in another activity you retrieve these preferences using string key ("twitterButtonStatus"):
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
boolean buttonStatus = settings.getBoolean("twitterButtonStatus", false); // second param is default!
See: http://developer.android.com/guide/topics/data/data-storage.html
Edit:
Youre saving SharedPrefs now, to get them back and set your Button Gone do something like this:
SharedPreferences settings = getSharedPreferences(prefName, 0);
boolean buttonStatus = settings.getBoolean(TWITTER_KEY, true); //2nd is default
if(buttonstatus==false) twitter.setVisibility(View.GONE);

Categories

Resources