Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Android SQLite Database And Login System
There are several ways of storing data in Android. One of them is Android SQLite
Database. Using SQLite, we can store our structured data into the database. In this
tutorial we are going to explore how we can create, manage and use Android SQLite
Database functionality with an example of a Login System.
Create a SQLite Database and a table with following structure.
TYPE=>
COLUMN=>
Database Name : login.db
Table Name : LOGIN
Integer
Text
ID
USERNAME
1
2
Text
PASSWORD
Lets’s Start with Android SQLite Database
Step 1 – Create a new project in Android Studio and select empty Activity, name the
project as SQLite Database.
Step 2 – First of all we need a class which manage our SQLite Database and a
table. Create a new class in your project and call it DataBaseHelper. Our class will
extend with SQLiteOpenHelper class and will implement two primary override methods
for handling and managing our database.
@Override
public void onCreate(SQLiteDatabase db) {...}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {...}
Now Open DataBaseHelper class and modify its code, make sure to extends
with SQLiteOpenHelper class
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
//to create a new one.
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
1|Page
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion + " to " +
newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing oldVersion and newVersion
// values.
// The simplest case is to drop the old table and create a new one.
db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(db);
}
}
In this project we will use three activities.
MainActivity - login or register
signUP – Register Account Activity
LoginSuccessActivity
Creating Main Activity
Step 3 – Open activity_main.xml and either paste the following xml code or create
design yourself,
<LinearLayout 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:orientation="vertical"
android:gravity="center_vertical"
tools:context="com.example.se245547.sqlitedatabse2.MainActivity">
<EditText
android:id="@+id/editTextUserNameToLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User Name"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextPasswordToLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
android:hint="Password" />
<Button
android:id="@+id/buttonSignIN"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sign In"
android:textAppearance="?android:attr/textAppearanceMedium"
android:onClick="signIn"/>
< TextView
android:id = "@+id/buttonSignUP"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
2|Page
android:textAppearance="?android:attr/textAppearanceMedium"
android:text = "Are you new? Sign up now."
android:textAlignment="center" />
</LinearLayout>
Above xml code will generate the design look like below.
Step 4 – Now Open MainActivity.java and paste the following code. Read comments in
following code.
public class MainActivity extends AppCompatActivity {
Button btnSignIn;
TextView btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Refference Of Buttons
btnSignIn = (Button)findViewById(R.id.buttonSignIN);
btnSignUp = (TextView)findViewById(R.id.buttonSignUP);
// get the Refferences of views
final EditText editTextUserName =
(EditText)findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword =
(EditText)findViewById(R.id.editTextPasswordToLogin);
// Set OnClick Listener on SignIn button
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
3|Page
// get The User name and Password
String userName = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(MainActivity.this, "Congrats: Login Successfull",
Toast.LENGTH_LONG).show();
Intent intent = new
Intent(MainActivity.this,LoginSuccessActivity.class);
intent.putExtra("fullname",userName);
startActivity(intent);
}
else
{
Toast.makeText(MainActivity.this, "User Name or Password does not
match", Toast.LENGTH_LONG).show();
}
}
});
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity abd Start The Activity
Intent intentSignUP = new Intent(MainActivity.this,signUP.class);
startActivity(intentSignUP);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
Step 5 – create a class file LoginDataBaseAdapter.java and paste the following code. Read
comments in following code.
public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD
text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
4|Page
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
}
public int deleteEntry(String UserName)
{
String where="USERNAME=?";
int numberOFEntriesDeleted = db.delete("LOGIN", where, new String[]{UserName})
;
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName},
null, null, null);
if(cursor.getCount() < 1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
}
Step 6 - Create a new Empty Activity in your project and name it signUP. Open
activity_signUP.xml and paste the following xml for its design or you can create your own
design.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
5|Page
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_vertical"
tools:context="com.example.se245547.sqlitedatabse2.signUP">
<EditText
android:id="@+id/editTextUserName"
android:hint="User Name"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
<EditText
android:id="@+id/editTextConfirmPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Confirm Password"
android:inputType="textPassword" />
<Button
android:id="@+id/buttonCreateAccount"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Create Account"
android:layout_marginBottom="60dp" />
</LinearLayout>
Output of above xml code will be look like this.
6|Page
Step 7 – Now Open signUP.java and paste the following code. Carefully Read comments in
following code.
import
import
import
import
import
import
import
import
android.content.DialogInterface;
android.support.v7.app.AlertDialog;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;
public class signUP extends AppCompatActivity {
EditText editTextUserName,editTextPassword,editTextConfirmPassword;
Button btnCreateAccount;
LoginDataBaseAdapter loginDataBaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get Refferences of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
// check if any of the fields are vacant
if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vacant",
Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match",
Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password);
//Alert dialog after clicking the Register Account
final AlertDialog.Builder builder = new
AlertDialog.Builder(signUP.this);
builder.setTitle("Information");
builder.setMessage("Your Account is Successfully Created.");
builder.setPositiveButton("Okey", new
DialogInterface.OnClickListener() {
@Override
7|Page
public void onClick(DialogInterface dialogInterface, int i) {
//Finishing the dialog and removing Activity from stack.
dialogInterface.dismiss();
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
}
Step 8 – We have created MainActivity [Login Activity] and signUP [Register Account
Acitivity], now we need an Activity which comes after a successful login. Create a new
Empty Activity in your project and name it LoginSuccessActivity.
Open activity_login_success.xml and design the activity look like below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:gravity="center_vertical"
tools:context="com.example.se245547.sqlitedatabse2.LoginSuccessActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
8|Page
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Welcome, "
android:gravity="center_horizontal"
android:id="@+id/txt_success_name"
android:textColor="#1E90FF"
android:textSize="25sp"
android:textAlignment="center" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Log Out"
android:id="@+id/btn_logout"
android:layout_below="@+id/txt_success_name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textAlignment="center"/>
</LinearLayout>
In this layout we will retrieve and show following field in a TextView.
User FullName
Step 8 – Now Open LoginSuccessActivity.java and paste/type the following code. Carefully
Read comments in following code.
public class LoginSuccessActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_success);
TextView txtname = (TextView) findViewById(R.id.txt_success_name);
TextView btnlogout = (TextView) findViewById(R.id.btn_logout);
Intent intent = getIntent();
String loginName = intent.getStringExtra("fullname");
txtname.setText("Welcome, " + loginName);
btnlogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LoginSuccessActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
});
}
}
9|Page