Check if switch from SettingsActivity is on - android

How can I check in my MainActivity if the on/off switch is on in the SettingsActivity. I want to check if the switch is on and if it is, I want to do something. How do I do this so that this preference is saved and will be the same when you restart the app?
Here is a part of my SettingsActivity with a switch
static int audio;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
Preference switchPref = (Preference) findPreference("audio_switch");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean isOn = (boolean) o;
if (isOn) {
audio = 1;
}else{
audio = 0;
}
return true;
}
});
}

You are saving correctly the preference value, even you are returning true from your onPreferenceChangeListener to store the new value.
Preference switchPref = (Preference) findPreference("audio_switch");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean isOn = (boolean) o;
if (isOn) {
audio = 1;
}else{
audio = 0;
}
//* Set true to update the state of the Preference with the new value!
return true;
}
});
}
The value is saved correctly when you close the application, if you want to check the value you can read it from the preference:
//Check the current value in preference.
SharedPreferences switchPrefStatus = PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean switchPrefValue = switchPrefStatus.getBoolean("audio_switch", false);
Toast.makeText(getActivity(), "Current value: " + switchPrefValue, Toast.LENGTH_SHORT).show();
Here is a complete example of PreferenceFragment with PreferenceFragment:

I usually do the following:
To save your setting
(Put this in a save() method you call when you click a button or something in your settings activity)
SharedPreferences options =
getSharedPreferences("optionsPreference",
contextOfSettings.MODE_PRIVATE);
options.edit().putString("key", "value").apply();
In order to do this you need to add this in your settings activity
As a global variable in settings
public static Context contextOfSettings;
And this method in your onCreate of settings
#Override
protected void onCreate {
contextOfSettings = getApplicationContext();
}
And import it in your main activity by typing context of settings somewhere and then import it by pressing alt+enter
Like this:
import com.SettingsActivity.contextOfSettings;
Then you can get your saved value (which will still be saved even if you close your app) with this in your on create of your MainActivity
SharedPreferences options = getSharedPreferences("optionsPreference", contextOfSettings.MODE_PRIVATE);
String savedValue = options.getString("key", "defaultValue");
This String can have the values true and false which you can set with checkBox.isChecked() in combination with an if-statement

Related

Boolean Shared Preference is not storing

I am working on an Android game, in which in settings there is an option to turn off/on the sound of game.
I want to store these settings for the game, for this i am using shared preference to store a boolean value.
but issue is Boolean variable is not saving after app is closed.
here is my Code
Button Click Listener which is setting the SharedPreference
volume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (check == false) {
check = true;
PrefrencesClass.setBoolPreference(mContext,
Constants.APPSPREF, Constants.FIRSTTIME, true);
volume.setBackgroundResource(R.drawable.mute);
Log.e("Check is True", "Preference is True");
} else if (check == true) {
check = false;
volume.setBackgroundResource(R.drawable.volume);
PrefrencesClass.setBoolPreference(mContext,
Constants.APPSPREF,Constants.FIRSTTIME, false);
Log.e("Check is false", "Preference is false");
}
Toast.makeText(getApplicationContext(), "Volume is Clicked",
Toast.LENGTH_SHORT).show();
}
});
My function to set the boolean SharedPreference
public static final void setBoolPreference(Context base, String prefName,
String key, boolean value) {
SharedPreferences userPref = base.getSharedPreferences(prefName,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userPref.edit();
editor.putBoolean(key, value);
editor.commit();
}
This is how i am getting the SharedPreference
public static final boolean getBoolPreference(Context base,
String prefName, String key) {
SharedPreferences usePref = base.getSharedPreferences(prefName,
Context.MODE_PRIVATE);
boolean value = usePref.getBoolean(key, false);
return value;
}
and this is the code where i need to use the sharedpreference saved state to play sound or not
mPlayer = MediaPlayer.create(MainActivity.this, R.raw.stronghold);
if (PrefrencesClass.getBoolPreference(context, Constants.APPSPREF,
Constants.FIRSTTIME) == false) {
mPlayer.start();
mPlayer.setLooping(true);
}
Boolean state is not saving Please Help
Try this
public static void saveBooleanToSharedPref(Context context, String key, boolean value){
SharedPreferences settings = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, value);
editor.commit();
}//saveBooleanToSharedPref
public static boolean getBooleanBySharedPref(Context context, String key){
SharedPreferences settings = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean value = settings.getBoolean(key, true);
return value;
}//getStringBySharedPref
Your set is wrong, because you use putInt method.
You should be able to say:
volume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check = !check // avoids if statements, same below
SharedPreferences prefsget = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
SharedPreferences.Editor prefset = prefsget.edit();
prefset.putBoolean(yourBoolVar, !prefsget.getBoolean(yourBoolVar, false));
prefset.commit();
}
});
You can still put an if statement for setting image background. But the what I have above should cut down on a lot of your code. Remember to replace the activity I typed above with your own activity and also for the boolean variable too.

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

Check/Uncheck all preferences?

I'm trying to improve the user friendliness of an app by providing the user with "Select all" and "Deselect all" options in the preferences. Things seem to be working, except for one major flaw:
I'm using SharedPreferences.getAll() to retrieve all the checkboxes so I can iterate them and check/uncheck them. But it seems that getAll() doesn't quite live up to it's name. It doesn't return ALL preferences, but only the ones that have been previously altered by the user.
So, is there a way to retrieve ALL of the preferences?
The code I'm currently using:
public class ADRpreferences extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
((Preference) findPreference("searchresult_select_all")).
setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
setCheckState("searchresult", true);
return true;
}
});
((Preference) findPreference("searchresult_deselect_all")).
setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
setCheckState("searchresult", false);
return true;
}
});
}
private void setCheckState(String prefix, Boolean state) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
#SuppressWarnings("unchecked")
Map<String, Boolean> categories = (Map<String, Boolean>) settings.getAll();
for (String s : categories.keySet()) {
Preference pref = findPreference(s);
if( s.startsWith(prefix) && (pref instanceof CheckBoxPreference) ){
((CheckBoxPreference) pref).setChecked(state);
}
}
}
}
EDIT
Ok, for now I will go with MH's solution. I put all the ID's of the checkbox preferences into arrays.xml, and will use those values to iterate through all the checkboxes (there are 44 of them in case you wonder why I just don't hardcode the ID's). Works great, of course in the future I will have to remember to add/remove the ID's in the arrays if I make changes to the preferences. Here's the new setCheckState():
private void setCheckState(String category, Boolean state) {
String[] arr = null;
if( category.equals("loadlist") ){
arr = getResources().getStringArray(R.array.array_loadlist_checkboxes);
}
else if( category.equals("searchresult") ){
arr = getResources().getStringArray(R.array.array_searchresult_checkboxes);
}
else{
return;
}
for( String s : arr ){
Preference pref = findPreference(s);
if( pref instanceof CheckBoxPreference ){
((CheckBoxPreference) pref).setChecked(state);
}
}
}

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

Android: CheckboxPreferences act like RadioButtons

I have four checkboxpreferences in my preferencescreen that I would like to interact like a radiobuttongroup, meaning that you can only check one of them! If lets say the first is checked, and you like to check another one, its just the desired one checked, and the other ones is unchecked.
I did like this :
public class PreferenceActivity extends PreferenceActivity {
private SharedPreferences prefs;
private Editor editor;
private int keyItemChecked;
private CheckBoxPreference item1CheckBox, item2CheckBox, ..., itemICheckBox;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
addPreferencesFromResource(R.xml.prefs);
item1CheckBox = (CheckBoxPreference) getPreferenceManager().findPreference("item1");
item2CheckBox = (CheckBoxPreference) getPreferenceManager().findPreference("item2");
...
itemICheckBox = (CheckBoxPreference) getPreferenceManager().findPreference("itemI");
item1CheckBox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
manageItem(1, item1CheckBox);
return true;
}
});
....
itemICheckBox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
manageItem(I, itemICheckBox);
return true;
}
});
}
private void manageItem(int i ,CheckBoxPreference pref) {
keyItemChecked = prefs.getInt("keyItemChecked",1); // 1 is your default checked item
if (! pref.isChecked() && keyItemChecked == i)
// If you click on the checked item, you don't want it to be unchecked :
pref.setChecked(true);
if (pref.isChecked() && keyItemChecked != i) {
editor = prefs.edit();
editor.putInt("keyItemChecked", i);
editor.commit(); // or editor.apply() if you use API > 9
unckeckOldItem(keyItemChecked);
}
}
private void unckeckOldItem(int item) {
switch (item) {
case 1:
item1CheckBox.setChecked(false);
break;
...
case I:
itemICheckBox.setChecked(false);
break;
}
}
You don't need to declare "keyItemChecked" on your prefs.xml.
The first time you call the activity, the data doesn't exist and
keyItemChecked = prefs.getInt("keyItemChecked",1);
will return 1.
Once you click on an other item than the default, the data will exist.
Looks like you can use http://developer.android.com/reference/android/preference/CheckBoxPreference.html#setDisableDependentsState%28boolean%29 to create that functionality. I think setting dependency of preferences can be done in xml.

Categories

Resources