Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Android preferences without magic strings

Tags:

android

Im using Androids built in way of handling preferences which works by writing all settings in an xml file. It's really nice but I can't find any good way of doing it without using magic strings in the xml and Java code.

The only way I could think of is to save the preference key as String but that doesn't feels right either. Anyone got a good way of solving this?

like image 524
mr-F8 Avatar asked May 17 '11 06:05

mr-F8


1 Answers

You can move your "magic string" to string resources:

In you preference xml file:

<EditTextPreference
        android:key="@string/preferences_pdn_key"
        android:title="@string/preferences_pdn_title"
        android:summary="@string/preferences_pdn_summary"
        android:dialogMessage="@string/input_pdn_message" />

In your values/strings.xml files:

...
<string name="preferences_pdn_key">pdn</string>
...

You then can reference preference from your Activity or PreferenceActivity:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pdnKey = getString(R.string.prefernece_pdn_key);
String pdn = sharedPreferences.getString(pdnKey, null);

If you don't like to fetch preference keys from string resources all the time you can do yet another trick:

public class PreferenceNames {

    /* categories */ 
    public static final String LoginCategory = MyApplication.getResourceString(R.string.preferences_login_category_key);
    ...

    /* preferences */   
    public static final String Pdn = MyApplication.getResourceString(R.string.preferences_pdn_key);
    ...
}

So you can now reference you preference key next way:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pdn = sharedPreferences.getString(PreferenceNames.Pdn, null);

And here is how your MyApplication class should look like:

public class MyApplication extends Application {    
    private static VvmApplication s_instance;

    public MyApplication(){
        s_instance = this;
    }

    public static Context getContext(){
        return s_instance;
    }

    public static String getResourceString(int resId){
        return getContext().getString(resId);       
    }
}

Plus you need to add next thing to your AndroidManifest.xml:

<application android:name="com.mypackage.application.MyApplication" ... >
...
</application>
like image 188
inazaruk Avatar answered Oct 02 '22 20:10

inazaruk