Skip to main content

Simple Login/Register Example using SQLite database



MainActivity.java(login Screen)
package com.AndroidDevelopmentGuru.database_new;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends Activity {

               
                EditText user, pass;
                Button login, not_reg;
                DatabaseHandler db;
                Cursor cursor;

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


                                user =(EditText)findViewById(R.id.eduser);
                                pass = (EditText)findViewById(R.id.edpass);
                                login =(Button)findViewById(R.id.login);
                                not_reg =(Button)findViewById(R.id.not_reg);
                               
                                login.setOnClickListener(new OnClickListener() {
                                               
                                                @Override
                                                public void onClick(View arg0) {
                                                                // TODO Auto-generated method stub
                                                                db=new DatabaseHandler(MainActivity.this, null, null, 2);
                                                String username=user.getText().toString();
                                                String password= pass.getText().toString();
                                               
                                                String StoredPassword =db.getregister(username);
                                                if(password.equals(StoredPassword)){
                                                               
                                                                Toast.makeText(getApplicationContext(), StoredPassword+"Login Successfully", Toast.LENGTH_LONG).show();
                                                               
                                                }
                                                else{
                                                                Toast.makeText(getApplicationContext(), "Username/Password incorrect", Toast.LENGTH_LONG).show();
                                                user.setText("");
                                                pass.setText("");
                                                }
                                               
                                               
                                                }
                                });
                               
                                not_reg.setOnClickListener(new OnClickListener() {
                                               
                                                @Override
                                                public void onClick(View arg0) {
                                                                // TODO Auto-generated method stub
                                                               
                                                startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
                                                }
                                });
                               
                               
                               
                               

                                }
                               
                                /* @Override
                                                public boolean onCreateOptionsMenu(Menu menu) {
                        MenuInflater inflater = getMenuInflater();
                        inflater.inflate(R.menu.action_settings, menu);
                                        return super.onCreateOptionsMenu(menu);    
                                       //
                                 }
                                 */
                                  public boolean onOptionsItemSelected(MenuItem item) {
                                        // Take appropriate action for each action item click
                                        switch (item.getItemId()) {
                                        case R.id.action_settings:
                                            // search action
                                                                  Intent i=new Intent(MainActivity.this,RegisterActivity.class);
                                                                                startActivity(i);
                                            return true;
                                    }
                                                                return false;

                                  }
                /*             @Override
                                protected void onResume() {
                                                // TODO Auto-generated method stub
                                                 list = db.getAllRegister();
                                //            list=((alertv) alert).showAlert();
                                                                Customlist adapter = new Customlist(MainActivity.this, list);
                                                //            mylistview.setAdapter(adapter);
                                                               
                                                                if(adapter.getCount()!=0){
                                                                      mylistview.setAdapter(adapter);
                                                               
                                                               
                                                                }else{
                                                                     Toast.makeText(MainActivity.this, "No Items Available",Toast.LENGTH_SHORT).show();
                                                                }
                                                super.onResume();
                                  }
  */

}
                               
RegisterActivity.java
package com.AndroidDevelopmentGuru.database_new;

importandroid.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

publicclass RegisterActivity extends Activity {

       EditText first, last, email, mobile, pass, confpass;
       Button save, cancel;
       DatabaseHandler db;
       @Override
       protectedvoid onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_register);
      
      
              first= (EditText)findViewById(R.id.editfirstname);
              last =(EditText)findViewById(R.id.editlastname);
              email=(EditText)findViewById(R.id.editemail);
              mobile =(EditText)findViewById(R.id.editmobileno);
              pass=(EditText)findViewById(R.id.editpassword);
              confpass=(EditText)findViewById(R.id.editconformpassword);
             
              save=(Button)findViewById(R.id.btnsave);
              cancel=(Button)findViewById(R.id.btncancel);
      
             
              save.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     publicvoid onClick(View arg0) {
                           // TODO Auto-generated method stub
                          
                     String edfirst = first.getText().toString();
                     String edlast = last.getText().toString();
                     String edemail = email.getText().toString();
                     String edmobile = mobile.getText().toString();
                     String edpass = pass.getText().toString();
                     String edConf = confpass.getText().toString();
                    
                     if(edConf.equals(edpass) ){
                          
                          
                           db = new DatabaseHandler(RegisterActivity.this, null, null, 2);
                           Registerdata reg = new Registerdata();
                          
                           reg.setfirstName(edfirst);
                           reg.setlastName(edlast);
                           reg.setEmailId(edemail);
                           reg.setMobNo(edmobile);
                           reg.setPassword(edpass);
                           db.addregister(reg);
                          
                           Toast.makeText(getApplicationContext(), "Registered", Toast.LENGTH_LONG).show();
                           startActivity(new Intent(getApplicationContext(), MainActivity.class));
                     }
                     else{
                          
                           Toast.makeText(getApplicationContext(), "Password doesn't match", Toast.LENGTH_LONG).show();
                           pass.setText("");
                           confpass.setText("");
                     }
                     }
              });
       }

      

}


RegisterData.java
package com.AndroidDevelopmentGuru.database_new;

publicclass Registerdata {

      
       //private variables
int_id;
 String first_name;
 String last_name;
 String email_id;
 String mobile_number;
public String getPassword() {
       returnpassword;
}
publicvoid setPassword(String password) {
       this.password = password;
}

String password;

// Empty constructor
public Registerdata(){

 }
// constructor
public Registerdata(int id, String first_name, String  last_name,String email_id,String phone_number,String mobile_number){
this._id = id;
this.first_name = first_name;
this.last_name = last_name;
this.email_id=email_id;
this.mobile_number=mobile_number;
 }


// getting ID
publicint getID(){
returnthis._id;
 }

// setting id
publicvoid setID(int id){
this._id = id;
 }

       public String getfirstName() {
              // TODO Auto-generated method stub
              returnfirst_name;
       }
      
       // setting  first name
publicvoid setfirstName(String first_name){
this.first_name =first_name;
 }
       public String getlastName() {
              // TODO Auto-generated method stub
              returnlast_name;
       }
      
       publicvoid setlastName(String last_name){
this.last_name =last_name;
 }
       public String getEmailId() {
              // TODO Auto-generated method stub
              returnemail_id;
       }
       publicvoid setEmailId(String email_id){
this.email_id =email_id;
 }
       public String getMobNo() {
              // TODO Auto-generated method stub
              returnmobile_number;
       }
      
       publicvoid setMobNo(String mobile_number){
this.mobile_number=mobile_number;
 }
}

DataBAseHandler.java

package com.AndroidDevelopmentGuru.database_new;
import java.util.ArrayList;
import java.util.List;

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

public class DatabaseHandler extends SQLiteOpenHelper {

                public DatabaseHandler(Context context, Object name,
                                                Object factory, int version) {
                                // TODO Auto-generated constructor stub
                                super(context,  DATABASE_NAME, null, DATABASE_VERSION);
                }
               

                String password;
                // Database Version
                private static final int DATABASE_VERSION = 1;
                // Database Name
                private static final String DATABASE_NAME = "Mydatabase.db";

                // Contacts table name
                private static final String TABLE_REGISTER= "register";   
                public static final String KEY_ID = "id";
                public static final String KEY_FIRST_NAME = " first_name";
                public static final String KEY_lAST_NAME = "last_name";
                public static final String KEY_EMAIL_ID="email_id";
                public static final String KEY_MOB_NO = "mobile_number";
                public static final String KEY_PASSWORD = "password";
                public static final String CREATE_TABLE="CREATE TABLE " + TABLE_REGISTER + "("
                                                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_FIRST_NAME + " TEXT,"+KEY_lAST_NAME + " TEXT,"+KEY_EMAIL_ID+ " TEXT,"
                                                + KEY_MOB_NO + " TEXT," + KEY_PASSWORD + " TEXT " + ")";
               
                @Override
                public void onCreate(SQLiteDatabase db) {
                                // TODO Auto-generated method stub
                                db.execSQL(CREATE_TABLE);    
                }
                @Override
                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                                // TODO Auto-generated method stub
                                // Drop older table if existed
                                db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);

                                // Create tables again
                                onCreate(db);
                }

                void addregister(Registerdata registerdata)  
                                                // code to add the new register
                { 
                                SQLiteDatabase db = this.getWritableDatabase();  
                                ContentValues values = new ContentValues();   
                                values.put(KEY_FIRST_NAME,registerdata.getfirstName()); // register first Name
                                values.put(KEY_lAST_NAME, registerdata. getlastName() ); // register last name
                                values.put(KEY_EMAIL_ID, registerdata.getEmailId());//register email id
                                values.put(KEY_MOB_NO, registerdata.getMobNo());//register mobile no
                                values.put(KEY_PASSWORD, registerdata.getPassword());
                                // Inserting Row

                                db.insert(TABLE_REGISTER, null, values);
                                db.close(); // Closing database connection

                } 
               
               

                //code to get the register
                String getregister(String username){
                                SQLiteDatabase db = this.getReadableDatabase();
                                //String selectquery="SELECT * FROM TABLE_REGISTER";
                                Cursor cursor=db.query(TABLE_REGISTER,null,  "email_id=?",new String[]{username},null, null, null, null);

                                if(cursor.getCount()<1){
                                                cursor.close();
                                                return "Not Exist";
                                }
                                else if(cursor.getCount()>=1 && cursor.moveToFirst()){
                                               
                                                 password = cursor.getString(cursor.getColumnIndex(KEY_PASSWORD));
                                                cursor.close();
                                               
                                }
                                return password;
                               

}
               
               
                public String getDatabaseName() {
                                return DATABASE_NAME;
                }

                public static String getKeyId() {
                                return KEY_ID;
                }

                public static String getTableContacts() {
                                return TABLE_REGISTER;
                }

                public static int getDatabaseVersion() {
                                return DATABASE_VERSION;
                }

}

Activity_main.xml
<RelativeLayoutxmlns: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/eduser"
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(Email)">

<requestFocus/>
</EditText>

<EditText
android:id="@+id/edpass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/eduser"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:ems="10"
android:hint="Pssword"/>

<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/edpass"
android:layout_below="@+id/edpass"
android:layout_marginTop="43dp"
android:text="Login"/>

<Button
android:id="@+id/not_reg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/login"
android:layout_alignBottom="@+id/login"
android:layout_alignRight="@+id/edpass"
android:text="Not Registed ?"/>

</RelativeLayout>
Activity_register.xml

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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=".RegisterActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FIRST NAME:"/>

<EditText
android:id="@+id/editfirstname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="8">

<requestFocus/>
</EditText>
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LAST NAME:"/>

<EditText
android:id="@+id/editlastname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="8"/>
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/txttextemail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email Id"/>

<EditText
android:id="@+id/editemail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="8"
android:inputType="textEmailAddress"/>
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/    txttextmobileno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mobile No"/>

<EditText
android:id="@+id/editmobileno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="8"
android:inputType="phone"/>
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="password"/>

<EditText
android:id="@+id/editpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="8"
android:inputType="textPassword"/>
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textconformpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="conform password"/>

<EditText
android:id="@+id/editconformpassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="8"
android:inputType="textPassword"/>
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<Button
android:id="@+id/btnsave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"/>

<Button
android:id="@+id/btncancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"/>
</LinearLayout>

</LinearLayout>

Download the Code here 

Output:







Comments

  1. Hi, may i ask how do you show all the register data inside the listview? need help for it.

    ReplyDelete
  2. if (id == R.id.action_settings)

    this line getting error help me solve
    cannot resolve symbol

    ReplyDelete

Post a Comment

Popular posts from this blog

Android: Login Screen using Fragments

In this tutorial, our focus is on making a User/Member login activity using fragments. With the help of Fragments we will use the same activity to show User login area and also Members Login area. Prerequisite for this tutorial: You should be know how to make an Activity And most importantly you should have prior Knowledge of Fragments. For practising basic Fragment implementation refer to Android Simple Fragment Example      We have used only three activities for this: MainActivity(which represents the Login Screen) Fragments for Members area Fragment for New Users

Android: Current Location Using Fused APi on Google Maps

This tutorial gives us the simple implementation of "Fused API" to fetch the current location on google map in android. Fused API is latest among all techniques to get the location. It provides you very precise results and also uses less battery of your device. It chooses GPS or Network provider to get to your current location. And it helps your device remember about the last saved location. Let's implement the Fused API to fetch/get the current location. Step 1: Create a new project in Android studio. and select Maps Activity.