You are on page 1of 25

UNITY UNIVERSITY

Department of computer science

CHAPTER FOUR

Basic Database Programming in


Android using SQLite

Performing CRUD
(Create, Read, Update, and Delete)
operation in SQLite
Procedure:

PART I: TOGGLE BUTTON EXAMPLE


Step 1. Create Android Application
The first step is to create a simple Android Application using Android studio. Search
for android in the program menu. When you click on Android studio icon, then click
“Start a new Android Studio Project”it will show screen as shown below:
Step 2: Type the application name

You can start your application development by calling start a new android studio
project. in a new installation frame should ask Application name, package
information and location of the project. Type the application name
“SQLiteExample ”
Step 3: Select Target Android Device

After entered application name, it going to be called select the form factors your
application runs on, here need to specify Minimum SDK, in our tutorial, I have
declared as API23: Android 6.0(Mashmallow) −
Step 4: Choose an Activity

The next level of installation should contain selecting the activity to mobile, it
specifies the default layout for Applications.

Step 5: Getting Ready for writing the application code

At the final stage it going to be open development tool to write the application code.
Step 6: After Click on a virtual device icon, it going to be shown by default virtual
devices which are present on your SDK, or else need to create a virtual device by
clicking Create new Virtual device button

If your AVD is created successfully it means your environment is ready for Android
application development.

Step 7: Design the User Interface

Before Writing a Hello word code, you must know about XML tags.To write hello
word code, you should redirect to App>res>layout>Activity_main.xml. Drag a
LinearLayout and (4) Button on the Layout XML.
Step 8: Add a New Activity (Empty Activity) and Design the User Interface

Add a new activity and name it Add_Employee. After adding the new activity, you
should redirect to App>res>layout>Activity_add_employee.xml. Drag a (2)
TextView, (2) Plain Text and (1) Button on the Linear Layout XML.
Objects ID
editName
PlainText - Name

ditCompany
PlainText – Company

btn_Add
Button: Add Record

textView1
TextView1: Enter Username

textView2
TextView1: Enter Company

Step 9: Add a New Activity (Empty Activity) and Design the User Interface

Add a new activity and name it Search_Employee. After adding the new activity, you
should redirect to App>res>layout>Activity_search_employee.xml. Drag some
objects/widgets on the Linear Layout XML as shown below.
Step 10: Add a New Activity (Empty Activity) and Design the User Interface

Add a new activity and name it Login_Employee. After adding the new activity, you
should redirect to App>res>layout>Activity_login_employee.xml. Drag some
objects/widgets on the Linear Layout XML as shown below.
Step 11: Add a New Activity (Empty Activity) and Design the User Interface

Add a new activity and name it ShowAll_Employee. After adding the new activity,
you should redirect to App>res>layout>Activity_showall_employee.xml. Drag
some objects/widgets on the Linear Layout XML as shown below.
Step 12: Modify the MainActivity.java

A. Import necessary libraries

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

B. Declare and Create a variable. Add the following code to main function.

private Button btnInsert, btnSearch, btnLogin, btnShowAll;

C. Create an object instance by adding the code in the onCreate() Function

btnInsert = (Button) findViewById(R.id.insert_btn);


btnSearch = (Button) findViewById(R.id.search_btn);
btnShowAll = (Button) findViewById(R.id.showall_btn);
btnLogin = (Button) findViewById(R.id.btnLoginMain);

D. Still on the onCreate() function, add the actionListener() method to the button objects

btnInsert.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View view) {

launchActivity_add();
}
});

btnSearch.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View view) {

launchActivity_search();
}

});

btnShowAll.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View view) {

launchActivity_show();
}

});

btnLogin.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View view) {

launchActivity_login();
}

});

E. Add the function to open a new activity when the menu button is click
private void launchActivity_add() {

Intent intent = new Intent(this,


Add_Employee.class); startActivity(intent);
}

private void launchActivity_show() {

Intent intent = new Intent(this,


Tanan_All.class); startActivity(intent);
}

private void launchActivity_search() {

Intent intent = new Intent(this,


SeearchEmployee.class); startActivity(intent);
}

private void launchActivity_login() {

Intent intent = new Intent(this, Login.class);


startActivity(intent);
}

Full MainActivity.java file code

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private Button btnInsert, btnSearch, btnLogin, btnShowAll;

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

btnInsert = (Button) findViewById(R.id.insert_btn);


btnSearch = (Button) findViewById(R.id.search_btn);
btnShowAll = (Button) findViewById(R.id.showall_btn);
btnLogin = (Button) findViewById(R.id.btnLoginMain);

btnInsert.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View view) {

launchActivity_add();
}

});

btnSearch.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View view) {

launchActivity_search();
}

});

btnShowAll.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View view) {

launchActivity_show();
}
});

btnLogin.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View view) {

launchActivity_login();
}

});

}
private void launchActivity_add() {

Intent intent = new Intent(this,


Add_Employee.class); startActivity(intent);
}

private void launchActivity_show() {

Intent intent = new Intent(this,


Tanan_All.class); startActivity(intent);
}

private void launchActivity_search() {

Intent intent = new Intent(this, SeearchEmployee.class);


startActivity(intent);
}

private void launchActivity_login() {

Intent intent = new Intent(this, Login.class);


startActivity(intent);
}

Step 13: Create a Class for DB Handler named it SQL “DBHelper” and add the
following code:
package com.example.bah.employeeba;

/**
* Created by bah on 5/2/2017.
*/

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 java.util.ArrayList;
import java.util.HashMap;

public class DBHelper extends SQLiteOpenHelper {

public static final String TAG = "DBHelper";

public static final String DATABASE_NAME = "EmpDB.db";


public static final String EMP_TABLE_NAME = "EmpTable";
public static final String EMP_COLUMN_ID = "id";
public static final String EMP_COLUMN_NAME = "name"; public
static final String EMP_COLUMN_COMPANY = "company";

public static final String idnila = "2";

public DBHelper(Context context) {


super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"create table IF NOT EXISTS " + EMP_TABLE_NAME + "
(id integer primary key, name text, company text)"
);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{

/* Insert a row into the database */


public boolean insert(String name, String company) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new
ContentValues(); contentValues.put("name", name);
contentValues.put("company", company);
db.insert(EMP_TABLE_NAME, null, contentValues);
return true;
}

/* Get the first row ID from the table


*/ public int getFirstId() {

int idToUpdate = 0;
String query = "select id from " + EMP_TABLE_NAME + " LIMIT 1";

SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);

if (null != res && res.getCount() > 0)


{ res.moveToFirst();
idToUpdate = res.getInt(0);
}
return idToUpdate;
}

/* Get all employees records from the table based on search criteria
*/ public ArrayList<Employee> getAllEmployees(String searchName) {

ArrayList<Employee> employeeList = new ArrayList<Employee>();


String query;

if (searchName == null) {
query = "select * from " + EMP_TABLE_NAME;
} else
query = "select * from " + EMP_TABLE_NAME + " where name like
'%" + searchName + "%'";

SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
res.moveToFirst();

while (res.isAfterLast() == false) {

Employee emp = new Employee();

int id = res.getInt(0);
String name = res.getString(1);
String company = res.getString(2);

emp.setAll(id, name, company);


employeeList.add(emp);
res.moveToNext();
}
return employeeList;

public ArrayList<Employee> loginCredentials(String searchName,


String searchCompany) {

ArrayList<Employee> employeeList = new ArrayList<Employee>();


String query;

query = "select * from " + EMP_TABLE_NAME + " where name like '%" +
searchName + "%'" + " AND company like '%" + searchCompany + "%'" ;

SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
res.moveToFirst();

while (res.isAfterLast() == false) {

Employee emp = new Employee();

int id = res.getInt(0);
String name = res.getString(1);
String company = res.getString( 2);

emp.setAll(id, name, company);


employeeList.add(emp);

res.moveToNext();
}
return employeeList;

/* Update the table row with ID - id */


public boolean updateDB(Integer id, String name, String company) {
Log.i(TAG, "Updating ID : " + id);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("company", company);
db.update(EMP_TABLE_NAME, contentValues, "id = ? ", new
String[]{Integer.toString(id)});
return true;
}

/* Delete the row with ID - id from the employees table


*/ public Integer deleteRow(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(EMP_TABLE_NAME, "id = ? ", new
String[]{Integer.toString(id)});
}

Step 14: Create a Model Class named it SQL “Employee” and add the following
code:
package com.example.bah.employeeba;

/**
* Created by bah on 5/2/2017.
*/

public class Employee {

public int id;


public String name, company;

public void setAll(int id, String name, String company)


{ this.id = id;
this.name = name;
this.company = company;
}
public Employee(){

public long getEmpId()


{ return id;
}

public void setEmpId(long empId)


{ this.id = id;
}

public String getName() {


return name;
}

public void setName(String firstname)


{ this.name = name;
}

public String getCompany() {


return company;
}

public void setCompany (String lastname)


{ this.company = company;
}

Step 14: Modify the Search_Employee.java

SearchEmployee.java file code

package com.example.bah.employeeba;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class SeearchEmployee extends AppCompatActivity {

private TextView mTv;


private EditText empSearch, editName, editCompany;
private Button btnSearchRecords, btnUpdateRecords, btnDeleteRecords;

private DBHelper myDb;


ArrayList<Employee> allEmployees;

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

empSearch = (EditText) findViewById(R.id.editSearchText);


editName = (EditText) findViewById(R.id.editTextName);
editCompany = (EditText) findViewById(R.id.editTextCompany);
mTv = (TextView) findViewById(R.id.textViewShow);

btnSearchRecords = (Button) findViewById(R.id.bthSearchButton);


btnUpdateRecords = (Button) findViewById(R.id.bthUpdate);
btnDeleteRecords = (Button) findViewById(R.id.btnDelete);

myDb = new DBHelper(this);

btnSearchRecords.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

// allEmployees = myDb.getAllEmployees(null);
String searchVal = empSearch.getText().toString().trim();
allEmployees = myDb.getAllEmployees(searchVal);
//String basta = allEmployees.indexOf(1);
//editName.setText(allEmployees);

for (Employee emp : allEmployees) {


//stringBuffer.append("[ " + emp.id + " ] [ " + emp.name
+ " ] [ " + emp.company + " ]\n");
editName.setText(emp.name.toString());
editCompany.setText(emp.company.toString());
}

// printTable(allEmployees);
// Log.i(TAG, "Searched Size : " + allEmployees.size());
if (allEmployees.size() == 0) {
showToastMessage("No Results");
}
}

});

btnUpdateRecords.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

// allEmployees = myDb.getAllEmployees(null);
String searchVal = empSearch.getText().toString().trim();
allEmployees = myDb.getAllEmployees(searchVal);
//String basta = allEmployees.indexOf(1);
//editName.setText(allEmployees);

for (Employee emp : allEmployees) {


//stringBuffer.append("[ " + emp.id + " ] [ " + emp.name
+ " ] [ " + emp.company + " ]\n");
//editName.setText(emp.name.toString());
//editCompany.setText(emp.company.toString());

myDb.updateDB(emp.id, editName.getText().toString(),
editCompany.getText().toString());
allEmployees = myDb.getAllEmployees(null);

}
showUpdateToastMessage("Updated the record
" +empSearch.getText().toString().trim());
launchActivity_Main();
// printTable(allEmployees);
// Log.i(TAG, "Searched Size : " + allEmployees.size());
if (allEmployees.size() == 0) {
showToastMessage("No Results");
}
}

});

btnDeleteRecords.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

// allEmployees = myDb.getAllEmployees(null);
String searchVal = empSearch.getText().toString().trim();
allEmployees = myDb.getAllEmployees(searchVal);
//String basta = allEmployees.indexOf(1);
//editName.setText(allEmployees);

for (Employee emp : allEmployees) {


//stringBuffer.append("[ " + emp.id + " ] [ " +
emp.name + " ] [ " + emp.company + " ]\n");
//editName.setText(emp.name.toString());
//editCompany.setText(emp.company.toString());

myDb.deleteRow(emp.id);
allEmployees = myDb.getAllEmployees(null);

// printTable(allEmployees);
// Log.i(TAG, "Searched Size : " + all Employees.size());
showDeleteToastMessage("Deleted the record "
+empSearch.getText().toString().trim());
launchActivity_Main();

if (allEmployees.size() == 0) {
showToastMessage("No Results");
}
}

});
}

void showToastMessage(String message) {


Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}

void showUpdateToastMessage(String message) {


Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}

void showDeleteToastMessage(String message) {


Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}

private void launchActivity_Main() {

Intent intent = new Intent(this,


MainActivity.class); startActivity(intent);
}
}
Step 15: Modify the ShowAll.java
ShowAll.java file code

package com.example.bah.employeeba;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class Tanan_All extends AppCompatActivity {

TextView mTv;

private DBHelper myDb;


ArrayList<Employee> allEmployees;

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

mTv = (TextView) findViewById(R.id.textView2);

//allEmployees = myDb.getAllEmployees(null);
myDb = new DBHelper(this);

allEmployees = myDb.getAllEmployees(null);
printTable(allEmployees);
}

void printTable(ArrayList<Employee> allEmployees) {

// Empty text in the TextView to show new


values mTv.setText("");

StringBuffer stringBuffer = new StringBuffer();


// Append table values in a String buffer
for (Employee emp : allEmployees) {
stringBuffer.append("[ " + emp.id + " ] [ " + emp.name + " ] [ "
+ emp.company + " ]\n");
}

// Show the table values


mTv.setText(stringBuffer);
}
}
Step 16: Modify the Login.java

Login.java file code

package com.example.bah.employeeba;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class Login extends AppCompatActivity {

private EditText editName, editCompany;


private Button btnLoginRecords, btnCancelRecords;

private DBHelper myDb;


ArrayList<Employee> allEmployees;

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

editName = (EditText) findViewById(R.id.editLoginName);


editCompany = (EditText) findViewById(R.id.editLoginCompany);

btnLoginRecords= (Button) findViewById(R.id.btnLogin1);


btnCancelRecords = (Button) findViewById(R.id. btnCancel1);

myDb = new DBHelper(this);

btnLoginRecords.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

// allEmployees = myDb.getAllEmployees(null);
String searchVal1 = editName.getText().toString().trim();
String searchVal2 = editCompany.getText().toString().trim();
allEmployees = myDb.loginCredentials(searchVal1, searchVal2);
//String basta = allEmployees.indexOf(1);
//editName.setText(allEmployees);

for (Employee emp : allEmployees) {


//stringBuffer.append("[ " + emp.id + " ] [ " +
emp.name + " ] [ " + emp.company + " ]\n");
//editName.setText(emp.name.toString());
//editCompany.setText(emp.company.toString());
showLoginMessage("Login Successful for "
+editName.getText().toString().trim());
launchActivity_Main();
}

// printTable(allEmployees);
// Log.i(TAG, "Searched Size : " + allEmployees.size());
if (allEmployees.size() == 0) {
showLoginUnsuccessfulMessage("Login Not Successful");

}
}

});

btnCancelRecords.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View view) {

launchActivity_Main();
}

});

void showLoginMessage(String message) {


Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}

void showLoginUnsuccessfulMessage(String message) {


Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}

private void launchActivity_Main() {

Intent intent = new Intent(this,


MainActivity.class); startActivity(intent);
}

You might also like