Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

Android Preferences


Android shared preference is used to store and retrieve primitive information. In android, string, integer, long, number etc. are considered as primitive data type.

Android Shared preferences are used to store data in key and value pair so that we can retrieve the value on the basis of key.

It is widely used to get information from user such as in settings.

Android Preferences Example

Let’s see a simple example of android shared preference.

preference-directory

activity_main.xml

Drag one textview and two buttons from the pallete.

File: activity_main.xml
  1. <RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
  2.     xmlns:tools=“http://schemas.android.com/tools”
  3.     android:layout_width=“match_parent”
  4.     android:layout_height=“match_parent”
  5.     tools:context=“.MainActivity” >
  6.     <TextView
  7.         android:id=“@+id/txtPrefs”
  8.         android:layout_width=“wrap_content”
  9.         android:layout_height=“wrap_content”
  10.         android:layout_centerVertical=“true”
  11.         android:text=“Data:” />
  12.     <Button
  13.         android:id=“@+id/storeinformation”
  14.         android:layout_width=“wrap_content”
  15.         android:layout_height=“wrap_content”
  16.         android:layout_below=“@+id/showinformation”
  17.         android:layout_centerHorizontal=“true”
  18.         android:layout_marginTop=“18dp”
  19.         android:text=“Store Information” />
  20.     <Button
  21.         android:id=“@+id/showinformation”
  22.         android:layout_width=“wrap_content”
  23.         android:layout_height=“wrap_content”
  24.         android:layout_alignParentTop=“true”
  25.         android:layout_centerHorizontal=“true”
  26.         android:layout_marginTop=“17dp”
  27.         android:text=“Show Information” />
  28. </RelativeLayout>

array.xml

It is created inside res/values directory.

File: array.xml
  1. <?xml version=“1.0” encoding=“utf-8”?>
  2.  <resources>
  3.    <string-array name=“listOptions”>
  4.      <item>English</item>
  5.      <item>Hindi</item>
  6.      <item>Other</item>
  7.      </string-array>
  8.    <string-array name=“listValues”>
  9.      <item>English Language</item>
  10.      <item>Hindi Language</item>
  11.      <item>Other Language</item>
  12.    </string-array>
  13.  </resources>

prefs.xml

It is created inside res/xml directory.

File: prefs.xml
  1. <?xml version=“1.0” encoding=“utf-8”?>
  2. <PreferenceScreen xmlns:android=“http://schemas.android.com/apk/res/android” >
  3.    <PreferenceCategory
  4.    android:summary=“Username and password information”
  5.    android:title=“Login information” >
  6.   <EditTextPreference
  7.      android:key=“username”
  8.      android:summary=“Please enter your login username”
  9.      android:title=“Username” />
  10.   <EditTextPreference
  11.      android:key=“password”
  12.      android:summary=“Enter your password”
  13.      android:title=“Password” />
  14.  </PreferenceCategory>
  15.  <PreferenceCategory
  16.    android:summary=“Username and password information”
  17.    android:title=“Settings” >
  18.   <CheckBoxPreference
  19.      android:key=“checkBox”
  20.      android:summary=“On/Off”
  21.      android:title=“Keep me logged in” />
  22.   <ListPreference
  23.      android:entries=“@array/listOptions”
  24.      android:entryValues=“@array/listValues”
  25.      android:key=“listpref”
  26.      android:summary=“List preference example”
  27.      android:title=“List preference” />
  28.  </PreferenceCategory>
  29. </PreferenceScreen>

Preference Demo Activity Class

File: PreferenceDemoActivity.java
  1. package com.example.preferences;
  2. import android.os.Bundle;
  3. import android.preference.PreferenceManager;
  4. import android.app.Activity;
  5. import android.content.Intent;
  6. import android.content.SharedPreferences;
  7. import android.view.Menu;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import android.widget.TextView;
  11. public class PreferenceDemoActivity extends Activity {
  12.         TextView textView;
  13.         @Override
  14.         public void onCreate(Bundle savedInstanceState) {
  15.            super.onCreate(savedInstanceState);
  16.            setContentView(R.layout.activity_main);
  17.            Button storeinformation = (Button) findViewById(R.id.storeinformation);
  18.            Button showinformation = (Button) findViewById(R.id.showinformation);
  19.            textView = (TextView) findViewById(R.id.txtPrefs);
  20.            View.OnClickListener listener = new View.OnClickListener() {
  21.            @Override
  22.            public void onClick(View v) {
  23.            switch (v.getId()) {
  24.             case R.id.storeinformation:
  25.             Intent intent = new Intent(PreferenceDemoActivity.this,PrefsActivity.class);
  26.             startActivity(intent);
  27.            break;
  28.            case R.id.showinformation:
  29.               displaySharedPreferences();
  30.               break;
  31.            default:
  32.              break;
  33.            }
  34.            }
  35.            };
  36.            storeinformation.setOnClickListener(listener);
  37.            showinformation.setOnClickListener(listener);
  38.         }
  39.         private void displaySharedPreferences() {
  40.            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(PreferenceDemoActivity.this);
  41.            String username = prefs.getString(“username”“Default NickName”);
  42.            String passw = prefs.getString(“password”“Default Password”);
  43.            boolean checkBox = prefs.getBoolean(“checkBox”false);
  44.            String listPrefs = prefs.getString(“listpref”“Default list prefs”);
  45.            StringBuilder builder = new StringBuilder();
  46.            builder.append(“Username: “ + username + “\n”);
  47.            builder.append(“Password: “ + passw + “\n”);
  48.            builder.append(“Keep me logged in: “ + String.valueOf(checkBox) + “\n”);
  49.            builder.append(“List preference: “ + listPrefs);
  50.            textView.setText(builder.toString());
  51.         }
  52.     @Override
  53.     public boolean onCreateOptionsMenu(Menu menu) {
  54.         // Inflate the menu; this adds items to the action bar if it is present.
  55.         getMenuInflater().inflate(R.menu.activity_main, menu);
  56.         return true;
  57.     }
  58. }

PrefsActivity class

File: PrefsActivity.java
  1. package com.example.preferences;
  2. import android.os.Bundle;
  3. import android.preference.PreferenceActivity;
  4. public class PrefsActivity extends PreferenceActivity{
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7.    super.onCreate(savedInstanceState);
  8.    addPreferencesFromResource(R.xml.prefs);
  9. }
  10. }

download this android example

Output:

android-preference-output1

Click on the store information button.

android-preference-output2

Now click on username and store information. Like username, store password and click on the checkbox.

android-preference-output3

Now click on the list preference to store language information.

android-preference-output4

Now click on the back button to come to first activity. Now click on the show information button.

android-preference-output5

Comments

comments