Tuesday, 29 September 2015

Shared Preferences in Android

Android provides several storage options to store persistent data application data. The solution you choose depends on on your specific needs, such as whether tha data should be private to your application or accessible to other applicaitons (and the user) and how much space your data requires.

Data storage options in Android:


1.                 SharedPreferences: Store private primitive data in key-value pairs.
2.                 Internal Storage: Store private data on the device memory.
3.                 External Storage: Store public data on shared external storage.
4.                 SQLiteDatabase: Store structured data in private database.
5.                 Network Connection: Store data on the web with your own network server.
SharedPreferences: The SharedPreferences class provides general framework that allows you to save  and retreive persistent key-value pairs of primitive datatypes .

you can use SharedPreferences to save any primitive data : booleans, floats, ints, longs, Strings. The data will persist across user sessions (even your application kills).

To get SharedPrferences object for your application use the following method
getSharedPrefeneces()

Ex:
 SharedPreferences sp = getSharedPrefereces(getApplicationContext(),0);


-->call edit() to get a SharedPreferences.Editor to get writing permissions to store the data in SharedPreferences.

-->Add values with methods such as putBoolean(), putString(), putInt(), putLong() and putFloat()

-->commit the new values with commit()

To read values: To read values , use SharedPreferences methods such as getBoolean(), getString(), getInt(), getFloat() and getLong()


activity_main.xml
---------------------

<LinearLayout
   
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"
   
android:orientation="vertical">


    <
EditText
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:id="@+id/editText"
       
android:hint="enter name"
       
android:layout_marginTop="7dp" />

    <
EditText
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:id="@+id/editText2"
       
android:hint="enter location"
       
android:layout_marginTop="7dp" />

    <
EditText
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:id="@+id/editText3"
       
android:hint="enter email"
       
android:layout_marginTop="7dp" />

    <
Button
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Save"
       
android:id="@+id/button"
       
android:layout_gravity="center_horizontal"
       
android:layout_marginTop="15dp" />

    <
Button
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Show"
       
android:id="@+id/button2"
       
android:layout_gravity="center_horizontal"
       
android:layout_marginTop="15dp" />
</
LinearLayout>
MainActivity.Java
------------------------
package com.android.anil.sharedprefrences;



import android.content.Intent;

import android.content.SharedPreferences;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;



public class MainActivity extends AppCompatActivity {

    Button savebtn,showbtn;

    EditText uname,uloc,uemail;

    String  name1,loc1,email1;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        uname=(EditText)findViewById(R.id.editText);

        uloc=(EditText)findViewById(R.id.editText2);

        uemail=(EditText)findViewById(R.id.editText3);

        savebtn=(Button)findViewById(R.id.button);

        showbtn=(Button)findViewById(R.id.button2);

        savebtn.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                name1=uname.getText().toString();

                loc1=uloc.getText().toString();

                email1=uemail.getText().toString();

                SharedPreferences sp=getSharedPreferences("pref",MODE_PRIVATE);

                SharedPreferences.Editor editor=sp.edit();

                //Storing the data from sharedpreferences

                editor.putString("name",name1);

                editor.putString("loc",loc1);

                editor.putString("email",email1);

                editor.commit();

                Toast.makeText(MainActivity.this, "Values are saved", Toast.LENGTH_SHORT).show();



            }

        });

        showbtn.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                startActivity(new Intent(getApplicationContext(),ReceivingActivity.class));

            }

        });



    }

}
activity_receiving.xml
-------------------------------
<LinearLayout     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="com.android.anil.sharedprefrences.ReceivingActivity"     android:orientation="vertical">     <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:textAppearance="?android:attr/textAppearanceLarge"         android:text="Large Text"         android:id="@+id/textView"         android:layout_gravity="center_horizontal"         android:layout_marginTop="10dp" />     <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:textAppearance="?android:attr/textAppearanceLarge"         android:text="Large Text"         android:id="@+id/textView2"         android:layout_gravity="center_horizontal"         android:layout_marginTop="10dp" />     <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:textAppearance="?android:attr/textAppearanceLarge"         android:text="Large Text"         android:id="@+id/textView3"         android:layout_gravity="center_horizontal"         android:layout_marginTop="10dp" /> </LinearLayout>
ReceivingActivity.Java
-----------------------------
package com.android.anil.sharedprefrences;



import android.content.SharedPreferences;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.TextView;



public class ReceivingActivity extends AppCompatActivity {

    TextView t1,t2,t3;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_receiving);

        t1=(TextView)findViewById(R.id.textView);

        t2=(TextView)findViewById(R.id.textView2);

        t3=(TextView)findViewById(R.id.textView3);

        SharedPreferences sp=getSharedPreferences("pref",MODE_PRIVATE);

        //Retriving the data from sharedprefrences

        String s1=sp.getString("name",null);

        String s2=sp.getString("loc",null);

        String s3=sp.getString("email",null);

        t1.setText(s1);

        t2.setText(s2);

        t3.setText(s3);

    }



}
Output is:
-----------------------------











No comments:

Post a Comment