addPreferencesFromResource(int preferencesResId) deprecated ?

addPreferencesFromResource(int preferencesResId) deprecated no matter what is the API level of android. The solution is to use the PreferenceFragmentCompat that is provided in the   Preferences Support v7 Library. Creating your preferences from XML files means less code and a consistent user experience across apps. You can use the PreferenceFragmentCompat in any acitivity as your need.

Let’s make the android settings having the ListPreference for a single choice.

add this dependency to app’s build.gradle.

compile 'com.android.support:preference-v7:23.0.0'

make the layout file in the res/xml directory with name preferences.xml as:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <ListPreference
        android:defaultValue="popular"
        android:entries="@array/categories"
        android:entryValues="@array/categories_value"
        android:summary="Select categories of movies"
        android:title="Categories"
        android:key="@string/movies_categories_key" />
</PreferenceScreen>

add the following for the entries and entryvalues in values/array.xml as:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="categories">
        <item>Popular Movies</item>
        <item>Top Rated Movies</item>
    </string-array>
    <string-array name="categories_value">
        <item>popular</item>
        <item>top_rated</item>
    </string-array>
</resources>

add the following values in strings.xml

<string name="movies_categories_key">categoriesKey</string>
<string name="default_movies_categories">popular</string>
make the fragment that extends the PreferenceFragmentCompat having name SettingsFragment.java as:
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.preference.ListPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;

/**
 * shows the settings option for choosing the movie categories in ListPreference.
 */
public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
    private static final String TAG = SettingsFragment.class.getSimpleName();

    SharedPreferences sharedPreferences;

    @Override
    public void onCreatePreferences(Bundle bundle, String s) {
        //add xml
        addPreferencesFromResource(R.xml.preferences);

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

        onSharedPreferenceChanged(sharedPreferences, getString(R.string.movies_categories_key));
    }


    @Override
    public void onResume() {
        super.onResume();
        //unregister the preferenceChange listener
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        Preference preference = findPreference(key);
        if (preference instanceof ListPreference) {
            ListPreference listPreference = (ListPreference) preference;
            int prefIndex = listPreference.findIndexOfValue(sharedPreferences.getString(key, ""));
            if (prefIndex >= 0) {
                preference.setSummary(listPreference.getEntries()[prefIndex]);
            }
        } else {
            preference.setSummary(sharedPreferences.getString(key, ""));

        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //unregister the preference change listener
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }
}
we can see in the above code that the preference.xml is linked to the SettingsFragment as:
  addPreferencesFromResource(R.xml.preferences);

The value’s that are in the android settings are stored in the android Default Shared Preferences.
Values that are stored in the Default shared Preferences can get using the http://developer.android.com/reference/android/preference/PreferenceManager.html
as:

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String moviesCategories=sharedPreferences.getString(getString(R.string.movies_categories_key),getString(R.string.default_movies_categories));

SharedPreferences.OnSharedPreferenceChangeListener is used for listening the on change the preference item. Hence I have impletmented in SettingsFragment.java.

Let’s look at the override method  by implementing the SharedPreferences.OnSharedPreferenceChangeListener .

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    Preference preference = findPreference(key);
    if (preference instanceof ListPreference) {
        ListPreference listPreference = (ListPreference) preference;
        int prefIndex = listPreference.findIndexOfValue(sharedPreferences.getString(key, ""));
        if (prefIndex >= 0) {
            preference.setSummary(listPreference.getEntries()[prefIndex]);
        }
    } else {
        preference.setSummary(sharedPreferences.getString(key, ""));

    }
}

 

In the case of the ListPreference we have to get the corresponding value of respective key. So that we have to identify the List Preference and get value of respective key changed  as:

//find the preference
Preference preference = findPreference(key);
 if (preference instanceof ListPreference) {
        //if it is listpreference cast preference to ListPreference
        ListPreference listPreference = (ListPreference) preference;
        //find the index of changed value in settings.
        int prefIndex = listPreference.findIndexOfValue(sharedPreferences.getString(key, ""));
        if (prefIndex >= 0) {
            //finally set's it value changed 
            preference.setSummary(listPreference.getEntries()[prefIndex]);
        }
    }

If it is not the ListPreference we can directly set the value changed as

preference.setSummary(sharedPreferences.getString(key, ""));

finally you can add  SettingsFragment.java to Any Activity as :

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.example.popularmovies.R;
import com.example.popularmovies.activities.base.BaseActivity;
import com.example.popularmovies.fragment.SettingsFragment;

import butterknife.Bind;



/**
 * loads the settings fragment.
 */
public class SettingsActivity extends BaseActivity {

    @Bind(R.id.toolbar)
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content, new SettingsFragment())
                .commit();

    }

    @Override
    protected int getLayout() {
        return R.layout.activity_settings;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_settings, menu);
        return true;
    }

    @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.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
        }

        return super.onOptionsItemSelected(item);
    }

}

if you want to the complete code of this how it is implemented you can go on my git


 

 

 

Advertisements