0% found this document useful (0 votes)
11 views52 pages

Android DB Tutorial (Sec) - Desbloqueado

This document is a tutorial for beginners on how to create and manage a database in an Android application, specifically focusing on SQLite. It covers the creation of a 'Students' database with operations for selecting, inserting, updating, and deleting records, as well as utilizing a RecyclerView to display data in real-time. The tutorial includes detailed steps for setting up the project, writing necessary Java classes, and implementing database functionalities with code snippets and explanations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views52 pages

Android DB Tutorial (Sec) - Desbloqueado

This document is a tutorial for beginners on how to create and manage a database in an Android application, specifically focusing on SQLite. It covers the creation of a 'Students' database with operations for selecting, inserting, updating, and deleting records, as well as utilizing a RecyclerView to display data in real-time. The tutorial includes detailed steps for setting up the project, writing necessary Java classes, and implementing database functionalities with code snippets and explanations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Android Database Tutorial for beginners

(select, insert, update, delete)


Today i’m going to teach you how can we create databases in the android. We can create
database at application run time or create database externally and when the application first
start, copy it to the relevant folder. That externally created & copied databases are called
pre-populated databases. In nowadays most of the applications are shipped with the pre-
populated databases.

Today we are going to make a simple android application that creates a database at run time
and teach you how to do select,insert,update & delete queries. In this tutorial we need to
create Students database and inside that STUDENTS table. Table has 4 columns
name,index_no,subject and marks. All the code snippets are added in the below with the
explanation

Before you start the tutorial you should download below project file and open it from the
Android Studio. Click the download button to get the uncompleted project file. After
downloaded extract the zip file.

Use below instructions to load the uncomplete project in to your android studio.

if this is your first start of the android studio, choose open an existing android studio project
and select the downloaded project location and press ok.
if you have allready opened a pre-project, go files select open and choose the downloaded
project location and press ok.
You should open the zip file and select project folder inside that. (SQLite DB Tutorial-
NIBM Uncomplete/project)
SQLite DB Tutorial-NIBM UncompleteDownload

I have used a recyclerview list view in this tutorial and i’m not going to teach that part
today. List view is added to show the database data realtime. So that code part is
allready done for you in the project you have downloaded.

First of all we need to create our layout file, below i have added the completed
activity_main.xml file, if you want to know more about layouts use the below link.

More About Layouts

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<!--Created by Shan Nirmala on 2019/01/01-->
<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="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center|top"
android:orientation="vertical">

<LinearLayout
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "
android:textSize="18sp"/>
<EditText
android:id="@+id/txtname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>
<LinearLayout
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Index No: "
android:textSize="18sp"/>
<EditText
android:id="@+id/txtindex_no"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"/>

</LinearLayout>
<LinearLayout
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subject: "
android:textSize="18sp"/>
<EditText
android:id="@+id/txtsubject"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>
<LinearLayout
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Marks: "
android:textSize="18sp"/>
<EditText
android:id="@+id/txtmarks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"/>

</LinearLayout>
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Add to DB"/>

</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="@color/colorPrimaryDark">

</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<android.support.v7.widget.RecyclerView
android:id="@+id/students_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scrollbars="none">
</android.support.v7.widget.RecyclerView>

</LinearLayout>

</LinearLayout>
preview of the activity_main.xml

Ok, now we have created our main layout file and now lets start coding. Open your
MainActivity.java file.

MainActivity.java

package nibm.uncomplete.shan.sqlitedbtutorial_nibm;

//Created by Shan Nirmala on 2019/01/01

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

}
}

First of all we need to declare our variables.

MainActivity.java

package nibm.uncomplete.shan.sqlitedbtutorial_nibm;

//Created by Shan Nirmala on 2019/01/01

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

TextView name,index_no,subject,marks;
Button add;
RecyclerView st_list;
DatabaseHelper dbHelper;
Boolean isInserted;

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

//Create new object of the class DatabaseHelper


dbHelper = new DatabaseHelper(this);
//Initializing objects
name = findViewById(R.id.txtname);
index_no = findViewById(R.id.txtindex_no);
subject = findViewById(R.id.txtsubject);
marks = findViewById(R.id.txtmarks);
add = findViewById(R.id.btn_add);
st_list = findViewById(R.id.students_list);

}
}

Now you will see a error in DatabaseHelper text and dont worry, now we are going to
fix it. After initializing the object wee need to create a class called DatabaseHelper. This
class should be extended using SQLiteOpenHelper super class. SQLiteOpenHelper is a
helper class to manage database creation and version management. Click Here to know
more. Use below instrcutions to create the class.

Write click on the sqlitedbtutorial_nibm folder and select new –> Java Class
Then in the create new class windows set the name as DatabaseHelper and select the
Superclass as SQLiteOpenHelper and press ok.

After creating the new class you should added below things in that class. I have added a
comments to clear the code. Below we have created the string variables for our database
name, database table and database columns. And in the onCreate method we should
create our database table.

DatabaseHelper.java

package nibm.uncomplete.shan.sqlitedbtutorial_nibm;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

//creating null object of SQLite database


SQLiteDatabase db;

//creating a public variable for the database name


public static final String DATABASE_NAME = "Students.db";
//creating a public variable for the db table name for future use
public static final String TABLE_NAME = "STUDENTS";

//creating variables for the table columns


public static final String TBL_COL_1 = "ID";
public static final String TBL_COL_2 = "NAME";
public static final String TBL_COL_3 = "INDEXNO";
public static final String TBL_COL_4 = "SUBJECT";
public static final String TBL_COL_5 = "MARKS";

//constructor
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}

//this method is called when the database is created for the first
time
//this method will be called when the first getwritabledatabase
method executed
@Override
public void onCreate(SQLiteDatabase db) {
//this is the query to create the table
db.execSQL("create table " + TABLE_NAME +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,INDEXNO INTEGER,SUBJECT
TEXT,MARKS INTEGER)");
Log.d("DB Helper: onCreate", "Database created successfully!");
}

/*this method is called when the database needs to be upgraded, if


the database version is
changed this method fires up automatically*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
Log.d("DB Helper: onUpgrade", "Database upgraded successfully!");
}
}

Now we should create a method to insert data to our database table. See the below code
carefully.

method insertData

//method to insert data to the database


public boolean insertData(String name, Integer index_no, String subject,
Integer marks){

//opening connection to the database and getting writable database


db = this.getWritableDatabase();
//Content values are used to store objects in the form of key-value
ContentValues contentValues = new ContentValues();
//putting our objects to the content values
contentValues.put(TBL_COL_2,name);
contentValues.put(TBL_COL_3,index_no);
contentValues.put(TBL_COL_4,subject);
contentValues.put(TBL_COL_5,marks);
//inserting values to the database
/*this will return a long value and if that value == -1, it means
data insertion failed,
else it will return the id(primary key) of that inserted row*/
long result = db.insert(TABLE_NAME,null ,contentValues);
//closes the db connection because we dont want it anymore
//db close is important when we are dealing with the sensitive data
db.close();
if(result == -1) {
Log.d("DB Helper: insertData", "Data insert failed!");
return false;
}
else {
Log.d("DB Helper: insertData", "Data inserted successfully!");
return true;
}
}

Now we should create a method to list the students and show them in our recyclerview list
view. To do that we need to write a select query and add them in to Students type array
list.

method listStudents

//getting students list as a List object


public List<Students> listStudents(){
db = this.getReadableDatabase();
List<Students> allStudents = new ArrayList<>();
Cursor cursor = null;
try {
//cursor is a kind of a pointer that points to individual rows
and return
cursor = db.rawQuery("SELECT * FROM "+TABLE_NAME, null);
if (cursor!=null) {
//moving the curser to the first result of the dataset
filtord by above query
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(0);
String name = cursor.getString(1);
int indexno = cursor.getInt(2);
String subejct = cursor.getString(3);
int marks = cursor.getInt(4);
allStudents.add(new Students(id, name, indexno,
subejct, marks));
} while (cursor.moveToNext());//moving curser forward one
by one
}
}else {
Log.d("DB Helper: listStudents", "try:Database Error!, Cursor
null!");
}
}catch (Exception e){
e.printStackTrace();
Log.d("DB Helper: listStudents", "catch:Database Error!");
}finally {
if (cursor!=null){
cursor.close();
}
db.close();
return allStudents;
}

If you got any underlined red text errors, move cursor to that relevant error text and
press alt+enter and it will import the missing packages to your class.

Now lets go back to our MainActivity.java file and create the code for ADD TO DB
button.

add button click listner

//set student add button click event listner


add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//inserting new data to the database & get return value(success
or failed)
if (name.getText().toString().equals("") ||
index_no.getText().toString().equals("")
|| subject.getText().toString().equals("") ||
marks.getText().toString().equals("")){
Toast.makeText(MainActivity.this,"You should fill all the
data!",Toast.LENGTH_SHORT).show();
}else {
isInserted = dbHelper.insertData(name.getText().toString(),
Integer.parseInt(index_no.getText().toString()),
subject.getText().toString(),
Integer.parseInt(marks.getText().toString()));

//if data inserted successfully, clear the text boxes


if (isInserted) {
Log.d("MainActivity: addbtnclk", "success adding
student!");
name.setText("");
index_no.setText("");
subject.setText("");
marks.setText("");
//if data inserted successfully, showing toast message to
the user
Toast.makeText(MainActivity.this, "Student added
successfully!", Toast.LENGTH_SHORT).show();
}else {
Log.d("MainActivity: addbtnclk", "failed adding
student!");
Toast.makeText(MainActivity.this, "Student adding
failed!", Toast.LENGTH_SHORT).show();
}
}
}
});

Now our data adding method is completed and now we want to show the added students in
our listview. To do that we need to create a method to retrieve the data from the database
and populate them in our list view. This method should be created outside of the
MainActivity onCreate method.

method loadStudentsList

//method that uses to load students data to our Recyclerview list view
public void loadStudentsList(){

//setting recyclerview list item divider


LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(this);
DividerItemDecoration dividerItemDecoration = new
DividerItemDecoration(st_list.getContext(),
linearLayoutManager.getOrientation());
st_list.addItemDecoration(dividerItemDecoration);

//setting new items add to the top of the list


linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);

st_list.setLayoutManager(linearLayoutManager);
st_list.setHasFixedSize(true);
List<Students> allStudents = null;
try {
//getting students list from the database
//we should do database things inside try catch, because if your
queries return null, it can crash the app
allStudents = dbHelper.listStudents();
Log.d("MainActivity: loadstd", "success getting data from the
db!");
}catch (Exception e){
Log.d("MainActivity: loadstd", "error while getting data from the
db!");
e.printStackTrace();
}

//checking if students data is available or not


if(allStudents.size() > 0){
//we can use logs to monitor what happens in the application and
we can see the logcats
Log.d("MainActivity: loadstd", "has students!");
//if database has data, populate that data to our list view using
adapter
StudentsListAdapter mAdapter = new StudentsListAdapter(this,
allStudents);
st_list.setAdapter(mAdapter);
}else if (allStudents == null){
Log.d("MainActivity: loadstd", "eror in the curser!");
Toast.makeText(this,"Database Error!",Toast.LENGTH_SHORT).show();
}else {
Log.d("MainActivity: loadstd", "no students in the list!");
}

Now we need to call above method inside MainActivity onCreate and the ADD TO DB
button onclick listner. See the below completed MainActivity.java file.

MainActivity.java

package nibm.uncomplete.shan.sqlitedbtutorial_nibm;

//Created by Shan Nirmala on 2019/01/01

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {

TextView name,index_no,subject,marks;
Button add;
RecyclerView st_list;
DatabaseHelper dbHelper;
Boolean isInserted;

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

//Create new object of the class DatabaseHelper


dbHelper = new DatabaseHelper(this);

//Initializing objects
name = findViewById(R.id.txtname);
index_no = findViewById(R.id.txtindex_no);
subject = findViewById(R.id.txtsubject);
marks = findViewById(R.id.txtmarks);
add = findViewById(R.id.btn_add);
st_list = findViewById(R.id.students_list);

//load the students list


loadStudentsList();
//set student add button click event listner
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//inserting new data to the database & get return
value(success or failed)
if (name.getText().toString().equals("") ||
index_no.getText().toString().equals("")
|| subject.getText().toString().equals("") ||
marks.getText().toString().equals("")){
Toast.makeText(MainActivity.this,"You should fill all
the data!",
Toast.LENGTH_SHORT).show();
}else {
isInserted =
dbHelper.insertData(name.getText().toString(),

Integer.parseInt(index_no.getText().toString()),
subject.getText().toString(),

Integer.parseInt(marks.getText().toString()));

//if data inserted successfully, clear the text boxes


if (isInserted) {
Log.d("MainActivity: addbtnclk", "success adding
student!");
loadStudentsList();
name.setText("");
index_no.setText("");
subject.setText("");
marks.setText("");
//if data inserted successfully, showing toast
message to the user
Toast.makeText(MainActivity.this,"Student added
successfully!",
Toast.LENGTH_SHORT).show();
}else {
Log.d("MainActivity: addbtnclk", "failed adding
student!");
Toast.makeText(MainActivity.this, "Student adding
failed!",
Toast.LENGTH_SHORT).show();
}
}
}
});

//method that uses to load students data to our Recyclerview list


view
public void loadStudentsList(){

//setting recyclerview list item divider


LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(this);
DividerItemDecoration dividerItemDecoration= new
DividerItemDecoration(st_list.getContext(),
linearLayoutManager.getOrientation());
st_list.addItemDecoration(dividerItemDecoration);

//setting new items add to the top of the list


linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);

st_list.setLayoutManager(linearLayoutManager);
st_list.setHasFixedSize(true);
List<Students> allStudents = null;
try {
//getting students list from the database
/*we should do database things inside try catch, because if
your queries return null,
it can crash the app*/
allStudents = dbHelper.listStudents();
Log.d("MainActivity: loadstd", "success getting data from the
db!");
}catch (Exception e){
Log.d("MainActivity: loadstd", "error while getting data from
the db!");
e.printStackTrace();
}

//checking if students data is available or not


if(allStudents.size() > 0){
//we can use logs to monitor what happens in the application
and we can see the logcats
Log.d("MainActivity: loadstd", "has students!");
//if database has data, populate that data to our list view
using adapter
StudentsListAdapter mAdapter = new StudentsListAdapter(this,
allStudents);
st_list.setAdapter(mAdapter);
}else if (allStudents == null){
Log.d("MainActivity: loadstd", "eror in the curser!");
Toast.makeText(this,"Database
Error!",Toast.LENGTH_SHORT).show();
}else {
Log.d("MainActivity: loadstd", "no students in the list!");
}

}
}
preview : adding student
preview : student added success

Now our Database data insertion methods are completed. Now lets see the update method.
First of all we need to create a layout for the update dialog. Lets create a Layout called
student_update.xml. If you dont know how to create a layout file see below instructions.

Write click on the res–>layout folder and select new–>Layout resource file.

Then in the New Layout Resource File dialog, set the name as update_student and
press ok.
student_update.xml

<?xml version="1.0" encoding="utf-8"?>


<!--Created by Shan Nirmala on 2019/01/01-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center|top"
android:orientation="vertical">

<LinearLayout
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_marginTop="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "
android:textSize="18sp"/>
<EditText
android:id="@+id/txtname"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>
<LinearLayout
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Index No: "
android:textSize="18sp"/>
<EditText
android:id="@+id/txtindex_no"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"/>

</LinearLayout>
<LinearLayout
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subject: "
android:textSize="18sp"/>
<EditText
android:id="@+id/txtsubject"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>
<LinearLayout
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Marks: "
android:textSize="18sp"/>
<EditText
android:id="@+id/txtmarks"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"/>

</LinearLayout>
<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Update Student"/>

</LinearLayout>

</LinearLayout>
preview : student_update dialog

Now our student_update layout file is done. To update a student, we also need to create a
new method in our DatabaseHelper.java class. Lets create a method called
updateStudent.

method updateStudent

//this is the method that uses to update students


//we should pass the relevant id and other data to update the record
public boolean updateStudent(int id,String name,int indexno,String
subject,int marks){

db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
try {
contentValues.put(TBL_COL_2,name);
contentValues.put(TBL_COL_3,indexno);
contentValues.put(TBL_COL_4,subject);
contentValues.put(TBL_COL_5,marks);

//this is how database record is update


db.update(TABLE_NAME, contentValues, "ID = ?",new String[]
{String.valueOf(id)});
return true;
}catch (Exception e){
e.printStackTrace();
Log.d("DB Helper: updtstudent", "catch: student update failed!");
return false;
}

We also need another method to fetch the selected student data to the student_update
dialog. To do that we should write a select query. see the below method.

//method to populate the student update dialog


public Cursor getUpdatedata(int id){

db = this.getReadableDatabase();
Cursor cursor = null;

try {
//getting data to the curser
cursor = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE
ID="+id,null);
Log.d("DB Helper: updtdata", "try: curser values setted!");
}catch (Exception e){
e.printStackTrace();
Log.d("DB Helper: updtdata", "catch: curser value getting
failed!");
}finally {
return cursor;
}
}

Because of this project is designed to show the database data realtime, above method
should be called in the StudentsListAdapter.java class. That class is used to fetch the
data to our recyclerview list view. The recyclerview item layouts are pre-designed &
allready included in the project and when we added a new student this class get that
data from the database and fetch them into the listview. All the listview items have
their own edit and delete button in right corner of the itemview. Above method should
be called inside the update button click listner in all the students list items. Lets see
the code for the update button click listner.

update button click listner

//this is the method that fires up when user click the update icon in the
list view
//this will show up a dialog with the current data in that relevant
record
studentsViewHolder.update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

final Dialog dialog = new Dialog(context);


dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.student_update);

final TextView name = dialog.findViewById(R.id.txtname);


final TextView indexno = dialog.findViewById(R.id.txtindex_no);
final TextView subject = dialog.findViewById(R.id.txtsubject);
final TextView marks = dialog.findViewById(R.id.txtmarks);
Button update = dialog.findViewById(R.id.btn_update);

try {
//this method get the data according to the clicked list item
//pass the id and get data from the database
Cursor cursor = myDb.getUpdatedata(getId(position));
if (cursor != null) {

//setting returned data to the text boxes


if (cursor.moveToFirst()) {
name.setText(String.valueOf(cursor.getString(1)));
indexno.setText(String.valueOf(cursor.getInt(2)));
subject.setText(String.valueOf(cursor.getString(3)));
marks.setText(String.valueOf(cursor.getString(4)));
}

//you should close the both cursor and the db connection


cursor.close();
myDb.db.close();
} else {
}
}catch (Exception e){
e.printStackTrace();
Log.d("STDListAdp: updtclick", "eror setting update dialog
values!");
}

//updating the student data


update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isUpdated;
//calling the update method
isUpdated =
myDb.updateStudent(getId(position),name.getText().toString(),
Integer.parseInt(indexno.getText().toString()),
subject.getText().toString(),
Integer.parseInt(marks.getText().toString()));

//check whether data is been update or not


if (isUpdated){
/*if updated, refresh the students list by calling
method in the main
activity*/
((MainActivity)context).loadStudentsList();
//dissmissing the dialog after data updates
successfully!
dialog.dismiss();
Toast.makeText(context,"Student Updated
Successfully!",
Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"Student Update Failed!",
Toast.LENGTH_SHORT).show();
}

}
});

dialog.setCancelable(true);
dialog.onBackPressed();
dialog.show();

//setting dialog width to fill parent and height to wrap content


Window window = dialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);

}
});

After adding this method, you should see the red text myDb. This is because we didnt
create a new instance of our DatabaseHelper class. if we going to use methods of our
DatabaseHelper class, we should create a new instance of that class before using the
methods. Create a new instance of the DatabaseHelper class like below.

create instance of DatabaseHelper


myDb = new DatabaseHelper(context);

This is the completed StudentsListAdapter.java class untill now.

StudentsListAdapter.java

package nibm.uncomplete.shan.sqlitedbtutorial_nibm;

//Created by Shan Nirmala on 2019/01/01

import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class StudentsListAdapter extends


RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Students> students;
private DatabaseHelper myDb;
public StudentsListAdapter(Context context, List<Students> stuDents)
{
this.context = context;
this.students = stuDents;
myDb = new DatabaseHelper(context);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
//setting our custom layout to show in the listview item
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout,
parent, false);
return new StudentsViewHolder(view);

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder,
final int position) {

final StudentsViewHolder studentsViewHolder =


(StudentsViewHolder) holder;
final Students singleStudent = students.get(position);
//setting data to the list view item
studentsViewHolder.name.setText("Name:
"+singleStudent.getName());
studentsViewHolder.index_no.setText("Index No:
"+singleStudent.getIndex_no());
//studentsViewHolder.subject.setText("Subject:
"+singleStudent.getSubject());
//studentsViewHolder.marks.setText("Marks:
"+singleStudent.getMarks());

//this is the method that fires up when user click the update
icon in the list view
//this will show up a dialog with the current data in that
relevant record
studentsViewHolder.update.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {

final Dialog dialog = new Dialog(context);


dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.student_update);

final TextView name = dialog.findViewById(R.id.txtname);


final TextView indexno =
dialog.findViewById(R.id.txtindex_no);
final TextView subject =
dialog.findViewById(R.id.txtsubject);
final TextView marks =
dialog.findViewById(R.id.txtmarks);
Button update = dialog.findViewById(R.id.btn_update);

try {
//this method get the data according to the clicked
list item
//pass the id and get data from the database
Cursor cursor = myDb.getUpdatedata(getId(position));
if (cursor != null) {

//setting returned data to the text boxes


if (cursor.moveToFirst()) {

name.setText(String.valueOf(cursor.getString(1)));

indexno.setText(String.valueOf(cursor.getInt(2)));

subject.setText(String.valueOf(cursor.getString(3)));

marks.setText(String.valueOf(cursor.getString(4)));
}

//you should close the both cursor and the db


connection
cursor.close();
myDb.db.close();
} else {
}
}catch (Exception e){
e.printStackTrace();
Log.d("STDListAdp: updtclick", "eror setting update
dialog values!");
}

//updating the student data


update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isUpdated;
//calling the update method
isUpdated =
myDb.updateStudent(getId(position),name.getText().toString(),

Integer.parseInt(indexno.getText().toString()),subject.getText().toString
(),

Integer.parseInt(marks.getText().toString()));

//check whether data is been update or not


if (isUpdated){
//if updated, refresh the students list by
calling method in the main activity
((MainActivity)context).loadStudentsList();
//dissmissing the dialog after data updates
successfully!
dialog.dismiss();
Toast.makeText(context,"Student Updated
Successfully!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"Student Update
Failed!",Toast.LENGTH_SHORT).show();
}

}
});

dialog.setCancelable(true);
dialog.onBackPressed();
dialog.show();

//setting dialog width to fill parent and height to wrap


content
Window window = dialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);

}
});

//returning listview item count


@Override
public int getItemCount() {
return students.size();
}

@Override
public int getItemViewType(int position) {
if (position == students.size()) {
return 0;
} else {
return 1;
}
}

//getting the db id of the relevant list item


int getId(int position){
return students.get(position).getId();
}

}
preview : update student dialog
preview : edit selected student
preview : student updated success

Ok now we have completed 85% of the project. Now we have to do one last thing, it’s the
student delete. Lets create a delete query method in the DatabaseHelper.

method deleteStudent

//method to delete students from the database


public boolean deleteStudent(int id){

db = this.getWritableDatabase();
try {
//this is how we delete a record from the database
db.delete(TABLE_NAME, "ID = ?",new String[]
{String.valueOf(id)});
Log.d("DB Helper: delstudent", "student deleted!");
return true;
}catch (Exception e){
e.printStackTrace();
Log.d("DB Helper: delstudent", "student delete failed!");
return false;
}
}

Now lets call above method inside our delete button click listner of the
StudentsListAdapter class.

delete button click listner

//this is the method that fires up when user click the delete icon in the
list view
studentsViewHolder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

boolean deleted = false;


try {
//calling delete method in DatabaseHelper class
deleted = myDb.deleteStudent(getId(position));
}catch (Exception e){
e.printStackTrace();
Log.d("STDListAdp: delclick", "return false from the db!");
}

if (deleted){
/*if record deleted successfully we should tell the listview
to delete that
item and refresh the list view*/
students.remove(position);
notifyDataSetChanged();
Toast.makeText(context,"Student
Deleted!",Toast.LENGTH_SHORT).show();

}else {
Log.d("STDListAdp: delclick", "error deleting student!");
Toast.makeText(context,"Event Delete
Failed!",Toast.LENGTH_SHORT).show();
}
}
});
Ok now we have completed our project. All the fully completed java class files are
added below.

MainActivity.java

package nibm.uncomplete.shan.sqlitedbtutorial_nibm;

//Created by Shan Nirmala on 2019/01/01

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {

TextView name,index_no,subject,marks;
Button add;
RecyclerView st_list;
DatabaseHelper dbHelper;
Boolean isInserted;

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

//Create new object of the class DatabaseHelper


dbHelper = new DatabaseHelper(this);

//Initializing objects
name = findViewById(R.id.txtname);
index_no = findViewById(R.id.txtindex_no);
subject = findViewById(R.id.txtsubject);
marks = findViewById(R.id.txtmarks);
add = findViewById(R.id.btn_add);
st_list = findViewById(R.id.students_list);

//load the students list


loadStudentsList();

//set student add button click event listner


add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//inserting new data to the database & get return
value(success or failed)
if (name.getText().toString().equals("") ||
index_no.getText().toString().equals("")
|| subject.getText().toString().equals("") ||
marks.getText().toString().equals("")){
Toast.makeText(MainActivity.this,"You should fill all
the data!",
Toast.LENGTH_SHORT).show();
}else {
isInserted =
dbHelper.insertData(name.getText().toString(),

Integer.parseInt(index_no.getText().toString()),
subject.getText().toString(),

Integer.parseInt(marks.getText().toString()));

//if data inserted successfully, clear the text boxes


if (isInserted) {
Log.d("MainActivity: addbtnclk", "success adding
student!");
loadStudentsList();
name.setText("");
index_no.setText("");
subject.setText("");
marks.setText("");
//if data inserted successfully, showing toast
message to the user
Toast.makeText(MainActivity.this,"Student added
successfully!",
Toast.LENGTH_SHORT).show();
}else {
Log.d("MainActivity: addbtnclk", "failed adding
student!");
Toast.makeText(MainActivity.this, "Student adding
failed!",
Toast.LENGTH_SHORT).show();
}
}
}
});

//method that uses to load students data to our Recyclerview list


view
public void loadStudentsList(){

//setting recyclerview list item divider


LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(this);
DividerItemDecoration dividerItemDecoration= new
DividerItemDecoration(st_list.getContext(),
linearLayoutManager.getOrientation());
st_list.addItemDecoration(dividerItemDecoration);

//setting new items add to the top of the list


linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
st_list.setLayoutManager(linearLayoutManager);
st_list.setHasFixedSize(true);
List<Students> allStudents = null;
try {
//getting students list from the database
/*we should do database things inside try catch, because if
your queries return null,
it can crash the app*/
allStudents = dbHelper.listStudents();
Log.d("MainActivity: loadstd", "success getting data from the
db!");
}catch (Exception e){
Log.d("MainActivity: loadstd", "error while getting data from
the db!");
e.printStackTrace();
}

//checking if students data is available or not


if(allStudents.size() > 0){
//we can use logs to monitor what happens in the application
and we can see the logcats
Log.d("MainActivity: loadstd", "has students!");
//if database has data, populate that data to our list view
using adapter
StudentsListAdapter mAdapter = new StudentsListAdapter(this,
allStudents);
st_list.setAdapter(mAdapter);
}else if (allStudents == null){
Log.d("MainActivity: loadstd", "eror in the curser!");
Toast.makeText(this,"Database
Error!",Toast.LENGTH_SHORT).show();
}else {
Log.d("MainActivity: loadstd", "no students in the list!");
}

}
}

DatabaseHelper.java

package nibm.uncomplete.shan.sqlitedbtutorial_nibm;

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.List;

public class DatabaseHelper extends SQLiteOpenHelper {


//creating null object of SQLite database
SQLiteDatabase db;

//creating a public variable for the database name


public static final String DATABASE_NAME = "Students.db";
//creating a public variable for the db table name for future use
public static final String TABLE_NAME = "STUDENTS";

//creating variables for the table columns


public static final String TBL_COL_1 = "ID";
public static final String TBL_COL_2 = "NAME";
public static final String TBL_COL_3 = "INDEXNO";
public static final String TBL_COL_4 = "SUBJECT";
public static final String TBL_COL_5 = "MARKS";

//constructor
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}

//this method is called when the database is created for the first
time
//this method will be called when the first getwritabledatabase
method executed
@Override
public void onCreate(SQLiteDatabase db) {
//this is the query to create the table
db.execSQL("create table " + TABLE_NAME +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,INDEXNO
INTEGER,SUBJECT TEXT,MARKS INTEGER)");
Log.d("DB Helper: onCreate", "Database created successfully!");
}

/*this method is called when the database needs to be upgraded, if


the database version is
changed this method fires up automatically*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
Log.d("DB Helper: onUpgrade", "Database upgraded successfully!");
}

//method to insert data to the database


public boolean insertData(String name, Integer index_no, String
subject, Integer marks){

//opening connection to the database and getting writable


database
db = this.getWritableDatabase();
//Content values are used to store objects in the form of key-
value
ContentValues contentValues = new ContentValues();
//putting our objects to the content values
contentValues.put(TBL_COL_2,name);
contentValues.put(TBL_COL_3,index_no);
contentValues.put(TBL_COL_4,subject);
contentValues.put(TBL_COL_5,marks);
//inserting values to the database
/*this will return a long value and if that value == -1, it means
data insertion failed,
else it will return the id(primary key) of that inserted row*/
long result = db.insert(TABLE_NAME,null ,contentValues);
//closes the db connection because we dont want it anymore
//db close is important when we are dealing with the sensitive
data
db.close();
if(result == -1) {
Log.d("DB Helper: insertData", "Data insert failed!");
return false;
}
else {
Log.d("DB Helper: insertData", "Data inserted
successfully!");
return true;
}
}

//getting students list as a List object


public List<Students> listStudents(){
db = this.getReadableDatabase();
List<Students> allStudents = new ArrayList<>();
Cursor cursor = null;
try {
//cursor is a kind of a pointer that points to individual
rows and return
cursor = db.rawQuery("SELECT * FROM "+TABLE_NAME, null);
if (cursor!=null) {
//moving the curser to the first result of the dataset
filtord by above query
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(0);
String name = cursor.getString(1);
int indexno = cursor.getInt(2);
String subejct = cursor.getString(3);
int marks = cursor.getInt(4);
allStudents.add(new Students(id, name, indexno,
subejct, marks));
} while (cursor.moveToNext());//moving curser forward
one by one
}
}else {
Log.d("DB Helper: listStudents", "try:Database Error!,
Cursor null!");
}
}catch (Exception e){
e.printStackTrace();
Log.d("DB Helper: listStudents", "catch:Database Error!");
}finally {
if (cursor!=null){
cursor.close();
}
db.close();
return allStudents;
}

//this is the method that uses to update students


//we should pass the relevant id and other data to update the record
public boolean updateStudent(int id,String name,int indexno,String
subject,int marks){

db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
try {
contentValues.put(TBL_COL_2,name);
contentValues.put(TBL_COL_3,indexno);
contentValues.put(TBL_COL_4,subject);
contentValues.put(TBL_COL_5,marks);

//this is how database record is update


db.update(TABLE_NAME, contentValues, "ID = ?",
new String[] {String.valueOf(id)});
return true;
}catch (Exception e){
e.printStackTrace();
Log.d("DB Helper: updtstudent", "catch: student update
failed!");
return false;
}

//method to populate the student update dialog


public Cursor getUpdatedata(int id){

db = this.getReadableDatabase();
Cursor cursor = null;

try {
//getting data to the curser
cursor = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE
ID="+id,null);
Log.d("DB Helper: updtdata", "try: curser values setted!");
}catch (Exception e){
e.printStackTrace();
Log.d("DB Helper: updtdata", "catch: curser value getting
failed!");
}finally {
return cursor;
}

//method to delete students from the database


public boolean deleteStudent(int id){
db = this.getWritableDatabase();
try {
//this is how we delete a record from the database
db.delete(TABLE_NAME, "ID = ?",new String[]
{String.valueOf(id)});
Log.d("DB Helper: delstudent", "student deleted!");
return true;
}catch (Exception e){
e.printStackTrace();
Log.d("DB Helper: delstudent", "student delete failed!");
return false;
}
}

StudentsListAdapter.java

package nibm.uncomplete.shan.sqlitedbtutorial_nibm;

//Created by Shan Nirmala on 2019/01/01

import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class StudentsListAdapter extends


RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Students> students;
private DatabaseHelper myDb;
public StudentsListAdapter(Context context, List<Students> stuDents)
{
this.context = context;
this.students = stuDents;
myDb = new DatabaseHelper(context);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
//setting our custom layout to show in the listview item
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout,
parent,
false);
return new StudentsViewHolder(view);

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder,
final int position) {

final StudentsViewHolder studentsViewHolder =


(StudentsViewHolder) holder;
final Students singleStudent = students.get(position);

//setting data to the list view item


studentsViewHolder.name.setText("Name:
"+singleStudent.getName());
studentsViewHolder.index_no.setText("Index No:
"+singleStudent.getIndex_no());
//studentsViewHolder.subject.setText("Subject:
"+singleStudent.getSubject());
//studentsViewHolder.marks.setText("Marks:
"+singleStudent.getMarks());

//this is the method that fires up when user click the update
icon in the list view
//this will show up a dialog with the current data in that
relevant record
studentsViewHolder.update.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {

final Dialog dialog = new Dialog(context);


dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.student_update);

final TextView name = dialog.findViewById(R.id.txtname);


final TextView indexno =
dialog.findViewById(R.id.txtindex_no);
final TextView subject =
dialog.findViewById(R.id.txtsubject);
final TextView marks =
dialog.findViewById(R.id.txtmarks);
Button update = dialog.findViewById(R.id.btn_update);

try {
//this method get the data according to the clicked
list item
//pass the id and get data from the database
Cursor cursor = myDb.getUpdatedata(getId(position));
if (cursor != null) {

//setting returned data to the text boxes


if (cursor.moveToFirst()) {

name.setText(String.valueOf(cursor.getString(1)));
indexno.setText(String.valueOf(cursor.getInt(2)));

subject.setText(String.valueOf(cursor.getString(3)));

marks.setText(String.valueOf(cursor.getString(4)));
}

//you should close the both cursor and the db


connection
cursor.close();
myDb.db.close();
} else {
}
}catch (Exception e){
e.printStackTrace();
Log.d("STDListAdp: updtclick", "eror setting update
dialog values!");
}

//updating the student data


update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isUpdated;
//calling the update method
isUpdated =
myDb.updateStudent(getId(position),name.getText().toString(),

Integer.parseInt(indexno.getText().toString()),
subject.getText().toString(),

Integer.parseInt(marks.getText().toString()));

//check whether data is been update or not


if (isUpdated){
/*if updated, refresh the students list by
calling method in the main
activity*/
((MainActivity)context).loadStudentsList();
//dissmissing the dialog after data updates
successfully!
dialog.dismiss();
Toast.makeText(context,"Student Updated
Successfully!",
Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"Student Update
Failed!",
Toast.LENGTH_SHORT).show();
}

}
});

dialog.setCancelable(true);
dialog.onBackPressed();
dialog.show();

//setting dialog width to fill parent and height to wrap


content
Window window = dialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);

}
});

//this is the method that fires up when user click the delete
icon in the list view
studentsViewHolder.delete.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {

boolean deleted = false;


try {
//calling delete method in DatabaseHelper class
deleted = myDb.deleteStudent(getId(position));
}catch (Exception e){
e.printStackTrace();
Log.d("STDListAdp: delclick", "return false from the
db!");
}

if (deleted){
/*if record deleted successfully we should tell the
listview to delete that
item and refresh the list view*/
students.remove(position);
notifyDataSetChanged();
Toast.makeText(context,"Student
Deleted!",Toast.LENGTH_SHORT).show();

}else {
Log.d("STDListAdp: delclick", "error deleting
student!");
Toast.makeText(context,"Event Delete
Failed!",Toast.LENGTH_SHORT).show();
}
}
});

//returning listview item count


@Override
public int getItemCount() {
return students.size();
}

@Override
public int getItemViewType(int position) {
if (position == students.size()) {
return 0;
} else {
return 1;
}
}

//getting the db id of the relevant list item


int getId(int position){
return students.get(position).getId();
}

You might also like