findPreference(java.lang.CharSequence) is deprecated - android

It gives me the error "findPreference(java.lang.CharSequence) is deprecated" .Currently, I am targeting API 10 and above for my application. Any kind of help to resolve this will be appreciated.
public class SettingsActivity extends PreferenceActivity
implements Preference.OnPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
// TODO: Add preferences from XML
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key));
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
// TODO: Add preferences
}
/**
* Attaches a listener so the summary is always updated with the preference value.
* Also fires the listener once, to initialize the summary (so it shows up before the value
* is changed.)
*/
private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
} else {
// For other preferences, set the summary to the value's simple string representation.
preference.setSummary(stringValue);
}
return true;
}
}

It is deprecated because Android moved to fragment-based activities. Calling findPreference(CharSequence) will still work in higher API levels. You are just encouraged to use fragments instead of a PreferenceActivity.
The reason for the deprecation can be found in the source:
This function is not relevant for a modern fragment-based PreferenceActivity.
In API 11+ you should use PreferenceFragment.
If you want to have your IDE ignore the error just add the following to your method: #SuppressWarnings("deprecation")

public class SettingsActivity extends PreferenceActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
}
public static class MyPreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_details);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
}
private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
} else {
// For other preferences, set the summary to the value's simple string representation.
preference.setSummary(stringValue);
Log.v("onpreferencechange",stringValue);
}
return true;
}
}
Instead of adding the methods
bindPreferenceSummaryToValue(Preference preference) &
onPreferenceChange(Preference preference, Object value)
inside the main SettingsActivity class create a fragment class which implements the Preference.OnPreferenceChangeListener add the both the methods inside it.
check out the code provided
hope it helps

Well here is the solution:
API Level 11+ introduced PreferenceFragment as another way of
constructing the contents of a PreferenceActivity. You are welcome to
use them, but if you are still supporting older devices, you cannot
use PreferenceFragment for those devices.
Try the following link:
Non Deprecated findPreference() Method? - Android

Related

How to provide multiple theme options in application?

I want to give the user the option of choosing between several different colour themes in my app in the settings activity. I know how to bundle/save/load the prefs, nevertheless I'm having trouble accomplishing this.
I have defined my colors in colors.xml, defined several themes in v21styles.xml, and added the options to a listview in the SettingsActivity.java.
The only part I am having difficulty with is actually applying the new themes. I would like to set up a switch statement to apply the themes using the built in android methods, but am not exactly how to accomplish this on API 21 (lolipop).
public class SettingsActivity extends PreferenceActivity {
/**
* Determines whether to always show the simplified settings UI, where
* settings are presented in a single list. When false, settings are shown
* as a master/detail two-pane view on tablets. When true, a single pane is
* shown on tablets.
*/
private static final boolean ALWAYS_SIMPLE_PREFS = false;
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setupSimplePreferencesScreen();
}
/**
* Shows the simplified settings UI if the device configuration if the
* device configuration dictates that a simplified, single-pane UI should be
* shown.
*/
private void setupSimplePreferencesScreen() {
if (!isSimplePreferences(this)) {
return;
}
// In the simplified UI, fragments are not used at all and we instead
// use the older PreferenceActivity APIs.
// Add 'general' preferences.
addPreferencesFromResource(R.xml.pref_general);
}
/**
* {#inheritDoc}
*/
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this) && !isSimplePreferences(this);
}
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
/**
* Determines whether the simplified settings UI should be shown. This is
* true if this is forced via {#link #ALWAYS_SIMPLE_PREFS}, or the device
* doesn't have newer APIs like {#link PreferenceFragment}, or the device
* doesn't have an extra-large screen. In these cases, a single-pane
* "simplified" settings UI should be shown.
*/
private static boolean isSimplePreferences(Context context) {
return ALWAYS_SIMPLE_PREFS
|| Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
|| !isXLargeTablet(context);
}
/**
* {#inheritDoc}
*/
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
if (!isSimplePreferences(this)) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* #see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
#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);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
}
/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
}
}
/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.string.theme:
//apply red theme
R.style.RedTheme;
break;
case R.style.IndigoTheme:
//apply blue theme
case R.style.AppTheme:
//apply default theme
return true;
}
return super.onOptionsItemSelected(item);
}}
The part at the bottom is where I am trying to do the actual theme swapping. Is this the correct way to handle preference options even though it's technically not a "menu item"?
I have defined the theme names in my styles.xml, and v21/styles.xml. In the manifest the theme is set to AppTheme. I just want to be able to swap themes when the user selects a new theme in the preferences activity.
I think you have to do this with following in your switch case:-
themeUtils.changeToTheme(this, themeUtils.ur_theme_name);
Take a look into this following tutorial http://www.developer.com/ws/android/changing-your-android-apps-theme-dynamically.html..Hope it will helps you.

Android How to update Background color from PreferenceList directly

I have a ListPreference containing colors. Only when I restart the application that the colors are being changed, not directly. How do I make it change directly when I click ?
public class Preferences extends PreferenceActivity {
SharedPreferences sharedpreferences;
SharedPreferences sharedpreferences2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
sharedpreferences2 = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
ListPreference listPreference = (ListPreference) findPreference("Color");
CharSequence entry = listPreference.getEntry();
final String value = listPreference.getValue();
final ListView rel = this.getListView();
if (sharedpreferences2.contains("Color")) {
if (value.toString().equals("Red")) {
rel.setBackgroundColor(Color.RED);
}
if (value.toString().equals("Blue")) {
rel.setBackgroundColor(Color.BLUE);
}
if (value.toString().equalsIgnoreCase("Green")) {
rel.setBackgroundColor(Color.GREEN);
}
}
}
you will need the OnSharedPreferenceChangeListener. Use registerOnSharedPreferenceChangeListener() in your onResume() and override the onSharedPreferenceChanged() method to perform actions on preference change.
Unregister the listener in your onPause() method.
P.S. PreferenceActivity is deprecated, consider using PreferenceFragment instead.

Enable and disable option in PreferenceActivity

I am new to creating PreferenceActivity. My question is how to enable and disable option in preference screen by changing other preference?
My prefs.xml:
<ListPreference
android:entries="#array/units"
android:entryValues="#array/lunits"
android:key="listUnits"
android:summary="Units schosssing"
android:title="Units" android:defaultValue="C"/>
<ListPreference
android:entries="#array/palette"
android:entryValues="#array/lpalette"
android:key="listpalette"
android:summary="Palette schosssing"
android:title="Palette"
android:defaultValue="1"/>
In the listUnits there are 2 options, Celsius and Fahrenheit, so if user selects Celsius the listpalette should get enabled, and if user selects Fahrenheit becomes disabled, how can I do this?
My settings activity:
public class SettingsActivity extends PreferenceActivity
{
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
}
This code may be useful to you. Can take as reference.
First take instance of both of the ListPreference and apply this method.
ListPreference mlistUnits, mlistPalette;
mlistUnits= (ListPreference)findPreference("listUnits");
mlistPalette= (ListPreference)findPreference("listpalette");
mlistUnits.setEnable(false);
mlistPalette.setEnabled(true);
and use below listner
OnPreferenceChangeListener listener = new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// newValue is the value you choose
return false;
}
};
apply listener to ListPreference
mlistPalette.setOnPreferenceChangeListener(listener);
Firstly you can set default value for your listUnits listpreference to celcius or Fahrenheit ,according this you can make enable-disable your second listpreference.
Now when changing your Preference by selecting anyone of them you can follow below procedure.
1) implement OnSharedPreferenceChangeListener in your MyPreferenceFragment class and override the method onSharedPreferenceChanged
2) Code like below in your method
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
if (key.equals("listUnits")) {
final String value = sharedPreferences.getString(key, "");
Preference Pref_cec=findPreference("listpalette");
if (value.equals("celcius")) {
wallpaperPref_admin.setEnabled(true);
}else{
wallpaperPref_admin.setEnabled(false);
}
}
}
Hope it will Help. Let me know if anything missing in my post.
As your second list is evaluated on basic of first list, what you may do
Look for preference click on the First list, get the value of preference clicked.
Using this value simply enable/disable your second list.

Android: Changing a preference via dialog does not update the value

I'm using a PreferenceActivity in my app. Defined the settings.xml as follows -
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Preferences" >
<PreferenceCategory android:title="Email Options" >
<EditTextPreference
android:dialogTitle="#string/pref_email_user_title"
android:key="pref_email_user"
android:summary="#string/pref_email_user_summary"
android:persistent="true"
android:title="#string/pref_email_user_title" />
<EditTextPreference
android:dialogTitle="#string/pref_email_password_title"
android:key="pref_email_password"
android:summary="#string/pref_email_password_summary"
android:persistent="true"
android:title="#string/pref_email_password_title" />
</PreferenceCategory>
Activity as follows -
public class Prefs extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
Which is all you need, right? Apparently not though, because what happens is that I click on the 'email user' setting, it brings up a dialog which I use to type in a string value. However what I typed in isn't getting placed on the Settings screen, I still see the default value.
I notice that the values are getting persisted in the preferences file under /data/data/<package>/shared_prefs
I also don't see these persisted values when I relaunch the app - it shows default values. What's the bit of magic I'm missing?
You need an OnPreferenceChangeListener that will listen for changes on your preferences and automatically update the preference summary.
See this code from the samples in the SDK:
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
You need to bind this to all your preference items, for example like this:
bindPreferenceSummaryToValue(findPreference("username"));
And:
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* #see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}

Is it possible to normalize an Android preference value upon change?

In Android 4, I have a preference value that I want to appear in the standard form E2C56DB5-DFFB-48D2-B060-D0F5A71096E0. But the user may enter the value without dashes. I would like to allow the user to enter it with any combination of whitespace or dashes, and simply have my code normalize it.
I am using the code below, and I see the log line, but it does nothing. I am guessing this is because Android has another Editor object open that overwrites my changes. Is there any other way to accomplish this?
public class UuidFragment extends PreferenceFragment {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
this.getPreferenceScreen().findPreference("pref_uuid").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.toString().length() != 0) {
String normalizedUuid=normalizeUuid(newValue.toString());
// TODO: this code runs but does nothing, I think because after committing the change, there is a higher level editor that commits the old value
// thereby undoing this change
if (!normalizedUuid.equals(newValue.toString())) {
Log.d(TAG, "Adjusting uuid from "+newValue.toString()+" to "+normalizedUuid);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(UuidFragment.this.getActivity());
SharedPreferences.Editor editor = settings.edit();
editor.putString(preference.getKey(), normalizedUuid);
editor.commit();
}
return true;
}
}
});
}
}
Try subclassing EditTextPreference and overriding setText(). In your setText() method, fix up the passed-in string before chaining to the superclass. Then, reference your EditTextPreference subclass from your preference XML.

Categories

Resources