Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a PreferenceActivity use a custom preference file

Tags:

My first attempt at preferences was without knowledge of PreferenceActivity. So now I have an app that stores all user preferences in a specific preference file.

I want to migrate to using a PreferenceActivity but I also want my users to keep their preferences.

Is there a way to tell my PreferenceActivity to use that specific file for all preferences?

like image 553
Yashima Avatar asked Mar 02 '11 15:03

Yashima


People also ask

How to use preference fragment?

To inflate from XML, use the addPreferencesFromResource(int) . The root element should be a PreferenceScreen . Subsequent elements can point to actual Preference subclasses. As mentioned above, subsequent PreferenceScreen in the hierarchy will result in the screen break.

What is PreferenceScreen?

androidx.preference.PreferenceScreen. A top-level container that represents a settings screen. This is the root component of your Preference hierarchy. A PreferenceFragmentCompat points to an instance of this class to show the preferences.

What is preference framework in Android?

What is the Preferences Framework? Android system provides many ways to save data for your application. One of them is Preferences Framework , through Android preference framework we can easily develop screen that allows user to modify preferences.


2 Answers

It may be too late to post this but you can find a nice solution here

  • How to make PreferenceActivity use non-default SharedPreferences

You set the name of the default shared preferences file beforehand like this:

public class MyPreferencesActivity extends PreferenceActivity {     protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);           PreferenceManager prefMgr = getPreferenceManager();          prefMgr.setSharedPreferencesName("my_preferences");          prefMgr.setSharedPreferencesMode(MODE_WORLD_READABLE);           addPreferencesFromResource(R.xml.preferences);     } } 

I hope this helps somebody.

Regards.

like image 117
emmanuel.aquino Avatar answered Oct 14 '22 09:10

emmanuel.aquino


You could read all the preferences at the beginning of your app, and then store them in the Preferences using

Editor e = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit(); e.putBoolean("yourPreference", true); e.putString("yourOtherPreference", "This is the Value"); ... e.commit(); 

I hope that helps

like image 36
raukodraug Avatar answered Oct 14 '22 10:10

raukodraug