How to use SQLite Database in Android Jump To: 1. Create Layouts 2. Database Creation (SQLiteHelper.java) 1. Make SQLiteHelper class 1. onCreate() method 2. onUpgrade() method 3. Steps For Open Database in SQLite Manager 3. Create model class for contact (ContactModel.java)
50
Embed
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
1. Make SQLiteHelper class 1. onCreate() method 2. onUpgrade() method 3. Steps For Open Database in SQLite Manager
3. Create model class for contact (ContactModel.java) 4. CRUD Operations (Insert/ Update/ Delete/ Select Records)
1. Insert Records 1. Why do we need SQLiteDatabase Object? 2. ContentValues 3. Insert Row
2. Update Rows 3. Delete Records 4. Select Records
1. What is Cursor? 2. Fetching Records from database
5. Calling SQLiteHelper class methods 1. Making SQLiteHelper class object 2. Add Record
1. Start TableManipulationActivity with ADD_RECORD request
2. onButtonClick() method 3. onActivityResult(int requestCode, int resultCode,
Intent data)4. Display all records
3. Update Record 1. onUpdateRecord
4. Delete Record: 6. Get all table names list into array from Current SQLite
database
ObjectiveLearn how to Insert Update Delete Retrieve Records in SQLite Database in Android
What is SQLite:
In Android, SQLite is used as database. So before we start coding our app, let’s understand few things about SQLite. SQLite is used as a Local Database in android.
Four Major things to understand about SQLite:
1. SQLite is RDBMS (Relational Database Management System)2. SQLite is written in C programming language3. SQLite is embedded within the Android operating System, so you don’t
need anything external on Android to use SQLite
4. To manipulate data (insert, update, delete) in SQLite database – we’ll use SQL (Structured Query Language)
SQLite is used as a database for android application development. If you would like to learn more about the above 4 points, please refer the following link:
To get more details about SQLite in general, please refer the following link:
http://www.sqlite.org
Android SQLite Example:
We are going to create a project where you will be able to insert/ update/ delete the user records from database.
The final output should look something like following:
[SCREENSHOT – FIRST SCREEN]
As you can see from the screenshots above initially user will see a list (which would be empty right now, since there are no records) and button called ‘Add‘.
[SCREENSHOT – SECOND SCREEN]
When user press the Add button, we’ll show him the form where user can add two fields
1. First Name2. Last Name
[SCREENSHOT – FIRST SCREEN AFTER ADDING THE RECORD]
By clicking the Insert button, record will be saved into SQLite database and user can see added record on the first screen.
[SCREENSHOT – LONG CLICK]
By long pressing on record you can Delete or Update record.
When you press on delete record the particular record will be deleted
from SQLite database.
When you press on update record you, you would be taken back to the
screen where you inserted your record. And from that screen you can
update the record.
Let’s start coding our Android app.
Step 1 Create LayoutsWe will need to create three layouts for our project
Layout 1: activity_main.xml
This layout holds all the records and an Add button to add records. When there are no contacts, we are showing the “No Records” and when user inserts the data, we hide that section.
Here, SQLiteDatabase.db is the name of your database, and database version is 1. When you make an object of SQLiteHelper class, it calls super class constructor and creates the SQLite database.
SQLiteOpenHelper class has two abstract methods that you need to override in SQLiteHelper class.
1. onCreate()2. onUpgrade()
2.1.1 onCreate() method
Let’s check the code and understand these methods in detail:
public static final String TABLE_NAME = "PEOPLE";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_FIRST_NAME = "FIRST_NAME";
public static final String COLUMN_LAST_NAME = "LAST_NAME";
This method is called when database is created for the first time. This is where the creation of tables should happen. If you wish to insert records at
the time of creating tables, even the code to insert the records should be written here.
Parameters:
db The Database
Here, we are making a table named PEOPLE in SQLite android.
Column Name Data Type Constraints
Id Integer auto increment
FirstName varchar
LastName varchar
db.execSQL() Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
For more details about execSQL() method please refer the following link:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
This method is called when the database needs to be upgraded (Database version changed). The implementation should use this method to drop tables/ add tables or to do anything else it needs to upgrade to the new schema version.
Parameters:
db The Database
oldVersion The old database version
newVersion The new database version
That’s all we are going to do in our SQLiteHelper class.
If you are interested in knowing more about SQLiteOpenHelper class, please refer following link:
2.1.3 Steps For How to use SQLite Manager (SQLite manager Firefox tutorial)
1. In Android Studio, go to Tools Menu >> DDMS or You can directly click on the Android Device Monitor icon appears on menu bar
2. Device Monitor window will open. Select your connected device/emulator from device tab and then go to File Explorer tab. In File Explorer tab go to data >> data >> select your project. Now Click on the Pull a file from the device icon(top right corner) and save it with .db extension.
3. Open Mozilla Firefox and then go to Tools Menu >> SQLite Manager.4. Now In SQLite Manger Go to Database Menu >> Connect Database.Then
select your database.
P.S.: You can directly create database using the plugin mentioned above. And then you have to import that database in your project directory.
Step 3 Create model class for contact (ContactModel.java)You’re doing awesome work till now! Now sit back and relax a bit.
We’ll do all the manipulation of data through a model class. So let’s first see our model class (Model is kind of skeleton of the data we want to use). We are working with contacts over here, so I have named my class as ContactModel.
We need following three things for the contact:
1. ID2. First Name
3. Last Name
We have declared them as String variables in our model class and we have generated getter and setter methods for ID, First Name and Last Name.
public class ContactModel {
private String ID, firstName, lastName;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Step 4 CRUD Operations (Insert/ Update/ Delete/ Select Records)Now we will learn about Inset, Update, Delete and display data from android SQLite database.
Please open SQLiteHelper.java class
4.1 Insert Records
I would be showing you 2 ways to do each of the operations; there is not much difference in them but its better if you learn both the ways.
>> Method 1:
Our first task would be to insert records in the database which we have
just created. To do that, check out the following code. We’ll be using
object of SQLiteDatabase class in all the operations, so I have declared
it as a class level object.
private SQLiteDatabase database;
public void insertRecord(ContactModel contact) {
database = this.getReadableDatabase();
ContentValues contentValues = new ContentValues();
To insert the record, first we are getting SQLiteDatabase object by calling getReadableDatabase() method of SQLiteOpenHelper class. We have set ContactModel class as an argument such that we can get the values of First Name and Last Name from that model.
4.1.1 Why do we need SQLiteDatabase Object?
database = this.getReadableDatabase();
SQLiteDatabase will help you to insert, update and delete the records from table and it also helps you to display table records.
For more details about SQLiteDatabase please refer following link:
This is a convenient method for inserting a row into the database.
Parameters:
TABLE_NAME String In which table you want insert data.
nullColumnHack
String
Optional, may be null. SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided values are empty, no column names are known and an empty row can't be inserted. If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your values are empty.
Values This map contains the initial column values for the row. The
keys should be the column names and the values the column
values.
Returns:
The row ID of the newly inserted row
-1 if an error occurred
For more details about database.insert() method please refer following link:
The method Queries the given table, and returns a cursor over the result set.
Parameters:
table The table name to compile the query against.
columnsA list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selectionA filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgs
You may include is in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupByA filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
HavingA filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
oerderByHow to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
For more details about database.query() method please refer the following link:
Note: We are done with all the database related operations; the next part is about how we are
calling the database methods in our Android project. So you can skip the following part if you
just wanted to learn about database operations in Android.
Step 5 Calling SQLiteHelper class methods 5.1 Making SQLiteHelper class object
sQLiteHelper = new SQLiteHelper(MainActivity.this);
Here, we are making an object of SQLiteHelper class. While calling parameterized constructor of SQLiteHelper class it calls super class
i.e.
SQLiteOpenHelper class constructor.
SQLiteOpenHelper class will create/open the database that we have discussed above.
5.2 Add Record
By pressing add button it calls an onAddRecord() method. onAddRecord() method Starts new activity called TableManipulationActivity with request code ADD_RECORD.
If request is for inserting the record, then we set the text of the button as Insert.
btnDML.setText(Constants.INSERT);
5.2.2 onButtonClick() method
private void onButtonClick() {
if (etFirstname.getText().toString().equals("") ||
etLastname.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Add Both Fields",
Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent();
intent.putExtra(Constants.FIRST_NAME,
etFirstname.getText().toString());
intent.putExtra(Constants.LAST_NAME,
etLastname.getText().toString());
setResult(RESULT_OK, intent);
finish();
}
}
>> First it will check if Firstname or Lastname is empty. If one of the fields is empty then we’ll not move forward.
>> Otherwise, we will make an object of intent and put First name and Last name as an extra values of intent.
>> Now set the result RESULT_OK. (Standard activity result: operation succeeded).
>> finish() the current activity.
5.2.3 onActivityResult(int requestCode, int resultCode, Intent data)
When we start any activity for result (Remember: startActivityForResult() method), after finishing or getting back from that particular activity onActivityResult() method will called from the last activity (Here, MainActivity).
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
>> Here, we are checking for resultCode. If resultCode is RESULT_OK then we are getting extra values that we have set on last activity (i.e. Firstname and Lastname).
>> After getting First name and Last name holding that data by ContactModel class.
>> Now check for requestCode. It requestCode is ADD_RECORD then insert record to the table.
sQLiteHelper.insertRecord(contact);
5.2.4 Display all records
After calling insertRecord() method we will call displayAllRecords() method to display all the inserted records.
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
rowID = view.getTag().toString();
onUpdateRecord(holder.firstname,
holder.lastname.toString());
}
>> First set values for alert dialog (Update, Delete)
>> Set long click listener on inflated view.
>> Make AlertDialog.Builder for alert dialog and set both the items to alert dialog.
>> Now set click listener for both the items that we have added to alert dialog.
DialogInterface: dialog reference
which: index of the item that is clicked.
>> Update index is 0, when it is called then rowID will be store by calling getTag() method view and onUpdateRecord() method will be called with first name and last name.
I hope you enjoy this tutorial and it would be helpful to you. Got an Idea of Android App Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Android App Development Company in Pakistan.