Thursday, 23 April 2015

Shared Preferences

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

Android Internal Storage Example

We are able to save or read data from the device internal memory. FileInputStream and FileOutputStream classes are used to read and write data into the file.
Here, we are going to read and write data to the internal storage of the device.

Example of reading and writing data to the android internal storage

activity_main.xml

Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the activity_main.xml file will like this:
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.     <EditText  
  8.         android:id="@+id/editText1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentRight="true"  
  12.         android:layout_alignParentTop="true"  
  13.         android:layout_marginRight="20dp"  
  14.         android:layout_marginTop="24dp"  
  15.         android:ems="10" >  
  16.   
  17.         <requestFocus />  
  18.     </EditText>  
  19.   
  20.     <EditText  
  21.         android:id="@+id/editText2"  
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:layout_alignRight="@+id/editText1"  
  25.         android:layout_below="@+id/editText1"  
  26.         android:layout_marginTop="24dp"  
  27.         android:ems="10" />  
  28.   
  29.     <TextView  
  30.         android:id="@+id/textView1"  
  31.         android:layout_width="wrap_content"  
  32.         android:layout_height="wrap_content"  
  33.         android:layout_alignBaseline="@+id/editText1"  
  34.         android:layout_alignBottom="@+id/editText1"  
  35.         android:layout_alignParentLeft="true"  
  36.         android:text="File Name:" />  
  37.   
  38.     <TextView  
  39.         android:id="@+id/textView2"  
  40.         android:layout_width="wrap_content"  
  41.         android:layout_height="wrap_content"  
  42.         android:layout_alignBaseline="@+id/editText2"  
  43.         android:layout_alignBottom="@+id/editText2"  
  44.         android:layout_alignParentLeft="true"  
  45.         android:text="Data:" />  
  46.   
  47.     <Button  
  48.         android:id="@+id/button1"  
  49.         android:layout_width="wrap_content"  
  50.         android:layout_height="wrap_content"  
  51.         android:layout_alignLeft="@+id/editText2"  
  52.         android:layout_below="@+id/editText2"  
  53.         android:layout_marginLeft="70dp"  
  54.         android:layout_marginTop="16dp"  
  55.         android:text="save" />  
  56.   
  57.     <Button  
  58.         android:id="@+id/button2"  
  59.         android:layout_width="wrap_content"  
  60.         android:layout_height="wrap_content"  
  61.         android:layout_alignBaseline="@+id/button1"  
  62.         android:layout_alignBottom="@+id/button1"  
  63.         android:layout_toRightOf="@+id/button1"  
  64.         android:text="read" />  
  65.   
  66. </RelativeLayout>  

Activity class

Let's write the code to write and read data from the internal storage.
File: MainActivity.java
  1. package com.example.internalstorage;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStreamReader;  
  9.   
  10. import android.os.Bundle;  
  11. import android.app.Activity;  
  12. import android.content.Context;  
  13. import android.view.Menu;  
  14. import android.view.View;  
  15. import android.view.View.OnClickListener;  
  16. import android.widget.Button;  
  17. import android.widget.EditText;  
  18. import android.widget.Toast;  
  19.   
  20. public class MainActivity extends Activity {  
  21.     EditText editTextFileName,editTextData;  
  22.     Button saveButton,readButton;  
  23.     @Override  
  24.     protected void onCreate(Bundle savedInstanceState) {  
  25.         super.onCreate(savedInstanceState);  
  26.         setContentView(R.layout.activity_main);  
  27.           
  28.         editTextFileName=(EditText)findViewById(R.id.editText1);  
  29.         editTextData=(EditText)findViewById(R.id.editText2);  
  30.         saveButton=(Button)findViewById(R.id.button1);  
  31.         readButton=(Button)findViewById(R.id.button2);  
  32.           
  33.         //Performing Action on Read Button  
  34.         saveButton.setOnClickListener(new OnClickListener(){  
  35.   
  36.             @Override  
  37.             public void onClick(View arg0) {  
  38.                 String filename=editTextFileName.getText().toString();  
  39.                 String data=editTextData.getText().toString();  
  40.                   
  41.                 FileOutputStream fos;  
  42.                    try {  
  43.                     fos = openFileOutput(filename, Context.MODE_PRIVATE);  
  44.                     //default mode is PRIVATE, can be APPEND etc.  
  45.                     fos.write(data.getBytes());  
  46.                     fos.close();  
  47.                      
  48.                     Toast.makeText(getApplicationContext(),filename + " saved",  
  49.                             Toast.LENGTH_LONG).show();  
  50.                       
  51.                      
  52.                    } catch (FileNotFoundException e) {e.printStackTrace();}  
  53.                    catch (IOException e) {e.printStackTrace();}  
  54.                   
  55.             }  
  56.               
  57.         });  
  58.           
  59.         //Performing Action on Read Button  
  60.         readButton.setOnClickListener(new OnClickListener(){  
  61.   
  62.             @Override  
  63.             public void onClick(View arg0) {  
  64.                 String filename=editTextFileName.getText().toString();  
  65.                 StringBuffer stringBuffer = new StringBuffer();    
  66.                 try {  
  67.                     //Attaching BufferedReader to the FileInputStream by the help of InputStreamReader  
  68.                     BufferedReader inputReader = new BufferedReader(new InputStreamReader(  
  69.                             openFileInput(filename)));  
  70.                     String inputString;  
  71.                     //Reading data line by line and storing it into the stringbuffer                
  72.                     while ((inputString = inputReader.readLine()) != null) {  
  73.                         stringBuffer.append(inputString + "\n");  
  74.                     }  
  75.                       
  76.                 } catch (IOException e) {  
  77.                     e.printStackTrace();  
  78.                 }  
  79.                 //Displaying data on the toast  
  80.                 Toast.makeText(getApplicationContext(),stringBuffer.toString(),  
  81.                         Toast.LENGTH_LONG).show();  
  82.                   
  83.             }  
  84.               
  85.         });  
  86.     }  
  87.   
  88.     @Override  
  89.     public boolean onCreateOptionsMenu(Menu menu) {  
  90.         // Inflate the menu; this adds items to the action bar if it is present.  
  91.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  92.         return true;  
  93.     }  
  94.   
  95. }  

Android External Storage Example

Like internal storage, we are able to save or read data from the device external memory such as sdcard. FileInputStream and FileOutputStream classes are used to read and write data into the file.

Example of reading and writing data in the android external storage

activity_main.xml

Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the activity_main.xml file will like this:
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.     <EditText  
  8.         android:id="@+id/editText1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentRight="true"  
  12.         android:layout_alignParentTop="true"  
  13.         android:layout_marginRight="20dp"  
  14.         android:layout_marginTop="24dp"  
  15.         android:ems="10" >  
  16.   
  17.         <requestFocus />  
  18.     </EditText>  
  19.   
  20.     <EditText  
  21.         android:id="@+id/editText2"  
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:layout_alignRight="@+id/editText1"  
  25.         android:layout_below="@+id/editText1"  
  26.         android:layout_marginTop="24dp"  
  27.         android:ems="10" />  
  28.   
  29.     <TextView  
  30.         android:id="@+id/textView1"  
  31.         android:layout_width="wrap_content"  
  32.         android:layout_height="wrap_content"  
  33.         android:layout_alignBaseline="@+id/editText1"  
  34.         android:layout_alignBottom="@+id/editText1"  
  35.         android:layout_alignParentLeft="true"  
  36.         android:text="File Name:" />  
  37.   
  38.     <TextView  
  39.         android:id="@+id/textView2"  
  40.         android:layout_width="wrap_content"  
  41.         android:layout_height="wrap_content"  
  42.         android:layout_alignBaseline="@+id/editText2"  
  43.         android:layout_alignBottom="@+id/editText2"  
  44.         android:layout_alignParentLeft="true"  
  45.         android:text="Data:" />  
  46.   
  47.     <Button  
  48.         android:id="@+id/button1"  
  49.         android:layout_width="wrap_content"  
  50.         android:layout_height="wrap_content"  
  51.         android:layout_alignLeft="@+id/editText2"  
  52.         android:layout_below="@+id/editText2"  
  53.         android:layout_marginLeft="70dp"  
  54.         android:layout_marginTop="16dp"  
  55.         android:text="save" />  
  56.   
  57.     <Button  
  58.         android:id="@+id/button2"  
  59.         android:layout_width="wrap_content"  
  60.         android:layout_height="wrap_content"  
  61.         android:layout_alignBaseline="@+id/button1"  
  62.         android:layout_alignBottom="@+id/button1"  
  63.         android:layout_toRightOf="@+id/button1"  
  64.         android:text="read" />  
  65.   
  66. </RelativeLayout>  

Provide permission for the external storage

You need to provide the WRITE_EXTERNAL_STORAGE permission.
  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
File: Activity_Manifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest   
  3.   
  4. xmlns:android="http://schemas.android.com/apk/res/android"  
  5.     package="com.example.externalstorage"  
  6.     android:versionCode="1"  
  7.     android:versionName="1.0" >  
  8.   
  9.     <uses-sdk  
  10.         android:minSdkVersion="8"  
  11.         android:targetSdkVersion="16" />  
  12. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  13.   
  14.     <application  
  15.         android:allowBackup="true"  
  16.         android:icon="@drawable/ic_launcher"  
  17.         android:label="@string/app_name"  
  18.         android:theme="@style/AppTheme" >  
  19.         <activity  
  20.             android:name="com.example.externalstorage.MainActivity"  
  21.             android:label="@string/app_name" >  
  22.             <intent-filter>  
  23.                 <action android:name="android.intent.action.MAIN" />  
  24.   
  25.                 <category android:name="android.intent.category.LAUNCHER" />  
  26.             </intent-filter>  
  27.         </activity>  
  28.     </application>  
  29.   
  30. </manifest>  

Activity class

Let's write the code to write and read data from the android external storage.
File: MainActivity.java
  1. package com.example.externalstorage;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStreamReader;  
  10. import java.io.OutputStreamWriter;  
  11.   
  12. import android.os.Bundle;  
  13. import android.app.Activity;  
  14. import android.content.Context;  
  15. import android.view.Menu;  
  16. import android.view.View;  
  17. import android.view.View.OnClickListener;  
  18. import android.widget.Button;  
  19. import android.widget.EditText;  
  20. import android.widget.Toast;  
  21.   
  22. public class MainActivity extends Activity {  
  23.     EditText editTextFileName,editTextData;  
  24.     Button saveButton,readButton;  
  25.     @Override  
  26.     protected void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.activity_main);  
  29.           
  30.         editTextFileName=(EditText)findViewById(R.id.editText1);  
  31.         editTextData=(EditText)findViewById(R.id.editText2);  
  32.         saveButton=(Button)findViewById(R.id.button1);  
  33.         readButton=(Button)findViewById(R.id.button2);  
  34.           
  35.         //Performing action on save button  
  36.         saveButton.setOnClickListener(new OnClickListener(){  
  37.   
  38.             @Override  
  39.             public void onClick(View arg0) {  
  40.                 String filename=editTextFileName.getText().toString();  
  41.                 String data=editTextData.getText().toString();  
  42.                   
  43.                 FileOutputStream fos;  
  44.                    try {  
  45.                        File myFile = new File("/sdcard/"+filename);  
  46.                         myFile.createNewFile();  
  47.                         FileOutputStream fOut = new   
  48.   
  49. FileOutputStream(myFile);  
  50.                         OutputStreamWriter myOutWriter = new   
  51.   
  52. OutputStreamWriter(fOut);  
  53.                         myOutWriter.append(data);  
  54.                         myOutWriter.close();  
  55.                         fOut.close();  
  56.                      
  57.             Toast.makeText(getApplicationContext(),filename + "   
  58.   
  59. saved",Toast.LENGTH_LONG).show();  
  60.                       
  61.                      
  62.                    } catch (FileNotFoundException e) {e.printStackTrace();}  
  63.                    catch (IOException e) {e.printStackTrace();}  
  64.                   
  65.             }  
  66.               
  67.         });  
  68.   
  69.         //Performing action on Read Button  
  70.         readButton.setOnClickListener(new OnClickListener(){  
  71.   
  72.             @Override  
  73.             public void onClick(View arg0) {  
  74.                 String filename=editTextFileName.getText().toString();  
  75.                 StringBuffer stringBuffer = new StringBuffer();    
  76.                 String aDataRow = "";  
  77.                 String aBuffer = "";  
  78.                 try {  
  79.                     File myFile = new File("/sdcard/"+filename);  
  80.                     FileInputStream fIn = new FileInputStream(myFile);  
  81.                     BufferedReader myReader = new BufferedReader(  
  82.                             new InputStreamReader(fIn));  
  83.                       
  84.                     while ((aDataRow = myReader.readLine()) != null) {  
  85.                         aBuffer += aDataRow + "\n";  
  86.                     }  
  87.                     myReader.close();  
  88.                       
  89.                 } catch (IOException e) {  
  90.                     e.printStackTrace();  
  91.                 }  
  92.                 Toast.makeText(getApplicationContext  
  93.   
  94. (),aBuffer,Toast.LENGTH_LONG).show();  
  95.                   
  96.             }  
  97.               
  98.         });  
  99.     }  
  100.   
  101.     @Override  
  102.     public boolean onCreateOptionsMenu(Menu menu) {  
  103.         // Inflate the menu; this adds items to the action bar if it is present.  
  104.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  105.         return true;  
  106.     }  
  107.   
  108. }  

No comments:

Post a Comment