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.
Related
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
I have a NavigationDrawer in my Activity with three items.
I want to show all three items when first time user Login.
In other session I want to make one item invisible and show only two items in NavigationDrawer.
you have to detect first launch of the app using this code
public class MyActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
add 1 item to navigation drawer at first launch or after first launch is completed, remove your 1 of the item from navigation drawer
USE SharedPreferences to store user status!
public class SharedPrefModel {
public static String INFO_STORE_TAG = "user_info";
public static String sharedPrefName = "USER";
private SharedPreferences sharedPref;
public SharedPrefModel(Context context) {
this.sharedPref = context.getSharedPreferences(sharedPrefName, MODE_PRIVATE);
}
public void setStatus(Boolean isFirstTime) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(INFO_STORE_TAG, isFirstTime);
editor.apply();
}
public Boolean getStatus() {
return sharedPref.getBoolean(INFO_STORE_TAG,false);
}
public void clearInfo() {
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.apply();
}
}
After login for the first time set the status to false.
new SharedPrefModel(this).setStatus(false);
Next Time check that if the status is true or not.
if(!new SharedPrefModel(this).getStatus()){
//hide
}
to reset the status! use
new SharedPrefModel(this).clearInfo();
I have two activities. In the second activity I have a spinner. what I would like to happen is after the user selects an item from the spinner it will save via actionbar press and on back press which will load the previous activity. Based on my research my activity is supposed to look something like the following below but it's not working what am I doing wrong??
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
getActionBar().setDisplayHomeAsUpEnabled(true);
spin = (Spinner)findViewById(R.id.editspin);
Intent i = this.getIntent();
note = new ArgueItem();
note.setKey(i.getStringExtra("key"));
note.setText(i.getStringExtra("text"));
EditText et = (EditText)findViewById(R.id.argueEdit);
et.setText(note.getText());
et.setSelection(note.getText().length());
}private boolean saveState() {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefEditor = prefs.edit();
int daddy = spin.getSelectedItemPosition();
prefEditor.putInt("savedValue",daddy);
prefEditor.commit();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
EditText et = (EditText)findViewById(R.id.argueEdit);
String argueText = et.getText().toString();
if(argueText.equals("")){
Toast.makeText(this, "Please Enter A New ", Toast.LENGTH_SHORT).show();
return false;
}
if (item.getItemId() == android.R.id.home) {
saveAndFinish();
}
return false;
}
#Override
public void onBackPressed() {
EditText et = (EditText)findViewById(R.id.argueEdit);
String argueText = et.getText().toString();
if(argueText.equals("")){
Toast.makeText(this, "Please Enter A New ", Toast.LENGTH_SHORT).show();
return;
}else{
saveAndFinish();
}
In your second activity, you have to override the onPause() and. Inside it write the saving process.
protected void onPause(){
super.onPause();
//Include the code which, save the data.
}
You should use a FragmentActivity and add/remove fragments within the same activity.
check these resources:
http://developer.android.com/guide/components/fragments.html
http://www.vogella.com/articles/AndroidFragments/article.html
This is how i'm initializing my spinner which is in the ActionBar. I'm not adding it as a custom view, but I'm using the drop down menu feature.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
//save in preferences
PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit().
putInt(SELECTED_DIARY_PREF, itemPosition).commit();
return true;
}
});
int selPosition = PreferenceManager.getDefaultSharedPreferences(this).getInt(SELECTED_DIARY_PREF, 0);
actionBar.setSelectedNavigationItem(selPosition);
What this code does is: saving the preference when an item of the menu is clicked, and restoring that preference when the activity is launched. Hope it helps.
I have a EditText in a preference menu that allows me to edit a URL address. The problem is when I get the preference value in the mainActivity is not getting updated right away after I click OK in the Preference Menu. Not sure how to fix this problem. I tried a bunch of ideas and finally decided to ask.
public class PreferencesActivityTest extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.radio_preferences);
PreferenceManager.setDefaultValues(PreferencesActivityTest.this,
R.xml.radio_preferences, false);
EditTextPreference editPref =(EditTextPreference)findPreference("MyText");
editPref.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.toString().length() > 0) {
return true;
}
// If now create a message to the user
Toast.makeText(PreferencesActivityTest.this,
"Invalid Input", Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
PS: This code updates the newValue to what I enter in the EditTextPreference, doesn't carry the new value to the MainActivity until I modify it again...
UPDATE:
In OnResume() I can see that the value is updated with the one that I modified in the PreferenceActivityTest from EditTextPreference. What I'm trying to do is to pass this newValue into the SetDataSource("").
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_radio);
initializeMediaPlayer();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_edit:
editURL();
// make a Dialog or show an Activity
return true;
}
}
private void initializeMediaPlayer() {
PreferenceManager.setDefaultValues(this, R.xml.radio_preferences, false);
SharedPreferences pref =PreferenceManager.getDefaultSharedPreferences(this);
String radioPath = pref.getString("MyText", "default value");
// Toast.makeText(this, radioPath, Toast.LENGTH_SHORT).show();
try {
radioPlayer.reset();
// radioPlayer.setDataSource("http://31.xx.xxx");
// Toast.makeText(this, radioPath, Toast.LENGTH_SHORT).show();
radioPlayer.setDataSource(radioPath);
} catch {
}
}
public void editURL() {
stopPlaying();
startActivity(new Intent(getBaseContext(), PreferencesActivityTest.class));
}
I am doing something fundamentally wrong but I need help. Thank you in advance !
how are you calling the preference activity? If you are calling it directly, you probably need to change the call to startActivityForResult so you refresh your data once you return from the Activity
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);
}
}
}