Friday, 29 July 2016

SharedPreference | How to use to store and get data.


  • It used to store and retrieve primitive information in the string,integer,long etc.
  • 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,profile update,save login ID and password.
  • It store only one data at a time.
  • If we store new data than previously data went to delete automatically.
  • In order to use shared preferences,we have to call a method getSharedPreferences() that returns a SharedPreference instance .
Requirement:-
Android Studio:-2.1.2

Step1:- Open your Android Studio.
Step2:-Click on File >New >New Project > SharedPreferenceTest
Step3:-Click on res>activity_main.xml and take 2 EditText and 2 Button as like below image.



Step4:- coding of  activity_main.xml will be like following....

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:hint="Enter Id"
        android:id="@+id/txtId"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:hint="Enter Password"
        android:id="@+id/txtPassqword"
        android:inputType="textPassword"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="30dp">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Set Data"
            android:id="@+id/btnSet"
            android:background="#FF5733"
            android:textColor="#ffffff"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Get Data"
            android:id="@+id/btnGet"
            android:background="#FF5733"
            android:layout_marginLeft="4dp"
            android:textColor="#ffffff"/>
    </LinearLayout>
</LinearLayout>

Step5:- Now Open MainActivity.java and write following code..

package supriya.sharedpreferencetest;

import android.content.Context;
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 {

    //create object of Edittext and button..    EditText txtId,txtPass;
    Button btnSetData,btnGetData;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //find id ..        txtId=(EditText)findViewById(R.id.txtId);
        txtPass=(EditText)findViewById(R.id.txtPassqword);
        btnSetData=(Button)findViewById(R.id.btnSet);
        btnGetData=(Button)findViewById(R.id.btnGet);

        //click listner of setdata button
        btnSetData.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                //first we have to create database...                
SharedPreferences spf=getSharedPreferences("MyDatabase", Context.MODE_PRIVATE);

                //By usin editor class of SharedPreferences we can edit the data base... 
               SharedPreferences.Editor editDatabase=spf.edit();

                //set ID in to the database..we are using id as a integer type 
               editDatabase.putInt("ID",Integer.parseInt(txtId.getText().toString().trim()));

                //set Password..we r using password as String type.... 
               editDatabase.putString("PASSWORD",txtPass.getText().toString().trim());

                //save all changes into database.. 
               editDatabase.commit();
//make empty editbox....
               txtId.setText("");
               txtPass.setText("");
            }
        });



        //get button coding....       
 btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override            
public void onClick(View v) {
                //again create object of SharedPreferences and database.. as like above 
               SharedPreferences spf=getSharedPreferences("MyDatabase",Context.MODE_PRIVATE);

                //here we getint password into integer variable i of key value ID 
               int i=spf.getInt("ID",0);
                String str=spf.getString("PASSWORD","No Data");
                Toast.makeText(getApplicationContext(),"Id:-"+i+"\n"+"Password:-"+str+"\n",Toast.LENGTH_LONG).show();
            }
        });
    }
}

Step6: Run the program and Output will be like following..



No comments:

Post a Comment