Monday, July 16, 2012

Store Data in Mobile Memory using SharedPreference



Click Here to download source code

Package Name   :   selva.shared

Project Name     :   SharedPreferences

Version              :   1.5 ( Support 1.5 and above versions)


main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

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

 
    <Button
        android:id="@+id/button1"
        android:layout_width="98dp"
        android:layout_height="wrap_content"
        android:text="Save" />

</LinearLayout>



m1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <Button
        android:id="@+id/button"
        android:layout_width="140dp"
        android:layout_height="wrap_content"
        android:text="View Saved Data" />
   
</LinearLayout>


SharedPreferencesActivity.java


package selva.shared;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SharedPreferencesActivity extends Activity
{
     public SharedPreferences prefs;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button btn=(Button) findViewById(R.id.button1);
       
      btn.setOnClickListener(new View.OnClickListener()
      {
       
        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
       
               String str="www.androidprogramz.in";
                int no=234; 
                float fno=234.234f;
               
                prefs = getSharedPreferences("detail", MODE_PRIVATE);
                      // detail is sharedpreference name
                SharedPreferences.Editor editor = prefs.edit();
               
                editor.putString("Urlname",str);
                // To save str value in Urlname
                editor.putInt("Intvalue", no);
               // To save no value in Intvalue
                editor.putFloat("Floatvalue", fno);
                
// To save fno value in Floatvalue
                editor.commit();
           
           
            Intent i=new Intent(SharedPreferencesActivity.this,Anotheractivity.class);
            startActivity(i);
           
        }
    });
       
       
    }
}



Anotheractivity.java



package selva.shared;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Anotheractivity extends Activity
{
    public SharedPreferences prefs;
   
      public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.m1);
       
            Button btn=(Button) findViewById(R.id.button);
   
             prefs = getSharedPreferences("detail", MODE_PRIVATE);
            
                final String name=prefs.getString("Urlname", "novalue");
                     // To get name value from Urlname
               final int val=prefs.getInt("Intvalue", 0);
                       // To get val value from Intvlue
               final float fval=prefs.getFloat("Floatvalue", 0);
                     
// To get fval value from Floatvalue
            btn.setOnClickListener(new View.OnClickListener()
            {
               
                @Override
                public void onClick(View v)
                {
                    // TODO Auto-generated method stub
                LinearLayout l=(LinearLayout) findViewById(R.id.linearlayout);
               
                TextView tv=new TextView(Anotheractivity.this);
                tv.setText(name);
                tv.setTextColor(Color.GREEN);
                l.addView(tv);
               
                TextView tv1=new TextView(Anotheractivity.this);
                tv1.setText(Integer.toString(val));
                tv1.setTextColor(Color.GREEN);
                l.addView(tv1);
               
                TextView tv2=new TextView(Anotheractivity.this);
                tv2.setText(Float.toString(fval));
                tv2.setTextColor(Color.GREEN);
                l.addView(tv2);
               
           
                }
            });
             
             
        }

}

   note : to clear sharedpreference 

               prefs = getSharedPreferences("detail", MODE_PRIVATE);
                    
                SharedPreferences.Editor editor = prefs.edit();
              
                editor.clear(); // to clear all values in detail                

                editor.commit();

   note 1: to remove one particular value

              prefs = getSharedPreferences("detail", MODE_PRIVATE);
                    
                SharedPreferences.Editor editor = prefs.edit();
              
                editor.remove("Urlname"); // to remove paricular value from detail                

                editor.commit();



  AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="selva.shared"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="3" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".SharedPreferencesActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
             android:label="@string/app_name"
             android:name=".Anotheractivity">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

OUTPUT:





















click save button and View Saved Data











































Click Here to download source code


1 comment:

  1. Hi..

    My listview using sharedpreferences data is not updating the row. It has only one row which replaces new value each time.

    How to append listview with new and old data without replacing it..

    Thanks

    ReplyDelete