Android development: where to put static key / value pairs?

I have a list of static key / value pairs that I need to include in my project, like this one:

givenName : First Name
sn        : Last Name
mail      : Email
... snip ...

Where in the Android project would I put this?

Thanks Eric

+3
source share
3 answers

You need an XML file stored in res/values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="givenName">First Name</string>
    <string name="sn">Last Name</string>
    <string name="mail">Email</string>
</resources>

Here is how you can access values ​​from other xmls:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/givenName" />

Or you can access the value from Java code:

String string = getString(R.string.givenName);
Log.d("Test", string); // Outputs "First Name" to LogCat console.

Check out this Android Dev guide for a complete reference on String resources.

+1
source

Android provides a predefined content provider shell called SharedPreferences, which is specifically designed to store primitives in key-value pairs.

        SharedPreferences mySharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(getApplication());
        mySharedPrefs.edit().putString(key, value).commit();

getApplication() .

        SharedPreferences mySharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context);
        String value = mySharedPrefs.getString(key, null);

key null, .

+2

If you really have to use static / globals, put them in your own class that extends Application. Like this:

public classYourApplication extends Application {
    protected Bar myBar;

    public Bar getBar() { return myBar; }
    public void setBar(Bar bar) { myBar = bar; }
    ...
}

Declare that you are using your own application class using the manifest.

<application
    android:icon="@drawable/ic_launcher_noteit1"
    android:label="@string/app_name" 
    android:theme="@style/App_Theme"
    android:name="YourApplication" 
    android:debuggable="true">

Now you can access your application object from any activity using (YourApplication) getApplication (). Please note that this is not a recommended method. The recommended method is to use a singleton pattern. (answer from one of my answers to the question)

+1
source

All Articles