Wednesday, 8 June 2016

Shared Preferences In Anadroid

Android provides several options for us to save persistent application data. The solution us choose depends on our specific needs, such as whether the data should be private to our application or accessible to other applications (and the user) and how much space our data requires.
User data storage options are the following:
  • Shared Preferences
    • Store private primitive data in key-value pairs.
  • Internal Storage
  • External Storage
  • SQLite Databases
Shared Preferences
Preferences are an important part of an Android application. It is important to let the users have the choice to modify and personalize their application depending on their needs.
The SharedPreferences class provides a general framework that allows us to save and retrieve persistent key-value pairs of primitive data types. We can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist  across user sessions (even if our application is killed).
The main importance of preferences is even we comes out the application, the preferences available even for next start of the application also.
To get a SharedPreferences object for user application, use one of two methods:
  • getSharedPreferences() 
    • Use this if we need multiple preferences files identified by name, which we specify with the first parameter.
  • getPreferences()
    • Use this if we need only one preferences file for our Activity. Because this will be the only preferences file for our Activity, we no need to supply a name.

To write values:
  1. Call edit() to get a SharedPreferences.Editor.
  2. Add values with methods such as putBoolean() and putString().
  3. Commit the new values with commit()

To read values, use SharedPreferences methods such as getBoolean() and getString().
            Example:

ActvityMain.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="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1"
        android:layout_marginLeft="20dp"
        android:ems="10"
        android:inputType="number"/>

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="41dp"
        android:ems="10" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText3"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="29dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="Button" />

</RelativeLayout>

MainActivity.java
package com.example.sharedprefences;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
           
            EditText et1,et2,et3;
            Button b;
             public static final String MyPREFERENCES = "MyPrefs";
             public static final String Name = "nameKey";
                public static final String Phone = "phoneKey";
                public static final String mail = "emailKey";

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                       
                        et1=(EditText)findViewById(R.id.editText1);
                        et2=(EditText)findViewById(R.id.editText2);
                        et3=(EditText)findViewById(R.id.editText3);
                       
                        b=(Button)findViewById(R.id.button1);
                       
                        b.setOnClickListener(new OnClickListener() {
                                   
                                    @Override
                                    public void onClick(View v) {
                                                // TODO Auto-generated method stub
                                                String name=et1.getText().toString();
                String num=et2.getText().toString();
                String Email=et3.getText().toString();
                                               
                                               
                                                SharedPreferences preferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();

                            
               
                editor.putString(Name, name);
                editor.putString(Phone, num);
                editor.putString(mail, Email);
               
                editor.commit();
               
                Intent in=new Intent(MainActivity.this, SecondActivity.class);
                startActivity(in);
                                               
                                    }
                                   
                        });
                       
                       
            }
}

activity_second
 <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="${relativePackage}.${activityClass}" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:id="@+id/tv1" />

</RelativeLayout>

SecondActvity.Java

package com.example.sharedprefences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class SecondActivity extends Activity {
           
            public static final String MyPREFERENCES = "MyPrefs";
             public static final String Name = "";
                public static final String Phone = "";
                public static final String mail = "";
               
                TextView t;
                String n="",p="",e="";

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_second);
                       
                        SharedPreferences preferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                       
                        n=preferences.getString("nameKey", null);
                        p=preferences.getString("phoneKey", null);
                        e=preferences.getString("emailKey", null);
                       
                        System.out.println("Vales"+p);
                       
                        t=(TextView) findViewById(R.id.tv1);
                       
                        t.setText("HIIIIIII"+n+p+e);                
                       
       
            }

}

OutPut:



No comments:

Post a Comment

Ads Inside Post