Wednesday 14 August 2013

Registration Activity Using Shared Preference Android

3 comments
Android comes with plenty of options to store persistent Application data. The approach you use depends upon your needs, is your data is private or how much space you need and is it accessible to other application or not.
In Android we have following option for storing persistence data.
Shared Preference -> store data in key- value pairs.
Internal Storage  -> Private data on device.
External storage -> public data on sharable storage.
SQLite Database -> more structure approach to store data in tables.

Today i am going to discuss about shared Preference:-
So Shared Preference is a framework that store persistent data in key-value pairs. You can store any primitive data type with Shared Preference.
To get a shared Preference object, use one of the following.
getSharedPreferences() -> if you have multiple sharedpreferecne file
getPreferences() -> if you need only on preference file for your activity
you Also need one editor to write into the file

Initialization:-
SharedPreferences pref=getApplicationContext().getSharedPreferences("MyFilename", 0);
// 0 - for private mode
Editor editor = pref.edit(); // Getting editor to edit the data

Storing Data:-
Editor.editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "arpit"); // Storing string
editor.putInt("key_name", "10"); // Storing integer
editor.putFloat("key_name", "10.5"); // Storing float
editor.putLong("key_name", "10.5L"); // Storing long

Need to commit in order to put value in file
editor.commit();
// commit changes

Retrieve data:-
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean

Clearing data:-
editor.remove("key_name"); // will delete key name

To delete all value of Shared Preference file call
clear();


Now we begin with our project.
In this project i will make an activity where user registered with the details like Name, Email and Password. Only After completing each of the details user is allowed to be in next activity where he/she will see the entered information.
Use of Shared Preference in the project:-
The information entered is stored in shared preference.
Value of the second activity is generated after fetching of information from the same file.


Step 1:- Make a new project named, SharedPreferenceSample.
Step 2:- As there will be two activity in the project, lets first define the xml for both.
activity_main.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"
    android:gravity="fill_horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/textview_Register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="80dp"
        android:text="Registeration"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textview_Register"
        android:layout_marginTop="25dp"
        android:text="Enter Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10" >
   
    </EditText>
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText_name"
        android:layout_below="@+id/editText_name"
        android:layout_marginTop="19dp"
        android:text="E-mail:"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText_mail"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="20dp"
        android:ems="10" >
    </EditText>
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText_mail"
        android:layout_below="@+id/editText_mail"
        android:layout_marginTop="31dp"
        android:text="Password:"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="24dp"
        android:ems="10" >
    </EditText>
    <Button
        android:id="@+id/button_register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText_password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Register" />
</RelativeLayout>

second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp" >
    <TextView
        android:id="@+id/second_text_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Username"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <TextView
        android:id="@+id/second_text_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Email"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <TextView
        android:id="@+id/second_text_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Password"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>


Step 3:- MainActivity Class
package com.arpit.sharedpreferencesample;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
    SharedPreferences pref;
    Editor editor;
    Button btn_register;
    EditText et_name, et_pass, et_email;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    et_name = (EditText) findViewById(R.id.editText_name);
    et_pass = (EditText) findViewById(R.id.editText_password);
    et_email = (EditText) findViewById(R.id.editText_mail);
    btn_register = (Button) findViewById(R.id.button_register);
   
    // creating an shared Preference file for the information to be stored
    // first argument is the name of file and second is the mode, 0 is private mode

   
    pref = getSharedPreferences("Registration", 0);
    // get editor to edit in file
    editor = pref.edit();
   
    // the tap of button we will fetch the information from three edittext    btn_register.setOnClickListener(new View.OnClickListener() {
       
        @Override
        public void onClick(View v) {
        String name = et_name.getText().toString();
        String email = et_email.getText().toString();
        String pass = et_pass.getText().toString();
       
        if(et_name.getText().length()<=0){
            Toast.makeText(MainActivity.this, "Enter name", Toast.LENGTH_SHORT).show();
        }
        else if( et_email.getText().length()<=0){
            Toast.makeText(MainActivity.this, "Enter email", Toast.LENGTH_SHORT).show();
        }
        else if( et_pass.getText().length()<=0){
            Toast.makeText(MainActivity.this, "Enter password", Toast.LENGTH_SHORT).show();
        }
        else{
       
        // as now we have information in string. Lets stored them with the help of editor
        editor.putString("Name", name);
        editor.putString("Email",email);
        editor.putString("Password",pass);
        editor.commit();   // commit the values
        
        // after saving the value open next activity
        Intent ob = new Intent(MainActivity.this, Second.class);
        startActivity(ob);
       
        }   
        }
    });
   }
}

Step 4:- Second class file
package com.arpit.sharedpreferencesample;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
// in this activity we will fetch the value entered in main activity
public class Second extends Activity{
    TextView tv_name, tv_pass, tv_email;
    SharedPreferences pref;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
    tv_name = (TextView) findViewById(R.id.second_text_name);
    tv_email = (TextView) findViewById(R.id.second_text_email);
    tv_pass = (TextView) findViewById(R.id.second_text_pass);
    pref = getSharedPreferences("Registration", 0);
   // retrieving value from Registration
    String name = pref.getString("Name", null);
    String email = pref.getString("Email", null);
    String password = pref.getString("Password", null);
   
    // Now set these value into textview of second activity   
    tv_name.setText(name);
    tv_pass.setText(password);
    tv_email.setText(email);
     }
}


Step 5:- Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.arpit.sharedpreferencesample"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.arpit.sharedpreferencesample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Second"></activity>
   
    </application>
</manifest>


Result:-
Entered information                                Fetched value on second activity
firstsecond
Catch Me On: CreateAppFaster.com

3 comments:

  1. According to Stanford Medical, It is indeed the ONLY reason this country's women get to live 10 years longer and weigh 42 pounds lighter than we do.

    (And by the way, it really has NOTHING to do with genetics or some secret-exercise and EVERYTHING about "how" they eat.)

    P.S, What I said is "HOW", and not "what"...

    Click this link to discover if this easy questionnaire can help you unlock your real weight loss potential

    ReplyDelete