Monday 5 May 2014

How to save Login information in Android using Sqlite I How to save UserName and Password in Android

While developing a business application I found that almost all business apps or social media related apps are storing the login details for future use, so that user should skip the login step while next time opens the application.

It’s very easy to develop this feature in any android app. You can do it by storing Login details either in shared preferences or sqlite database.  Here in my Example I’m storing in sqlite database.


Step-1: Create new project -> Android Application Project. Name as ‘Save Login’ and click ‘next’,‘next’,               And lastly finish’
Step-2: Goto  res folder -> layout-> activity_main.xml file and design your login screen.

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: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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="UserName">

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="37dp"
        android:ems="10"
        android:hint="PassWord" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="30dp"
        android:text="Save Login" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/checkBox1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:text="Login" />

</RelativeLayout>

After this your login screen will look like this.





Step-3: Create your second screen as HomePage of app in layout folder.

home.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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to Home Page"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

This simple Homepage will look like this. You can add more buttons ,icons etc according to your app requirements.



Step-4: Now goto src folder and right click-> new-> class, name as Home. This class is corresponding java file for Home screen. We should have corresponding java files for each activity to access it from another activity.
Pase the following code in Home.java

Home.java
package com.example.savelogin;

import android.app.Activity;
import android.os.Bundle;

public class Home extends Activity {

      
       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.home); // Loading the home page
      
       }

}

Step-5: Open AndroidMenifest.xml file and define your home activity in that as following within <application> tab

<activity android:name="Home"></activity>

Step-6:Now to store login data we need to create the sqlite data base.
Go to src-add new class as MyDatabase.java. Here we will create our database. Database name is Mydb.db and table name is ‘logincredentials’.

MyDatabase.java

package com.example.savelogin;

import android.app.Activity;
import android.os.Bundle;

public class Home extends Activity {

      
       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.home); // Loading the home page
      
       }

}
package com.example.savelogin;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabase {

       MyHelper mh;
       SQLiteDatabase sdb;
      
       public MyDatabase(Context con) {
              // Creating MyDatabase Mydb.db
              mh=new MyHelper(con, "Mydb.db", null, 1);
       }
      
       public void open(){
              sdb = mh.getWritableDatabase();
       }
      
       //getting data from user Login page.
       public void insertLoginCredentials(String tmpUName,String tmpPWD, String tmpLoginStatus){
              ContentValues cv = new ContentValues();
              cv.put("UserName",tmpUName);            
              cv.put("PassWord",tmpPWD);
              cv.put("LoginStatus", tmpLoginStatus);
              sdb.insert("loginCredentials", null, cv);      
             
       }
       //read values from emp table
       public Cursor getLoginCrendentials(){
              Cursor c=null;
              c=sdb.query("loginCredentials", null, null, null, null, null, null);
             
              return c;
       }
      
      
       private class MyHelper extends SQLiteOpenHelper{

              public MyHelper(Context context, String name, CursorFactory factory,
                           int version) {
                     super(context, name, factory, version);
                     // TODO Auto-generated constructor stub
              }

              @Override
              public void onCreate(SQLiteDatabase db) {
                     // Creating table in database
                    
                     db.execSQL("Create table loginCredentials(_id integer primary key, " +
                                  "UserName text, PassWord text, LoginStatus text);");
                    
              }

              @Override
              public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                     // TODO Auto-generated method stub
                    
              }
             
       }
      
}

Step-7: Now our database is ready to save our data. Go to MainActivity.java and implement the login to save data and login. Here is the final code.

MainActivity.java

package com.example.savelogin;


import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


       //Declaring variables for views
      
       EditText etUser,etPass;
       Button bLogin;
       CheckBox cb;
       Cursor c=null;
       public static String hasSavedLogin="false";
      
       MyDatabase mdb=new MyDatabase(this);
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              //opening the database and reading the value
             
              mdb.open();
              c=mdb.getLoginCrendentials();
               if(c!=null){
                           //then only proceed
                            
                           while(c.moveToNext()){
                                  hasSavedLogin = c.getString(3);
                          
                           }
                     }
             
               // If login details is not saved enter in if statements
               
               if(!hasSavedLogin.equals("true")){
                      
      
             
                 etUser=(EditText) findViewById(R.id.editText1);
              etPass=(EditText) findViewById(R.id.editText2);
             
              bLogin=(Button) findViewById(R.id.button1);
              //Check box
             
              cb=(CheckBox) findViewById(R.id.checkBox1);
           
              bLogin.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View arg0) {               
                          
                           String user=etUser.getText().toString();
                           String pass=etPass.getText().toString();
                          
                           if(user.equals("android") && pass.equals("android")){
                                  Intent in=new Intent(getApplicationContext(),Home.class);
                                  if(cb.isChecked()){
                                         startActivity(in);
                                         etUser.setText("");
                                         etUser.requestFocus();
                                         etPass.setText("");
                                        
                                         //Storing Login details in MyDatabase
                                         hasSavedLogin="true";
                                        
                                         mdb.insertLoginCredentials(user,pass,hasSavedLogin);
                                     
                                        
                                         Toast.makeText(getApplicationContext(), "User saved", 0).show();
                                        
                                         finish();
                                  }
                                 
                                  //Login without saving data
                                  else{
                                  startActivity(in);
                                  etUser.setText("");
                                  etUser.requestFocus();
                                  etPass.setText("");
                                  finish();
                                  }
                           }
                          
                           //If Username or pwd is wrong
                          
                           else{
                                  Toast.makeText(getApplicationContext(), "Wrong username or password, please re-enter!", 0).show();
                                  etUser.setText("");
                                  etUser.requestFocus();
                                  etPass.setText(""); 
                           }                   
                          
                     }
              });        
            
       }
               
               //when user already saved the Logindetails,direct start home activity.
               
               else{
                      Intent in=new Intent(getApplicationContext(),Home.class);
                           startActivity(in);
                           finish();
               }

       }
}

I have commented in each section of codes for understanding purpose. Run the code and by default i have given username = ”android”and password = ”android”  to match for successful login.You can apply your own login credentials to match with database and validation for successful l login. Here I’m only trying to show to save the login credentials for next time login.

After successful  login you will switch to Home page. Close the app and again start, this time you will be directed to Home page without login.

Please comments if any doubts or suggestions. Thank You...Good Luck!!

No comments:

Post a Comment