Android DB Tutorial (Sec) - Desbloqueado
Android DB Tutorial (Sec) - Desbloqueado
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.
activity_main.xml
<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;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
MainActivity.java
package nibm.uncomplete.shan.sqlitedbtutorial_nibm;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.TextView;
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);
}
}
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;
//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!");
}
Now we should create a method to insert data to our database table. See the below code
carefully.
method insertData
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
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.
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(){
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();
}
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;
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;
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);
//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);
Integer.parseInt(index_no.getText().toString()),
subject.getText().toString(),
Integer.parseInt(marks.getText().toString()));
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();
}
}
}
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
<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
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);
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.
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.
//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) {
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) {
}
});
dialog.setCancelable(true);
dialog.onBackPressed();
dialog.show();
}
});
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.
StudentsListAdapter.java
package nibm.uncomplete.shan.sqlitedbtutorial_nibm;
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;
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder,
final int position) {
//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) {
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) {
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)));
}
Integer.parseInt(indexno.getText().toString()),subject.getText().toString
(),
Integer.parseInt(marks.getText().toString()));
}
});
dialog.setCancelable(true);
dialog.onBackPressed();
dialog.show();
}
});
@Override
public int getItemViewType(int position) {
if (position == students.size()) {
return 0;
} else {
return 1;
}
}
}
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
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.
//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) {
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;
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;
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);
//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);
Integer.parseInt(index_no.getText().toString()),
subject.getText().toString(),
Integer.parseInt(marks.getText().toString()));
}
}
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;
//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!");
}
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);
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;
}
StudentsListAdapter.java
package nibm.uncomplete.shan.sqlitedbtutorial_nibm;
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;
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder,
final int position) {
//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) {
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) {
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)));
}
Integer.parseInt(indexno.getText().toString()),
subject.getText().toString(),
Integer.parseInt(marks.getText().toString()));
}
});
dialog.setCancelable(true);
dialog.onBackPressed();
dialog.show();
}
});
//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) {
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();
}
}
});
@Override
public int getItemViewType(int position) {
if (position == students.size()) {
return 0;
} else {
return 1;
}
}