SQLite Introduction:-

Android SQLite is a lightweight database which comes with android. It is an Open-Source embedded SQL database engine. This provides relational database management structure for storing user defined records in the form of tables.

SQLite is an Database that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. It  is zero-configured, which means like other databases you do not need to configure it in your system.

Features of SQLite

  1. The transactions follow ACID properties i.e. atomicity, consistency,isolation, and durability even after system crashes and power failures.
  2. The configuration process is very easy, no setup or administration needed.
  3. All the features of SQL are implemented in it with some additional features like partial indexes, indexes on expressions, JSON, and common table expressions.
  4. It supports terabyte-sized databases and gigabyte-sized strings and blobs.
  5. Complete database can be stored in a single cross-platform disk file.

 

In this tutorial we will learn about   Login and Registration  with Android SQLite.

lets starts, create a new project:-

 

Step 1). update your strings.xml

<resources>
<string name="app_name">SQLITE</string>
<string name="enter_message_name">Enter Your Name</string>
<string name="enter_message_email">Enter Your Email</string>
<string name="enter_message_mobile">Enter Your Mobile No</string>
<string name="enter_message_password">Enter Your Password</string>
<string name="register_now">Register Now</string>
<string name="login_now">Login Now</string>
<string name="welcome_back">Welcome Back</string>
<string name="not_register">Not Register? click Here</string>
</resources>


Step 2). update colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
</resources>


Step 3). Creating Login Activity

 

now create a activity  name as LoginActivity  that generate two file LoginActivity.java and activity_login.xml, add the below code in activity_login.xml .

The code will create a simple login form containing logo on the top, 2 input fields email and password, login button and registration screen navigation link.

activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
tools:context=".MainActivity">
<ImageView
android:src="@drawable/logo"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/welcome_back"
android:textSize="20dp"
android:layout_margin="20dp"
></TextView>
<EditText
android:id="@+id/et_email"
android:layout_gravity="center"
android:layout_width="match_parent"
android:hint="@string/enter_message_email"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:padding="5dp"></EditText>
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:hint="@string/enter_message_password"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:padding="5dp"></EditText>
<Button
android:id="@+id/button_login"
android:layout_width="wrap_content"
android:text="@string/login_now"
android:layout_gravity="center"
android:layout_height="wrap_content"></Button>
<TextView
android:id="@+id/tv_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/not_register"
android:gravity="center"
android:layout_marginTop="20dp"
android:textColor="@color/colorAccent"
></TextView>
</LinearLayout>


Step 4). Create Registration Activity:-

 

now create a activity  name as RegistrationActivity  that generates two file RegistrationActivity .java and activity_registration.xml, add the below code in activity_registration.xml .

The code will create a simple login form containing logo on the top, 4 input fields name, email,phone,  password, and register button.

activity_registration.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
tools:context=".MainActivity">
<ImageView
android:src="@drawable/logo"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/welcome_back"
android:textSize="20dp"
android:layout_margin="20dp"
></TextView>

<EditText
android:id="@+id/et_name"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_margin="5dp"
android:hint="@string/enter_message_name"
android:layout_height="wrap_content"></EditText>
<EditText
android:id="@+id/et_mobile"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_margin="5dp"
android:hint="@string/enter_message_mobile"
android:layout_height="wrap_content"></EditText>
<EditText
android:id="@+id/et_email"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_margin="5dp"
android:hint="@string/enter_message_email"
android:layout_height="wrap_content"></EditText>
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_margin="5dp"
android:hint="@string/enter_message_password"
android:layout_height="wrap_content"></EditText>
<Button
android:id="@+id/button_register"
android:layout_width="wrap_content"
android:text="@string/register_now"
android:layout_gravity="center"
android:layout_height="wrap_content"></Button>

</LinearLayout>


Step 5). Create DatabaseHelper Class

create a database helper class name as MyDatabaseHelper.java and extend it with SQLiteOpenHelper  .

this class is used to manage database creation ,version management and manipulating the data.

add the below code in MyDatabaseHelper.java :-

package com.androidcreation.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


/**
* This class provides some (basic) database functionality.
*/
public class MyDatabaseHelper extends SQLiteOpenHelper {

public static final String TABLE_USERS = "users";
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_MOBILE = "mobile";
public static final String COLUMN_PASSWORD = "password";

private static final String DATABASE_NAME = "users.db";
private static final int DATABASE_VERSION = 1;

// Database creation sql statement
private String DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " +
TABLE_USERS + "(" + COLUMN_ID + " integer primary key autoincrement, " +
COLUMN_NAME + " text not null, " + COLUMN_EMAIL +
" text not null, " + COLUMN_MOBILE + " integer, " +
COLUMN_PASSWORD + " text not null);";

// Initialize the database object.

/**
* Initialises the database object.
* @param context the context passed on to the super.
*/
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

/**
* Converts the show table in the database to a JSON string.
* @param database the database to get the data from.
* @return a string in JSON format containing all the show data.
*/
private String getJSONExportString(SQLiteDatabase database) {
String selectQuery = "SELECT * FROM " + TABLE_USERS;
Cursor cursor = database.rawQuery(selectQuery, null);

// Convert the database to JSON
JSONArray databaseSet = new JSONArray();

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();

for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
if (cursor.getString(i) != null) {
rowObject.put(cursor.getColumnName(i), cursor.getString(i));
} else {
rowObject.put(cursor.getColumnName(i), "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

databaseSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();

// Convert databaseSet to string and put in file
return databaseSet.toString();
}


/**
* Returns the database name.
* @return the database name.
*/
public static String getDatabaseFileName() {
return DATABASE_NAME;
}

@Override
public void onCreate(SQLiteDatabase database) {
// Create the database with the database creation statement.
database.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//if (oldVersion > 1) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_USERS);
//}
}
public boolean addUser(String name, String email, String mobile, String password){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues c=new ContentValues();
c.put(COLUMN_NAME,name);
c.put(COLUMN_EMAIL,email);
c.put(COLUMN_MOBILE,mobile);
c.put(COLUMN_PASSWORD,password);
long result=db.insert(TABLE_USERS,null,c);
if (result==-1){
return false;
} else {
return true;
}

}

public String getLoginData(String email,String password)
{
SQLiteDatabase sql=this.getReadableDatabase();
String query=" select count(*) from "+TABLE_USERS+" where email ='"+email+"' and password='"+password+"'";
Cursor cursor =sql.rawQuery(query,null);
cursor.moveToFirst();
String count = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));
return count;

}
}
}

Step 6). Update LoginActivity class

add the below code in LoginActivity.java

package com.androidcreation.sqlite;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity {

EditText et_email,et_password;
Button buttonLogin;
MyDatabaseHelper myDatabaseHelper;
String email,password;
TextView tv_register;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

et_email=findViewById(R.id.et_email);
et_password=findViewById(R.id.et_password);
buttonLogin=findViewById(R.id.button_login);
tv_register=findViewById(R.id.tv_register);

myDatabaseHelper= new MyDatabaseHelper(this);
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
email=et_email.getText().toString();
password=et_password.getText().toString();
if (email.equals("") && password.equals("")) {
Toast.makeText(getApplicationContext(),"Please Insert Email and password",Toast.LENGTH_LONG).show();
} else {
int status =Integer.parseInt( myDatabaseHelper.getLoginData(email, password));
if (status>0) {
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
} else {
Toast.makeText(getApplicationContext(), "You are not Registerd!", Toast.LENGTH_LONG).show();

}
}

}
});
tv_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), RegistrationActivity.class);
startActivity(i);

}
});
}
}


Step 7). update Registration Activity class

add the below code in RegistrationActivity.java:-

 

package com.androidcreation.sqlite;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegistrationActivity extends AppCompatActivity {

EditText et_email,et_password,et_name,et_mobile;
Button buttonRegister;
MyDatabaseHelper myDatabaseHelper;
String email,password,name,mobile;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
et_email=findViewById(R.id.et_email);
et_password=findViewById(R.id.et_password);
buttonRegister=findViewById(R.id.button_register);
et_mobile=findViewById(R.id.et_mobile);
et_name=findViewById(R.id.et_name);

myDatabaseHelper= new MyDatabaseHelper(this);
buttonRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
email=et_email.getText().toString();
password=et_password.getText().toString();
name=et_name.getText().toString();
mobile=et_mobile.getText().toString();

if (email.equals(null) && password.equals(null)&&name.equals(null)&&mobile.equals(null)) {
Toast.makeText(getApplicationContext(),"Please Insert Email and password",Toast.LENGTH_LONG).show();
} else {
boolean status = myDatabaseHelper.addUser(name,email,mobile,password);
if (status) {
Toast.makeText(getApplicationContext(), "Registration Successfully", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
} else {
Toast.makeText(getApplicationContext(), "You are not Registerd!", Toast.LENGTH_LONG).show();

}
}

}
});
}
}
2 CommentsClose Comments

2 Comments

  • Sunil
    Posted May 24, 2020 at 9:54 am 0Likes

    Nice tutorial

  • Amit
    Posted May 24, 2020 at 9:56 am 0Likes

    Very Good Thanks for This Tutorial.

Leave a comment

shares

Newsletter Subscribe

Get the Latest Posts & Articles in Your Email

We Promise Not to Send Spam:)