Android Shared Preferences Example

               Android shared preference Example code 

               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

How about we see a straightforward case of android shared preference.






activity_main.xml

File: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MainActivity" >  
  
    <TextView  
        android:id="@+id/txtPrefs"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_centerVertical="true"  
        android:text="Data:" />  
  
    <Button  
        android:id="@+id/storeinformation"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_below="@+id/showinformation"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="18dp"  
        android:text="Store Information" />  
  
    <Button  
        android:id="@+id/showinformation"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentTop="true"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="17dp"  
        android:text="Show Information" />  
      
</RelativeLayout>  


array.xml

File: array.xml
<?xml version="1.0" encoding="utf-8"?>  
 <resources>  
   <string-array name="listOptions">  
     <item>English</item>  
     <item>Hindi</item>  
     <item>Other</item>  
     </string-array>  
  
   <string-array name="listValues">  
     <item>English Language</item>  
     <item>Hindi Language</item>  
     <item>Other Language</item>  
   </string-array>  
     
 </resources>  

prefs.xml
File: prefs.xml
<?xml version="1.0" encoding="utf-8"?>  
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >  
  
   <PreferenceCategory  
   android:summary="Username and password information"  
   android:title="Login information" >  
  <EditTextPreference  
     android:key="username"  
     android:summary="Please enter your login username"  
     android:title="Username" />  
  <EditTextPreference  
     android:key="password"  
     android:summary="Enter your password"  
     android:title="Password" />  
 </PreferenceCategory>  
  
 <PreferenceCategory  
   android:summary="Username and password information"  
   android:title="Settings" >  
  <CheckBoxPreference  
     android:key="checkBox"  
     android:summary="On/Off"  
     android:title="Keep me logged in" />  
  
  <ListPreference  
     android:entries="@array/listOptions"  
     android:entryValues="@array/listValues"  
     android:key="listpref"  
     android:summary="List preference example"  
     android:title="List preference" />  
 </PreferenceCategory>  
</PreferenceScreen>  

Preference  Activity Class
File: PreferenceDemoActivity.java
package com.example.preferences;  
  
import android.os.Bundle;  
import android.preference.PreferenceManager;  
import android.app.Activity;  
import android.content.Intent;  
import android.content.SharedPreferences;  
import android.view.Menu;  
import android.view.View;  
import android.widget.Button;  
import android.widget.TextView;  
  
public class PreferenceDemoActivity extends Activity {  
        TextView textView;  
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
      
           Button storeinformation = (Button) findViewById(R.id.storeinformation);  
           Button showinformation = (Button) findViewById(R.id.showinformation);  
           textView = (TextView) findViewById(R.id.txtPrefs);  
             
           View.OnClickListener listener = new View.OnClickListener() {  
           @Override  
           public void onClick(View v) {  
           switch (v.getId()) {  
            case R.id.storeinformation:  
            Intent intent = new Intent(PreferenceDemoActivity.this,PrefsActivity.class);  
            startActivity(intent);  
           break;  
           case R.id.showinformation:  
              displaySharedPreferences();  
              break;  
           default:  
             break;  
           }  
           }  
           };  
           storeinformation.setOnClickListener(listener);  
           showinformation.setOnClickListener(listener);  
        }  
   
  
        private void displaySharedPreferences() {  
           SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(PreferenceDemoActivity.this);  
           String username = prefs.getString("username""Default NickName");  
           String passw = prefs.getString("password""Default Password");  
           boolean checkBox = prefs.getBoolean("checkBox"false);  
           String listPrefs = prefs.getString("listpref""Default list prefs");  
  
           
           StringBuilder builder = new StringBuilder();  
           builder.append("Username: " + username + "\n");  
           builder.append("Password: " + passw + "\n");  
           builder.append("Keep me logged in: " + String.valueOf(checkBox) + "\n");  
           builder.append("List preference: " + listPrefs);  
           textView.setText(builder.toString());  
      
        }  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        // Inflate the menu; this adds items to the action bar if it is present.  
        getMenuInflater().inflate(R.menu.activity_main, menu);  
        return true;  
    }  
  
}  

PrefsActivity class
File: PrefsActivity.java
package com.example.preferences;  
  
import android.os.Bundle;  
import android.preference.PreferenceActivity;  
  
public class PrefsActivity extends PreferenceActivity{  
@Override  
protected void onCreate(Bundle savedInstanceState) {  
   super.onCreate(savedInstanceState);  
   addPreferencesFromResource(R.xml.prefs);  
}  
}  

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:




















0 comments:

Post a Comment

My Instagram