AdSense

AdSense3

Saturday 22 August 2015

Android Preferences Example

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.
android preference directory output 1

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.   
  7.     <TextView  
  8.         android:id="@+id/txtPrefs"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_centerVertical="true"  
  12.         android:text="Data:" />  
  13.   
  14.     <Button  
  15.         android:id="@+id/storeinformation"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:layout_below="@+id/showinformation"  
  19.         android:layout_centerHorizontal="true"  
  20.         android:layout_marginTop="18dp"  
  21.         android:text="Store Information" />  
  22.   
  23.     <Button  
  24.         android:id="@+id/showinformation"  
  25.         android:layout_width="wrap_content"  
  26.         android:layout_height="wrap_content"  
  27.         android:layout_alignParentTop="true"  
  28.         android:layout_centerHorizontal="true"  
  29.         android:layout_marginTop="17dp"  
  30.         android:text="Show Information" />  
  31.       
  32. </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.   
  9.    <string-array name="listValues">  
  10.      <item>English Language</item>  
  11.      <item>Hindi Language</item>  
  12.      <item>Other Language</item>  
  13.    </string-array>  
  14.      
  15.  </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.   
  4.    <PreferenceCategory  
  5.    android:summary="Username and password information"  
  6.    android:title="Login information" >  
  7.   <EditTextPreference  
  8.      android:key="username"  
  9.      android:summary="Please enter your login username"  
  10.      android:title="Username" />  
  11.   <EditTextPreference  
  12.      android:key="password"  
  13.      android:summary="Enter your password"  
  14.      android:title="Password" />  
  15.  </PreferenceCategory>  
  16.   
  17.  <PreferenceCategory  
  18.    android:summary="Username and password information"  
  19.    android:title="Settings" >  
  20.   <CheckBoxPreference  
  21.      android:key="checkBox"  
  22.      android:summary="On/Off"  
  23.      android:title="Keep me logged in" />  
  24.   
  25.   <ListPreference  
  26.      android:entries="@array/listOptions"  
  27.      android:entryValues="@array/listValues"  
  28.      android:key="listpref"  
  29.      android:summary="List preference example"  
  30.      android:title="List preference" />  
  31.  </PreferenceCategory>  
  32. </PreferenceScreen>  

Preference Demo Activity Class

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

PrefsActivity class

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

Output:

android preference example output 1
Click on the store information button.
android preference example output 2
Now click on username and store information. Like username, store password and click on the checkbox.
android preference example output 3
Now click on the list preference to store language information.
android preference example output 4
Now click on the back button to come to first activity. Now click on the show information button.
android preference example output 5

1 comment:

  1. this is defenitely something more challenging and advance topic
    But you explained it very good.thank you kundan

    ReplyDelete