android preference back to default summary - android

I'm currently using a preference activity with fragments. I'm using android:summary in the xml file defining these preferences to set an explaining caption to the user and then setSummary on each preference when the user changes the preference value and everything works fine.
But when the user clears his/her choice in any EditTextPreference I would like to display back the explaining text from the xml tag android:summary. How could I achieve that?
Thanks in advance for your help.

OK I figured it out.
Just add a resource string for every preference key called "key_summary" and use it as android:summary in the xml file defining the preferences.
Then in the onSharedPreferenceChanged function, just load the corresponding string as the summary as follows:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
Preference preference = findPreference(key);
if(preference instanceof EditTextPreference)
{
EditTextPreference editPref = (EditTextPreference)preference;
String szPref = editPref.getText();
if(null!=szPref&&0<szPref.length())
editPref.setSummary(szPref);
else
{
Activity activity = getActivity();
int nSummary = getResources().getIdentifier(key + "_summary", "string", activity.getPackageName());
if(0<nSummary)
editPref.setSummary(getString(nSummary));
else
editPref.setSummary(szPref);
}
}
}

Related

Can't resolve findPreference() from MainActivity?

I'm getting a compiler error cannot resolve method findPreference when I try to intialize an OnSharedPreferencesChanged listener in my MainActivity. According to the answer here:
findPreference() should be called from a class implementing PreferenceActivity interface
but I don't understand what the code to do this would be. How can I get rid of the compiler error and successfully set listeners for preference changes?
MainActivity.java
public class MainActivity extends FragmentActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
//Test preference menu
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("pref_wood")) {
Preference woodPref = findPreference(key); //COMPILER ERROR HERE
MainActivity.getGLSurfaceView().setTexture("");
// Set summary to be the user-description for the selected value
woodPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
}
}
findPreference is a method which is part of both PreferenceFragment and PreferenceActivity - these are the Fragments/Activities that actually show your Preference screen (the activity is deprecated and you should be using the PreferenceFragment).
You're trying to use it in your MainActivity. This doesn't work because the Preference objects don't actually exist on this screen (they exist in another activity that usually have a PreferenceFragment as part of it). If you need to get access to a preference value of a preference in an activity that is not your preference screen, use SharedPreferences, something like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getBoolean(R.bool.saved_high_score_default);
boolean wood = sharedPref.getBoolean(pref_wood, defaultValue);
You can check out the documentation for further examples.
If your MainActivity is supposed to be a screen that shows settings, then you should probably rename it and include a preference fragment inside of it.
I believe you're also going to run into trouble with setSummary because the Preference is not part of this activity, it's part of the activity where you actually modify the preferences. setSummary is used to update the actual UI of the Preference so that if you, for example, select one of three values when using a list preference, it shows the value you just selected on the screen.

Handling clicks in PreferenceActivity

So I am trying to implement a preferences menu in my app. I used the standard generated template in android studio. THe issue is that now I can't figure out how save the values the user specifies. I thought about using a click listener to determine when a user clicked a checkbox and then getting the actual value of the checkbox and saving that to sharedpreferences, but I can't figure out how to do it.
Does anyone have any suggestions on how use onClick in a preference activity?
OK, we seem to be on the right track about the system storing the values automatically, but whenever I try to reference them from my main class, it always returns null. Here is my code:
boolean trueorfalse = PreferenceManager.getDefaultSharedPreferences(getActivity())
.getBoolean("my_key", false)
;
So I assume you've already defined your Preferences in res --> xml and it looks something like this:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="my_key"
android:summary="#string/desc_string"
android:title="#string/title_string" />
</PreferenceScreen>
As soon as the user checks or unchecks the CheckBox the systen will automatically create an entry in the default Preference-file which you can access like this:
PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean("my_key", false);
But back to your initial question: If you want to assign an onClick-Listener to your preference you have to do something like this:
Preference myPreference = (Preference) findPreference("my_key");
myPreference .setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
// do something
}
});
Note: In this example it isn't a CheckBoxPreference, it's just a simple Preference
I tried the same in my SettingsMenu by implementing OnSharedPreferenceChangeListener
public class SettingsMenu extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
Context context = getApplicationContext();
SharedPreferences menu_settings = PreferenceManager.getDefaultSharedPreferences(context);
menu_settings.registerOnSharedPreferenceChangeListener(this);
...
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// check the checkboxes
}
}
Hope it helps :)

How to keep information about an app in Android?

I want to know if its possible to keep information about an app in a while for example.
I have an app that access this file and get information about the choices that the user have made. For example:
I have a button for many events (event is a model), and i want to know if the user clicked in the button even after the application restarts.
I know that it is possible to keep information about login and password. Is possible to do something like this with other information?
Use Shared Preferences. Like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPrefValue()
{
SharedPreferences sp = getSharedPreferences("preferenceName", 0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPref(String thePreference)
{
SharedPreferences.Editor pref =getSharedPreferences("preferenceName",0).edit();
pref.putString("myStore", thePreference);
pref.commit();
}
You could call them like this:
// when they click the button:
writeToPref("theyClickedTheButton");
if (getPrefValue().equals("theyClickedTheButton"))
{
// they have clicked the button
}
else if (getPrefValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// this preference has not been created (have not clicked the button)
}
else
{
// this preference has been created, but they have not clicked the button
}
Explanation of the code:
"preferenceName" is the name of the preference you're referring to and therefore has to be the same every time you access that specific preference. eg: "password", "theirSettings"
"myStore" refers to a specific String stored in that preference and their can be multiple.
eg: you have preference "theirSettings", well then "myStore" could be "soundPrefs", "colourPrefs", "language", etc.
Note: you can do this with boolean, integer, etc.
All you have to do is change the String storing and reading to boolean, or whatever type you want.
You can use SharedPreference to save your data in Android.
To write your information
SharedPreferences preferences = getSharedPreferences("PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_Id",userid.getText().toString());
editor.putString("user_Password",password.getText().toString());
editor.commit();
To read above information
SharedPreferences prfs = getSharedPreferences("PREF", Context.MODE_PRIVATE);
String username = prfs.getString("user_Id", "");
In iOS NSUserDefaults is used to do the same
//For saving
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:your_username forKey:#"user_Id"];
[defaults synchronize];
//For retrieving
NSString *username = [defaults objectForKey:#"user_Id"];
Hope it helps.

Refresh android PreferenceFragment

I have a CheckBoxPreference in a FragmentPreference. When the user active the check box, I check if an application is installed and if not, I reset the preference on false and I open the Play Store to download the app.
Basically all works fine, but I have an issue to refresh the UI. Indeed, even if I set the preference on false before opened the Play Store, when the user come back, the box is checked (the fragment has just been paused and resumed so the preference value is ignored).
Is there a way to "refresh" the activity or the fragment?
Make your PreferenceFragment implement the OnSharedPreferenceChangeListener interface.
In onCreate(), you can read the preference value and set the UI accordingly. For instance:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource.
addPreferencesFromResource(R.xml.shakesql_app_prefs);
// Initialize pref summary label.
// Get a reference to the application default shared preferences.
SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
// Read the current preference value.
String listVal =
sp.getString(getString(R.string.preference_font_size_key),
getString(R.string.preference_font_size_default));
// Look up the textual description corresponding to the
// preference value and write it into the summary field.
String listDesc = descriptionFromPref(
listVal,
getResources().getStringArray(
R.array.preference_font_size_values),
getResources().getStringArray(
R.array.preference_font_size_labels)
);
if (!TextUtils.isEmpty(listDesc)) {
ListPreference listPref =
(ListPreference) findPreference(getString(R.string.preference_font_size_key));
listPref.setSummary(listDesc);
}
}
Then, in onSharedPreferenceChanged(), update the UI.
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);
if (pref instanceof ListPreference) {
// Update display title
// Write the description for the newly selected preference
// in the summary field.
ListPreference listPref = (ListPreference) pref;
CharSequence listDesc = listPref.getEntry();
if (!TextUtils.isEmpty(listDesc)) {
pref.setSummary(listDesc);
}
}
}
Here's a code snippet from the AdvancedPreferences sample in API Demos to force the value of a checkbox preference.
// Toggle the value of mCheckBoxPreference.
if (mCheckBoxPreference != null) {
mCheckBoxPreference.setChecked(!mCheckBoxPreference.isChecked());
}

How to update internal values of a PreferenceActivity when SharedPreferences change

I use a Preference in a PreferenceActivity to load default values: when this specific Preference is clicked, something like this happens:
private String mResetKeys = "key1,key2,key3";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor prefs_editor = prefs.edit();
for (String current_pref : mResetKeys.split(",")) {
prefs_editor.remove(current_pref);
}
prefs_editor.commit();
But afterwards, the Preferences whose corresponding SharedPreference was reset still show the old value - it seems to be cached in the Preference. Only when I leave the PreferenceActivity and reopen it, the Preferences show the new values.
How can I update the PreferenceActivity programmatically?
I had a similar problem. This probably isn't the most correct fix but it worked for my purposes. Right after I did the commits, I called the Activity.recreate(); method.
The activity will restart (onDestroy()/onCreate()/etc) but for my purposes all I needed was a special handling on one preference. I listened for a certain preference with an OnPreferenceClickListener and made an alert dialog box with a kind of warning message and an option to change their mind. If they did want to change their mind, I did my commit of the new value to the preference activity and then called recreate() so that the checkbox preference would be updated.
However, I am also interested in a way to do this without recreating the activity...
Update preference value without reloading PreferenceActivity
from http://liquidlabs.ca/2011/08/25/update-preference-value-without-reloading-preferenceactivity/
Here is how to update default shared preference value of target element (in this case EditTextPreference)
public class YourCustomPreference extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
// some logic goes above, when you want to reset value and update EditTextPreference value
// For convenience, I am going to wrap two different task in different methods
private void resetPreferenceValue() {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefEditor = sharedPref.edit(); // Get preference in editor mode
prefEditor.putString("your_edit_text_pref_key", "DEFAULT-VALUE"); // set your default value here (could be empty as well)
prefEditor.commit(); // finally save changes
// Now we have updated shared preference value, but in activity it still hold the old value
this.resetElementValue();
}
private void resetElementValue() {
// First get reference to edit-text view elements
EditTextPreference myPrefText = (EditTextPreference) super.findPreference("your_edit_text_pref_key");
// Now, manually update it's value to default/empty
myPrefText.setText("DEFAULT-VALUE"); // Now, if you click on the item, you'll see the value you've just set here
}
}

Categories

Resources