SlideShare a Scribd company logo
1 of 46
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)
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
Objective
Learn 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 language
3. 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:
 http://www.theappguruz.com/blog/use-sqlite-database-swift
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 Name
2. 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 Layouts
We 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.
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context=".MainActivity">

 <ScrollView
 android:id="@+id/scrollViewDisplay"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_weight="1">

 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical">

 <LinearLayout
 android:id="@+id/layoutDisplayPeople"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical">

 <TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:gravity="center"
 android:text="People"
 android:textColor="@color/color_black"
 android:textSize="25dp"
 android:textStyle="bold" />

 <TextView
 android:id="@+id/tvNoRecordsFound"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginBottom="15dp"
 android:layout_marginLeft="15dp"
 android:layout_marginTop="15dp"
 android:gravity="center"
 android:text="No Records Found"
 android:textColor="@color/color_black"
 android:textSize="15dp" />


 <LinearLayout
 android:id="@+id/parentLayout"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"></LinearLayout>


 </LinearLayout>

 </LinearLayout>
 </ScrollView>

 <com.rey.material.widget.Button
 android:id="@+id/btnAddNewRecord"
 style="@style/RaiseWaveColorButtonRippleStyle"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@color/color_blue"
 android:text="ADD"
 android:textColor="@color/color_white"
 android:textStyle="bold" />
 </LinearLayout>
Layout 2: inflate_record layout
We are using this layout to inflate the records we are inserting.
 <?xml version="1.0" encoding="utf-8"?>

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:gravity="center_horizontal">

 <com.rey.material.widget.LinearLayout
 android:id="@+id/inflateParentView"
 style="@style/FlatWaveButtonRippleStyle"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:gravity="center"
 >

 <com.rey.material.widget.TextView

 android:id="@+id/tvFullName"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginBottom="15dp"
 android:layout_marginTop="15dp"
 android:layout_marginLeft="15dp"
 android:layout_weight="1"
 android:text="Name"
 android:textSize="15sp"
 android:gravity="left"

 android:textColor="@color/color_black"
 android:textStyle="bold"
 />
 </com.rey.material.widget.LinearLayout>

 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="2dp"
 android:background="@color/color_grey"></LinearLayout>

 </LinearLayout>
Layout 3: table_manipulation.xml
This xml file for two DML (Data Manipulation Language – used for insert/ update/ delete
queries) statements of SQLite Database i.e. insert and update.
Here, we have two fieds:
1. EditText for FirstName and LastName
2. A Button for Insert/ Update records
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/layoutAddUpdate"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <EditText
 android:id="@+id/etFirstName"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:hint="First Name"
 android:inputType="textCapWords" />


 <EditText
 android:id="@+id/etLastname"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:hint="Last Name"
 android:inputType="textCapWords" />

 <com.rey.material.widget.Button
 android:id="@+id/btnDML"
 style="@style/RaiseWaveColorButtonRippleStyle"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@color/color_blue"
 android:text="Save"
 android:textColor="@color/color_white"
 android:textStyle="bold"
 />

 </LinearLayout>
Let’s learn how to create database and table in SQLite database and do the operations
(select/insert/update/delete) on table records.
Let’s get into java files now.
Step 2 Database Creation (SQLiteHelper.java)
2.1 Make SQLiteHelper class
 public class SQLiteHelper extends SQLiteOpenHelper

 We are creating a java file called SQLiteHelper and extending
SQLiteOpenHelper class and It is used to create a bridge between android
and SQLite.

 To perform basic SQL operations we need to extend SQLiteOpenHelper class.

 private static final int DATABASE_VERSION = 1;
 public static final String DATABASE_NAME = "SQLiteDatabase.db";

 public SQLiteHelper(Context context) {
 super(context, DATABASE_NAME, null, DATABASE_VERSION);
 }
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";

 @Override
 public void onCreate(SQLiteDatabase db) {
 db.execSQL("create table " + TABLE_NAME + " ( " + COLUMN_ID + "
INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_FIRST_NAME + " VARCHAR, " +
COLUMN_LAST_NAME + " VARCHAR);");
 }
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:
 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#exec
SQL(java.lang.String)
2.1.2 onUpgrade() method
 @Override
 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:
 http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
We are done with two things now:
1. We have created a database - SQLiteDemo.db
2. We have create a table - People
The structure for People table:
Column Name Data Type Constraints
ID int Auto Increment
FIRST_NAME varchar
LAST_NAME varchar
If you would like to see your database in action, you can download the FireFox plugin from the
following link:
 https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/
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. ID
2. 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();
 contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());
 contentValues.put(COLUMN_LAST_NAME, contact.getLastName());
 database.insert(TABLE_NAME, null, contentValues);
 database.close();
 }
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:
 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
If you would like to learn more about getReadbleDatabase() method, please refer following link:
 http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#g
etReadableDatabase()
4.1.2 ContentValues
 ContentValues contentValues = new ContentValues();
 contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());
 contentValues.put(COLUMN_LAST_NAME, contact.getLastName());
If you want to insert / update records, you can do it through ContentValues class by using
the put() method.
If you would like to learn more about ContentValues, please refer following link:
 http://developer.android.com/reference/android/content/ContentValues.html
4.1.3 Insert Row
>> Method 1:
 database.insert( TABLE_NAME, null, contentValues);
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:
 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#inser
t(java.lang.String,java.lang.String, android.content.ContentValues)
For safe coding, it is better to close the database once we are done with our operation. We are
closing the database at the end with following code.
 database.close();
>> Method 2:
 public void insertRecordAlternate(ContactModel contact) {
 database = this.getReadableDatabase();
 database.execSQL("INSERT INTO " + TABLE_NAME + "(" + COLUMN_FIRST_NAME
+ "," + COLUMN_LAST_NAME + ") VALUES('" + contact.getFirstName() + "','" +
contact.getLastName() + "')");
 database.close();
 }
Difference between both the methods:
1. We are using ContentValues in this method
2. We are using database.execSQL() method to execute the Query
database.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 following link:
 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#exec
SQL(java.lang.String
4.2 Update Rows
>> Method 1:
 public void updateRecord(ContactModel contact) {
 database = this.getReadableDatabase();
 ContentValues contentValues = new ContentValues();
 contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());
 contentValues.put(COLUMN_LAST_NAME, contact.getLastName());
 database.update(TABLE_NAME, contentValues, COLUMN_ID + " = ?", new
String[]{contact.getID()});
 database.close();
 }
 public int update (String table, ContentValues values, String whereClause,
String[] whereArgs)
update() is the convenient method for updating rows in the database.
Parameters:
Table The table to update in
Value
A map from column names to new column values. null is a valid value that will
be translated to NULL.
whereClause The optional WHERE clause to apply when updating. Passing null will update
all rows.
whereArgs
You may include is in the where clause, which will be replaced by the values
from whereArgs. The values will be bound as Strings.
Returns:
 The number of rows affected.
For more details about update() method please refer the following link:
 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#upda
te(java.lang.String, android.content.ContentValues, java.lang.String, java.lang.String[])
>> Method 2:
 public void updateRecordAlternate(ContactModel contact) {
 database = this.getReadableDatabase();
 database.execSQL("update " + TABLE_NAME + " set " + COLUMN_FIRST_NAME
+ " = '" + contact.getFirstName() + "', " + COLUMN_LAST_NAME + " = '" +
contact.getLastName() + "' where " + COLUMN_ID + " = '" + contact.getID()
+ "'");
 database.close();
 }
Here, we are using database.execSQL() instead of database.update() method. And in the end we
are closing the database.
4.3 Delete Records
>> Method 1:
 public void deleteRecord(ContactModel contact) {
 database = this.getReadableDatabase();
 database.delete(TABLE_NAME, COLUMN_ID + " = ?", new
String[]{contact.getID()});
 database.close();
 }
 public int delete (String table, String whereClause, String[] whereArgs)
database.delete() is convenient method for deleting rows in the database.
Parameters:
Table the table to delete from
whereClause
the optional WHERE clause to apply when deleting. Passing null will delete all
rows.
whereArgs
You may include ?s in the where clause, which will be replaced by the values
from whereArgs. The values will be bound as Strings.
Returns
 The number of rows affected if a whereClause is passed in, 0 otherwise. To remove all
rows and get a count pass 1 as the whereClause.
For more details about delete() method please refer the folloiwng link:
 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delet
e(java.lang.String, java.lang.String, java.lang.String[])
>> Method 2:
 public void deleteRecordAlternate(ContactModel contact) {
 database = this.getReadableDatabase();
 database.execSQL("delete from " + TABLE_NAME + " where " + COLUMN_ID +
" = '" + contact.getID() + "'");
 database.close();
 }
Here, again we are using database.execSQL() method to run the delete query and to delete the
record.
Challenge:
 Can you write a query to delete the whole table and not just all the records
4.4 Select Records
Before we get into the actual code of selecting the records, we need to understand the concept of
Cursor which is very important in this context.
4.4.1 What is Cursor?
When we query the database in Android, we get the result in cursor object containing the result
of the query
Two important points to remember about cursor:
 Cursors store query result records in rows and there are many methods which enables you
to access the data stored in cursor.
 We should use Cursor.close() method when Cursors is no longer used.
For more details about Cursor please refer following link:
 http://developer.android.com/reference/android/database/Cursor.html
Now we are getting back to fetching the records from database.
4.4.2 Fetching Records from database
I’ll show you two ways to achieve this.
>> Method 1:
 public ArrayList<ContactModel> getAllRecords() {
 database = this.getReadableDatabase();
 Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null,
null);

 ArrayList<ContactModel> contacts = new ArrayList<ContactModel>();
 ContactModel contactModel;
 if (cursor.getCount() > 0) {
 for (int i = 0; i < cursor.getCount(); i++) {
 cursor.moveToNext();

 contactModel = new ContactModel();
 contactModel.setID(cursor.getString(0));
 contactModel.setFirstName(cursor.getString(1));
 contactModel.setLastName(cursor.getString(2));

 contacts.add(contactModel);
 }
 }
 cursor.close();
 database.close();

 return contacts;
 }
 Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null,
null);
First of all, we are querying the database and fetching the records into cursor.
What is query() method?
 The query() method is highly overloaded, and there are variations of the method.
The one we are using is given below:
 public Cursor query (String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy)
The method Queries the given table, and returns a cursor over the result set.
Parameters:
table The table name to compile the query against.
columns
A 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.
selection
A 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.
groupBy
A 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.
Having A 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.
oerderBy
How 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:
 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#quer
y(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String,
java.lang.String, java.lang.String)
Now coming back to rest of the code of getAllRecrods() method:
 if (cursor.getCount() > 0): First, we are checking if we have got any records in Cursor or
not.
 for (int i = 0; i < cursor.getCount(); i++): If yes, than we fetch all the records by iterating
through the for loop.
 cursor.moveToNext(): Since, the initial position of the cursor is at -1.
We have to move cursor to the next record by using following code:
 cursor.getString(0) It retrieves first column value (i.e. ID)
 cursor.getString(1) It retrieves second column value(i.e. First Name)
 cursor.getString(2) It retrieves third column value (i.e. Last Name)
Then we are fetching data column wise
 cursor.close() After fetching all the records we are closing the cursor since it is very
important to close the cursor for safe coding.
>> Method 2:
Now we are fetching records using rawQuery() method that is quite similar to query() method.
 public ArrayList<ContactModel> getAllRecordsAlternate() {
 database = this.getReadableDatabase();
 Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME,
null);

 ArrayList<ContactModel> contacts = new ArrayList<ContactModel>();
 ContactModel contactModel;
 if (cursor.getCount() > 0) {
 for (int i = 0; i < cursor.getCount(); i++) {
 cursor.moveToNext();

 contactModel = new ContactModel();
 contactModel.setID(cursor.getString(0));
 contactModel.setFirstName(cursor.getString(1));
 contactModel.setLastName(cursor.getString(2));

 contacts.add(contactModel);
 }
 }
 cursor.close();
 database.close();

 return contacts;
 }
The only thing which is different in both the methods is following line of code.
 Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME, null);
We are using this method:
 public Cursor rawQuery (String sql, String[] selectionArgs)
Parameters:
sql The SQL query. The SQL string must not be ; terminated
selectionArgs
You may include is in where clause in the query, which will be replaced by the
values from selectionArgs. The values will be bound as Strings.
Returns
 Cursor
For more information about database.rawQuery() please refer following link:
 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#raw
Query(java.lang.String, java.lang.String[])
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.
 private void onAddRecord() {
 Intent intent = new Intent(MainActivity.this,
TableManipulationActivity.class);
 intent.putExtra(Constants.DML_TYPE, Constants.INSERT);
 startActivityForResult(intent, Constants.ADD_RECORD);
 }
>> Make an intent object to go from MainActivity to TableManipulationActivity.
>> Put extra values to intent
 Key: DML_TYPE
 Value: Insert
>> And start an activity for getting result for ADD_RECORD.
5.2.1 Start TableManipulationActivity with ADD_RECORD request
In TableManipulationActivity get Extra value that we have set on last activity.
 String request =
getIntent().getExtras().get(Constants.DML_TYPE).toString();
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)
{
 super.onActivityResult(requestCode, resultCode, data);

 if (resultCode == RESULT_OK) {
 String firstname = data.getStringExtra(Constants.FIRST_NAME);
 String lastname = data.getStringExtra(Constants.LAST_NAME);


 ContactModel contact = new ContactModel();
 contact.setFirstName(firstname);
 contact.setLastName(lastname);


 if (requestCode == Constants.ADD_RECORD) {
 sQLiteHelper.insertRecord(contact);
 }
 }
>> 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.
 private void displayAllRecords() {

 com.rey.material.widget.LinearLayout inflateParentView;
 parentLayout.removeAllViews();

 ArrayList<ContactModel> contacts = sQLiteHelper.getAllRecords();

 if (contacts.size() > 0) {
 tvNoRecordsFound.setVisibility(View.GONE);
 ContactModel contactModel;
 for (int i = 0; i < contacts.size(); i++) {

 contactModel = contacts.get(i);

 final Holder holder = new Holder();
 final View view =
LayoutInflater.from(this).inflate(R.layout.inflate_record, null);
 inflateParentView = (com.rey.material.widget.LinearLayout)
view.findViewById(R.id.inflateParentView);
 holder.tvName = (TextView) view.findViewById(R.id.tvName);


 view.setTag(contactModel.getID());
 holder.firstname = contactModel.getFirstName();
 holder.lastname = contactModel.getLastName();
 String personName = holder.firstname + " " + holder.lastname;
 holder.tvName.setText(personName);

 final CharSequence[] items = {Constants.UPDATE,
Constants.DELETE};
 inflateParentView.setOnLongClickListener(new
View.OnLongClickListener() {
 @Override
 public boolean onLongClick(View v) {

 AlertDialog.Builder builder = new
AlertDialog.Builder(MainActivity.this);
 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());
 } else {
 AlertDialog.Builder deleteDialogOk = new
AlertDialog.Builder(MainActivity.this);
 deleteDialogOk.setTitle("Delete
Contact?");
 deleteDialogOk.setPositiveButton("Ok", new
DialogInterface.OnClickListener() {
 @Override
 public void
onClick(DialogInterface dialog, int which) {

//sQLiteHelper.deleteRecord(view.getTag().toString());
 ContactModel contact = new
ContactModel();

contact.setID(view.getTag().toString());

sQLiteHelper.deleteRecord(contact);
 displayAllRecords();
 }
 }
 );
 deleteDialogOk.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
 @Override
 public void onClick(DialogInterface
dialog, int which) {

 }
 });
 deleteDialogOk.show();
 }
 }
 });
 AlertDialog alertDialog = builder.create();
 alertDialog.show();
 return true;
 }
 });
 parentLayout.addView(view);
 }
 } else {
 tvNoRecordsFound.setVisibility(View.VISIBLE);
 }
 }
Get all records from Table.
ArrayList contacts = sQLiteHelper.getAllRecords();
 Getting list of contacts by calling getAllRecords() method of SQLiteHelper Class.
 Here, we know that SQLiteHelper.getAllRecords() method returns ArrayList
of ContactModel Class.
Use Holder class to display records:
Holder class contains one TextView to display full name and two String values for first name
and last name holding.
 private class Holder {
 TextView tvName;
 String firstname;
 String lastname;
 }

 final Holder holder = new Holder();
 final View view =
LayoutInflater.from(this).inflate(R.layout.inflate_record, null);
 inflateParentView = (com.rey.material.widget.LinearLayout)
view.findViewById(R.id.inflateParentView);
 holder.tvFullName = (TextView) view.findViewById(R.id.tvFullName);


 view.setTag(contactModel.getID());
 holder.firstname = contactModel.getFirstName();
 holder.lastname = contactModel.getLastName();
 String personName = holder.firstname + " " + holder.lastname;
 holder.tvFullName.setText(personName);

>> Make an instance of Holder class.
>> Get layout as a view using inflate method.
>> Get TextView reference from layout.
>> Now setTag view which is ID.
>> Set First Name and Last Name of holder class from ContactModel class.
>> Finaly, set person name to TextView by merging first name and last name.
5.3 Update Record
By long pressing on records you will ask for update or delete record
 final CharSequence[] items = {Constants.UPDATE, Constants.DELETE};
 inflateParentView.setOnLongClickListener(new View.OnLongClickListener() {
 @Override
 public boolean onLongClick(View v) {

 AlertDialog.Builder builder = new
AlertDialog.Builder(MainActivity.this);
 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.
5.3.1 onUpdateRecord()
 private void onUpdateRecord(String firstname, String lastname) {
 Intent intent = new Intent(MainActivity.this,
TableManipulationActivity.class);
 intent.putExtra(Constants.FIRST_NAME, firstname);
 intent.putExtra(Constants.LAST_NAME, lastname);
 intent.putExtra(Constants.DML_TYPE, Constants.UPDATE);
 startActivityForResult(intent, Constants.UPDATE_RECORD);
 }

Here, we are doing same that we have done on onAddRecord() for making instance of an intent.
 We are passing first name and last name with intent to show it on edit text
of TableManipulationActivity.
 And at the end we are calling startActivityForResult() method with the request
of UPDATE_RECORD.
>> Start TableManipulationActivity with UPDATE_RECORD request.
>> In TableManipulationActivity get Extra value that we have set on last activity.
 String request = getIntent().getExtras().get(Constants.DML_TYPE).toString();
>> If request is for updating the record then set the text of the button as Update.
 btnDML.setText(Constants.UPDATE);
>> onButtonClick() method:
 onButtonClick() method is the same method that we have shown at the time of AddRecord.
>> onActivityResult(int requestCode, int resultCode, Intent data):
 Here, onActivityResult() method will called with UPDATE_RECORD request.
 else if (requestCode == Constants.UPDATE_RECORD) {

 contact.setID(rowID);
 sQLiteHelper.updateRecord(contact);
 }
>> Here, we already stored FirstName and LastName into ContactModel’s contact object.
>> In update we also need rowID which is being affected. So here we also setting rowID.
>> And Finally, calling updateRecord() method of SQLiteHelper class.
5.4 Delete Record
>> For deleting a record long press on record and select Delete.
>> You will be asked for confirmation if you would like to delete the record.
 AlertDialog.Builder deleteDialogOk = new
AlertDialog.Builder(MainActivity.this);
 deleteDialogOk.setTitle("Delete Contact?");
 deleteDialogOk.setPositiveButton("Ok", new
DialogInterface.OnClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which) {
 ContactModel contact = new ContactModel();
 contact.setID(view.getTag().toString());
 sQLiteHelper.deleteRecord(contact);

 }
 }
 );
>> Here, we are making alert dialog for confirmation of deleting record.
>> We are deleting the row based rowID, so we have just set the rowID to ContactModel class.
>> And call deleteRecord() method of SQLiteHelper class by passing object
of ContactModel class.
Step 6 Get all table name list into array from sqlite database
To get all the table names from the current database.
copytextpop-up
 public ArrayList<String> getAllTableName()
 {
 database = this.getReadableDatabase();
 ArrayList<String> allTableNames=new ArrayList<String>();
 Cursor cursor=database.rawQuery("SELECT name FROM sqlite_master WHERE
type='table'",null);
 if(cursor.getCount()>0)
 {
 for(int i=0;i<cursor.getCount();i++)
 {
 cursor.moveToNext();

allTableNames.add(cursor.getString(cursor.getColumnIndex("name")));
 }
 }
 cursor.close();
 database.close();
 return allTableNames;
 }
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.

More Related Content

What's hot

Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqliteArif Huda
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)Oum Saokosal
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Khaled Anaqwa
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOSMake School
 
Better Data Persistence on Android
Better Data Persistence on AndroidBetter Data Persistence on Android
Better Data Persistence on AndroidEric Maxwell
 
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?DicodingEvent
 
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...DicodingEvent
 
Introduction databases and MYSQL
Introduction databases and MYSQLIntroduction databases and MYSQL
Introduction databases and MYSQLNaeem Junejo
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core DataMake School
 
Database Programming
Database ProgrammingDatabase Programming
Database ProgrammingHenry Osborne
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of SlickKnoldus Inc.
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityAtul Saurabh
 

What's hot (20)

Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqlite
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOS
 
Better Data Persistence on Android
Better Data Persistence on AndroidBetter Data Persistence on Android
Better Data Persistence on Android
 
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
 
MySql:Introduction
MySql:IntroductionMySql:Introduction
MySql:Introduction
 
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
 
Database programming
Database programmingDatabase programming
Database programming
 
Introduction databases and MYSQL
Introduction databases and MYSQLIntroduction databases and MYSQL
Introduction databases and MYSQL
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Sql in dbms
Sql in dbmsSql in dbms
Sql in dbms
 
MYSQL-Database
MYSQL-DatabaseMYSQL-Database
MYSQL-Database
 

Viewers also liked

SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!DroidConTLV
 
Effective SQLite For Android
Effective SQLite For AndroidEffective SQLite For Android
Effective SQLite For AndroidShinobu Okano
 
Persistence in Android
Persistence in AndroidPersistence in Android
Persistence in Androidma-polimi
 
SQLite: Light, Open Source Relational Database Management System
SQLite: Light, Open Source Relational Database Management SystemSQLite: Light, Open Source Relational Database Management System
SQLite: Light, Open Source Relational Database Management SystemTanner Jessel
 
Android Protips: Advanced Topics for Expert Android App Developers
Android Protips: Advanced Topics for Expert Android App DevelopersAndroid Protips: Advanced Topics for Expert Android App Developers
Android Protips: Advanced Topics for Expert Android App DevelopersReto Meier
 

Viewers also liked (9)

Aula 06 - TEP - Introdução SQLite
Aula 06 - TEP - Introdução SQLiteAula 06 - TEP - Introdução SQLite
Aula 06 - TEP - Introdução SQLite
 
Android vs iOS
Android vs iOSAndroid vs iOS
Android vs iOS
 
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
SquiDB: a SQLite layer for Android - Jonathan Koren, Yahoo!
 
Effective SQLite For Android
Effective SQLite For AndroidEffective SQLite For Android
Effective SQLite For Android
 
Persistence in Android
Persistence in AndroidPersistence in Android
Persistence in Android
 
SQLite: Light, Open Source Relational Database Management System
SQLite: Light, Open Source Relational Database Management SystemSQLite: Light, Open Source Relational Database Management System
SQLite: Light, Open Source Relational Database Management System
 
SQLite - Overview
SQLite - OverviewSQLite - Overview
SQLite - Overview
 
Android Protips: Advanced Topics for Expert Android App Developers
Android Protips: Advanced Topics for Expert Android App DevelopersAndroid Protips: Advanced Topics for Expert Android App Developers
Android Protips: Advanced Topics for Expert Android App Developers
 
Design and Concepts of Android Graphics
Design and Concepts of Android GraphicsDesign and Concepts of Android Graphics
Design and Concepts of Android Graphics
 

Similar to ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ

Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptxvishal choudhary
 
Using prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesUsing prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesDavid Voyles
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenSony Suci
 
Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-Salman Mushtaq
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivitiesmaamir farooq
 
Lecture exercise on activities
Lecture exercise on activitiesLecture exercise on activities
Lecture exercise on activitiesmaamir farooq
 
Android Workshop
Android WorkshopAndroid Workshop
Android WorkshopJunda Ong
 
Android sq lite database tutorial
Android sq lite database tutorialAndroid sq lite database tutorial
Android sq lite database tutorialmaamir farooq
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving DataAnuchit Chalothorn
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfConint29
 
Introduction To Google Android (Ft Rohan Bomle)
Introduction To Google Android (Ft Rohan Bomle)Introduction To Google Android (Ft Rohan Bomle)
Introduction To Google Android (Ft Rohan Bomle)Fafadia Tech
 
Android app development basics
Android app development basicsAndroid app development basics
Android app development basicsAnton Narusberg
 

Similar to ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ (20)

Android sql examples
Android sql examplesAndroid sql examples
Android sql examples
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 
Using database in android
Using database in androidUsing database in android
Using database in android
 
Using prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesUsing prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile services
 
Databases with SQLite3.pdf
Databases with SQLite3.pdfDatabases with SQLite3.pdf
Databases with SQLite3.pdf
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
 
Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivities
 
Lecture exercise on activities
Lecture exercise on activitiesLecture exercise on activities
Lecture exercise on activities
 
9 content-providers
9 content-providers9 content-providers
9 content-providers
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
Android sq lite database tutorial
Android sq lite database tutorialAndroid sq lite database tutorial
Android sq lite database tutorial
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
 
Eclipse Tricks
Eclipse TricksEclipse Tricks
Eclipse Tricks
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdf
 
Android
AndroidAndroid
Android
 
Introduction To Google Android (Ft Rohan Bomle)
Introduction To Google Android (Ft Rohan Bomle)Introduction To Google Android (Ft Rohan Bomle)
Introduction To Google Android (Ft Rohan Bomle)
 
Android app development basics
Android app development basicsAndroid app development basics
Android app development basics
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 

More from LGS, GBHS&IC, University Of South-Asia, TARA-Technologies

More from LGS, GBHS&IC, University Of South-Asia, TARA-Technologies (20)

GAT Dogar Sons E book
GAT Dogar Sons E bookGAT Dogar Sons E book
GAT Dogar Sons E book
 
POSIMS Point Of Sale & Inventory Management System
POSIMS Point Of Sale & Inventory Management SystemPOSIMS Point Of Sale & Inventory Management System
POSIMS Point Of Sale & Inventory Management System
 
Waste management app launched for lahore | TARA-Technologies
Waste management app launched for lahore | TARA-Technologies Waste management app launched for lahore | TARA-Technologies
Waste management app launched for lahore | TARA-Technologies
 
CV-HMFTJ
CV-HMFTJ CV-HMFTJ
CV-HMFTJ
 
The Way To Perform Hajj Islamic Pilgrimage
The Way To Perform Hajj Islamic PilgrimageThe Way To Perform Hajj Islamic Pilgrimage
The Way To Perform Hajj Islamic Pilgrimage
 
Hajj All Duas * Pilgrimage Supplications
Hajj All Duas *  Pilgrimage SupplicationsHajj All Duas *  Pilgrimage Supplications
Hajj All Duas * Pilgrimage Supplications
 
Web Development Roadmaps ~hmftj
Web Development Roadmaps  ~hmftj Web Development Roadmaps  ~hmftj
Web Development Roadmaps ~hmftj
 
Top Software Houses In Pakistan
Top Software Houses In PakistanTop Software Houses In Pakistan
Top Software Houses In Pakistan
 
Russian Conversations and Dialogues​ -hmftj
Russian Conversations and Dialogues​ -hmftjRussian Conversations and Dialogues​ -hmftj
Russian Conversations and Dialogues​ -hmftj
 
hmftj-curriculum vitae-resume
hmftj-curriculum vitae-resumehmftj-curriculum vitae-resume
hmftj-curriculum vitae-resume
 
Continuous Integration vs Continuous Delivery vs Continuous Deployment
Continuous Integration vs Continuous Delivery vs Continuous Deployment Continuous Integration vs Continuous Delivery vs Continuous Deployment
Continuous Integration vs Continuous Delivery vs Continuous Deployment
 
Emotional Intelligence Info-graphic
Emotional Intelligence Info-graphicEmotional Intelligence Info-graphic
Emotional Intelligence Info-graphic
 
Human Computer Interaction Evaluation
Human Computer Interaction EvaluationHuman Computer Interaction Evaluation
Human Computer Interaction Evaluation
 
A9-HSMS: HCI Prototype Project
A9-HSMS: HCI Prototype Project A9-HSMS: HCI Prototype Project
A9-HSMS: HCI Prototype Project
 
hcimidtermhmftj
hcimidtermhmftjhcimidtermhmftj
hcimidtermhmftj
 
thehomemaster
thehomemasterthehomemaster
thehomemaster
 
cchmftjb-18298
cchmftjb-18298cchmftjb-18298
cchmftjb-18298
 
Good Men Live For Others Precis Writing -hmftj
Good Men Live For Others Precis Writing -hmftjGood Men Live For Others Precis Writing -hmftj
Good Men Live For Others Precis Writing -hmftj
 
Four colors of lies ~hmftj
Four colors of lies ~hmftjFour colors of lies ~hmftj
Four colors of lies ~hmftj
 
R&D Comes to Services: Software House's Pathbreaking Experiments
R&D Comes to Services: Software House's Pathbreaking ExperimentsR&D Comes to Services: Software House's Pathbreaking Experiments
R&D Comes to Services: Software House's Pathbreaking Experiments
 

Recently uploaded

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 

Recently uploaded (20)

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 

ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ

  • 1. 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) 4. CRUD Operations (Insert/ Update/ Delete/ Select Records) 1. Insert Records 1. Why do we need SQLiteDatabase Object? 2. ContentValues 3. Insert Row
  • 2. 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 Objective Learn 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 language 3. 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:
  • 3.  http://www.theappguruz.com/blog/use-sqlite-database-swift 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]
  • 4.
  • 5. 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]
  • 6.
  • 7. When user press the Add button, we’ll show him the form where user can add two fields 1. First Name 2. Last Name [SCREENSHOT – FIRST SCREEN AFTER ADDING THE RECORD]
  • 8.
  • 9. 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]
  • 10.
  • 11. 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 Layouts We 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.  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical"  android:paddingBottom="@dimen/activity_vertical_margin"  android:paddingLeft="@dimen/activity_horizontal_margin"  android:paddingRight="@dimen/activity_horizontal_margin"  android:paddingTop="@dimen/activity_vertical_margin"  tools:context=".MainActivity">   <ScrollView  android:id="@+id/scrollViewDisplay"  android:layout_width="match_parent"  android:layout_height="wrap_content"
  • 12.  android:layout_weight="1">   <LinearLayout  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:orientation="vertical">   <LinearLayout  android:id="@+id/layoutDisplayPeople"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:orientation="vertical">   <TextView  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:gravity="center"  android:text="People"  android:textColor="@color/color_black"  android:textSize="25dp"  android:textStyle="bold" />   <TextView  android:id="@+id/tvNoRecordsFound"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:layout_marginBottom="15dp"  android:layout_marginLeft="15dp"  android:layout_marginTop="15dp"  android:gravity="center"  android:text="No Records Found"  android:textColor="@color/color_black"  android:textSize="15dp" /> 
  • 13.   <LinearLayout  android:id="@+id/parentLayout"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical"></LinearLayout>    </LinearLayout>   </LinearLayout>  </ScrollView>   <com.rey.material.widget.Button  android:id="@+id/btnAddNewRecord"  style="@style/RaiseWaveColorButtonRippleStyle"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:background="@color/color_blue"  android:text="ADD"  android:textColor="@color/color_white"  android:textStyle="bold" />  </LinearLayout> Layout 2: inflate_record layout We are using this layout to inflate the records we are inserting.  <?xml version="1.0" encoding="utf-8"?>   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:orientation="vertical"
  • 14.  android:gravity="center_horizontal">   <com.rey.material.widget.LinearLayout  android:id="@+id/inflateParentView"  style="@style/FlatWaveButtonRippleStyle"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:gravity="center"  >   <com.rey.material.widget.TextView   android:id="@+id/tvFullName"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:layout_marginBottom="15dp"  android:layout_marginTop="15dp"  android:layout_marginLeft="15dp"  android:layout_weight="1"  android:text="Name"  android:textSize="15sp"  android:gravity="left"   android:textColor="@color/color_black"  android:textStyle="bold"  />  </com.rey.material.widget.LinearLayout>   <LinearLayout  android:layout_width="match_parent"  android:layout_height="2dp"  android:background="@color/color_grey"></LinearLayout>   </LinearLayout>
  • 15. Layout 3: table_manipulation.xml This xml file for two DML (Data Manipulation Language – used for insert/ update/ delete queries) statements of SQLite Database i.e. insert and update. Here, we have two fieds: 1. EditText for FirstName and LastName 2. A Button for Insert/ Update records  <?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:id="@+id/layoutAddUpdate"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical">   <EditText  android:id="@+id/etFirstName"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:hint="First Name"  android:inputType="textCapWords" />    <EditText  android:id="@+id/etLastname"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:hint="Last Name"  android:inputType="textCapWords" />   <com.rey.material.widget.Button  android:id="@+id/btnDML"  style="@style/RaiseWaveColorButtonRippleStyle"
  • 16.  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:background="@color/color_blue"  android:text="Save"  android:textColor="@color/color_white"  android:textStyle="bold"  />   </LinearLayout> Let’s learn how to create database and table in SQLite database and do the operations (select/insert/update/delete) on table records. Let’s get into java files now. Step 2 Database Creation (SQLiteHelper.java) 2.1 Make SQLiteHelper class  public class SQLiteHelper extends SQLiteOpenHelper   We are creating a java file called SQLiteHelper and extending SQLiteOpenHelper class and It is used to create a bridge between android and SQLite.   To perform basic SQL operations we need to extend SQLiteOpenHelper class.   private static final int DATABASE_VERSION = 1;  public static final String DATABASE_NAME = "SQLiteDatabase.db";   public SQLiteHelper(Context context) {  super(context, DATABASE_NAME, null, DATABASE_VERSION);  }
  • 17. 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";   @Override  public void onCreate(SQLiteDatabase db) {  db.execSQL("create table " + TABLE_NAME + " ( " + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_FIRST_NAME + " VARCHAR, " + COLUMN_LAST_NAME + " VARCHAR);");  } 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
  • 18. 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:  http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#exec SQL(java.lang.String) 2.1.2 onUpgrade() method  @Override  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
  • 19. 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:  http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html We are done with two things now: 1. We have created a database - SQLiteDemo.db 2. We have create a table - People The structure for People table: Column Name Data Type Constraints ID int Auto Increment FIRST_NAME varchar LAST_NAME varchar If you would like to see your database in action, you can download the FireFox plugin from the following link:  https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/ 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
  • 20. 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. ID 2. 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) {
  • 21.  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:
  • 22.  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();  contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());  contentValues.put(COLUMN_LAST_NAME, contact.getLastName());  database.insert(TABLE_NAME, null, contentValues);  database.close();  } 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:  http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html If you would like to learn more about getReadbleDatabase() method, please refer following link:
  • 23.  http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#g etReadableDatabase() 4.1.2 ContentValues  ContentValues contentValues = new ContentValues();  contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());  contentValues.put(COLUMN_LAST_NAME, contact.getLastName()); If you want to insert / update records, you can do it through ContentValues class by using the put() method. If you would like to learn more about ContentValues, please refer following link:  http://developer.android.com/reference/android/content/ContentValues.html 4.1.3 Insert Row >> Method 1:  database.insert( TABLE_NAME, null, contentValues); 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.
  • 24. 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:  http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#inser t(java.lang.String,java.lang.String, android.content.ContentValues) For safe coding, it is better to close the database once we are done with our operation. We are closing the database at the end with following code.  database.close(); >> Method 2:  public void insertRecordAlternate(ContactModel contact) {  database = this.getReadableDatabase();  database.execSQL("INSERT INTO " + TABLE_NAME + "(" + COLUMN_FIRST_NAME + "," + COLUMN_LAST_NAME + ") VALUES('" + contact.getFirstName() + "','" + contact.getLastName() + "')");  database.close();  } Difference between both the methods: 1. We are using ContentValues in this method 2. We are using database.execSQL() method to execute the Query
  • 25. database.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 following link:  http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#exec SQL(java.lang.String 4.2 Update Rows >> Method 1:  public void updateRecord(ContactModel contact) {  database = this.getReadableDatabase();  ContentValues contentValues = new ContentValues();  contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());  contentValues.put(COLUMN_LAST_NAME, contact.getLastName());  database.update(TABLE_NAME, contentValues, COLUMN_ID + " = ?", new String[]{contact.getID()});  database.close();  }  public int update (String table, ContentValues values, String whereClause, String[] whereArgs) update() is the convenient method for updating rows in the database. Parameters: Table The table to update in Value A map from column names to new column values. null is a valid value that will be translated to NULL. whereClause The optional WHERE clause to apply when updating. Passing null will update
  • 26. all rows. whereArgs You may include is in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings. Returns:  The number of rows affected. For more details about update() method please refer the following link:  http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#upda te(java.lang.String, android.content.ContentValues, java.lang.String, java.lang.String[]) >> Method 2:  public void updateRecordAlternate(ContactModel contact) {  database = this.getReadableDatabase();  database.execSQL("update " + TABLE_NAME + " set " + COLUMN_FIRST_NAME + " = '" + contact.getFirstName() + "', " + COLUMN_LAST_NAME + " = '" + contact.getLastName() + "' where " + COLUMN_ID + " = '" + contact.getID() + "'");  database.close();  } Here, we are using database.execSQL() instead of database.update() method. And in the end we are closing the database. 4.3 Delete Records >> Method 1:  public void deleteRecord(ContactModel contact) {  database = this.getReadableDatabase();
  • 27.  database.delete(TABLE_NAME, COLUMN_ID + " = ?", new String[]{contact.getID()});  database.close();  }  public int delete (String table, String whereClause, String[] whereArgs) database.delete() is convenient method for deleting rows in the database. Parameters: Table the table to delete from whereClause the optional WHERE clause to apply when deleting. Passing null will delete all rows. whereArgs You may include ?s in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings. Returns  The number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass 1 as the whereClause. For more details about delete() method please refer the folloiwng link:  http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delet e(java.lang.String, java.lang.String, java.lang.String[]) >> Method 2:  public void deleteRecordAlternate(ContactModel contact) {  database = this.getReadableDatabase();  database.execSQL("delete from " + TABLE_NAME + " where " + COLUMN_ID + " = '" + contact.getID() + "'");
  • 28.  database.close();  } Here, again we are using database.execSQL() method to run the delete query and to delete the record. Challenge:  Can you write a query to delete the whole table and not just all the records 4.4 Select Records Before we get into the actual code of selecting the records, we need to understand the concept of Cursor which is very important in this context. 4.4.1 What is Cursor? When we query the database in Android, we get the result in cursor object containing the result of the query
  • 29. Two important points to remember about cursor:  Cursors store query result records in rows and there are many methods which enables you to access the data stored in cursor.  We should use Cursor.close() method when Cursors is no longer used.
  • 30. For more details about Cursor please refer following link:  http://developer.android.com/reference/android/database/Cursor.html Now we are getting back to fetching the records from database. 4.4.2 Fetching Records from database I’ll show you two ways to achieve this. >> Method 1:  public ArrayList<ContactModel> getAllRecords() {  database = this.getReadableDatabase();  Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, null);   ArrayList<ContactModel> contacts = new ArrayList<ContactModel>();  ContactModel contactModel;  if (cursor.getCount() > 0) {  for (int i = 0; i < cursor.getCount(); i++) {  cursor.moveToNext();   contactModel = new ContactModel();  contactModel.setID(cursor.getString(0));  contactModel.setFirstName(cursor.getString(1));  contactModel.setLastName(cursor.getString(2));   contacts.add(contactModel);  }  }  cursor.close();  database.close(); 
  • 31.  return contacts;  }  Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, null); First of all, we are querying the database and fetching the records into cursor. What is query() method?  The query() method is highly overloaded, and there are variations of the method. The one we are using is given below:  public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) The method Queries the given table, and returns a cursor over the result set. Parameters: table The table name to compile the query against. columns A 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. selection A 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. groupBy A 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. Having A filter declare which row groups to include in the cursor, if row grouping is
  • 32. 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. oerderBy How 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:  http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#quer y(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String) Now coming back to rest of the code of getAllRecrods() method:  if (cursor.getCount() > 0): First, we are checking if we have got any records in Cursor or not.  for (int i = 0; i < cursor.getCount(); i++): If yes, than we fetch all the records by iterating through the for loop.  cursor.moveToNext(): Since, the initial position of the cursor is at -1. We have to move cursor to the next record by using following code:  cursor.getString(0) It retrieves first column value (i.e. ID)  cursor.getString(1) It retrieves second column value(i.e. First Name)  cursor.getString(2) It retrieves third column value (i.e. Last Name) Then we are fetching data column wise
  • 33.  cursor.close() After fetching all the records we are closing the cursor since it is very important to close the cursor for safe coding. >> Method 2: Now we are fetching records using rawQuery() method that is quite similar to query() method.  public ArrayList<ContactModel> getAllRecordsAlternate() {  database = this.getReadableDatabase();  Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME, null);   ArrayList<ContactModel> contacts = new ArrayList<ContactModel>();  ContactModel contactModel;  if (cursor.getCount() > 0) {  for (int i = 0; i < cursor.getCount(); i++) {  cursor.moveToNext();   contactModel = new ContactModel();  contactModel.setID(cursor.getString(0));  contactModel.setFirstName(cursor.getString(1));  contactModel.setLastName(cursor.getString(2));   contacts.add(contactModel);  }  }  cursor.close();  database.close();   return contacts;  } The only thing which is different in both the methods is following line of code.
  • 34.  Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME, null); We are using this method:  public Cursor rawQuery (String sql, String[] selectionArgs) Parameters: sql The SQL query. The SQL string must not be ; terminated selectionArgs You may include is in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings. Returns  Cursor For more information about database.rawQuery() please refer following link:  http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#raw Query(java.lang.String, java.lang.String[]) 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);
  • 35. 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.  private void onAddRecord() {  Intent intent = new Intent(MainActivity.this, TableManipulationActivity.class);  intent.putExtra(Constants.DML_TYPE, Constants.INSERT);  startActivityForResult(intent, Constants.ADD_RECORD);  } >> Make an intent object to go from MainActivity to TableManipulationActivity. >> Put extra values to intent  Key: DML_TYPE  Value: Insert >> And start an activity for getting result for ADD_RECORD. 5.2.1 Start TableManipulationActivity with ADD_RECORD request In TableManipulationActivity get Extra value that we have set on last activity.
  • 36.  String request = getIntent().getExtras().get(Constants.DML_TYPE).toString(); 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.
  • 37. 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) {  super.onActivityResult(requestCode, resultCode, data);   if (resultCode == RESULT_OK) {  String firstname = data.getStringExtra(Constants.FIRST_NAME);  String lastname = data.getStringExtra(Constants.LAST_NAME);    ContactModel contact = new ContactModel();  contact.setFirstName(firstname);  contact.setLastName(lastname);    if (requestCode == Constants.ADD_RECORD) {  sQLiteHelper.insertRecord(contact);  }  } >> 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.
  • 38.  sQLiteHelper.insertRecord(contact); 5.2.4 Display all records After calling insertRecord() method we will call displayAllRecords() method to display all the inserted records.  private void displayAllRecords() {   com.rey.material.widget.LinearLayout inflateParentView;  parentLayout.removeAllViews();   ArrayList<ContactModel> contacts = sQLiteHelper.getAllRecords();   if (contacts.size() > 0) {  tvNoRecordsFound.setVisibility(View.GONE);  ContactModel contactModel;  for (int i = 0; i < contacts.size(); i++) {   contactModel = contacts.get(i);   final Holder holder = new Holder();  final View view = LayoutInflater.from(this).inflate(R.layout.inflate_record, null);  inflateParentView = (com.rey.material.widget.LinearLayout) view.findViewById(R.id.inflateParentView);  holder.tvName = (TextView) view.findViewById(R.id.tvName);    view.setTag(contactModel.getID());  holder.firstname = contactModel.getFirstName();  holder.lastname = contactModel.getLastName();  String personName = holder.firstname + " " + holder.lastname;  holder.tvName.setText(personName);
  • 39.   final CharSequence[] items = {Constants.UPDATE, Constants.DELETE};  inflateParentView.setOnLongClickListener(new View.OnLongClickListener() {  @Override  public boolean onLongClick(View v) {   AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);  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());  } else {  AlertDialog.Builder deleteDialogOk = new AlertDialog.Builder(MainActivity.this);  deleteDialogOk.setTitle("Delete Contact?");  deleteDialogOk.setPositiveButton("Ok", new DialogInterface.OnClickListener() {  @Override  public void onClick(DialogInterface dialog, int which) {  //sQLiteHelper.deleteRecord(view.getTag().toString());  ContactModel contact = new ContactModel();
  • 40.  contact.setID(view.getTag().toString());  sQLiteHelper.deleteRecord(contact);  displayAllRecords();  }  }  );  deleteDialogOk.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {  @Override  public void onClick(DialogInterface dialog, int which) {   }  });  deleteDialogOk.show();  }  }  });  AlertDialog alertDialog = builder.create();  alertDialog.show();  return true;  }  });  parentLayout.addView(view);  }  } else {  tvNoRecordsFound.setVisibility(View.VISIBLE);  }  } Get all records from Table.
  • 41. ArrayList contacts = sQLiteHelper.getAllRecords();  Getting list of contacts by calling getAllRecords() method of SQLiteHelper Class.  Here, we know that SQLiteHelper.getAllRecords() method returns ArrayList of ContactModel Class. Use Holder class to display records: Holder class contains one TextView to display full name and two String values for first name and last name holding.  private class Holder {  TextView tvName;  String firstname;  String lastname;  }   final Holder holder = new Holder();  final View view = LayoutInflater.from(this).inflate(R.layout.inflate_record, null);  inflateParentView = (com.rey.material.widget.LinearLayout) view.findViewById(R.id.inflateParentView);  holder.tvFullName = (TextView) view.findViewById(R.id.tvFullName);    view.setTag(contactModel.getID());  holder.firstname = contactModel.getFirstName();  holder.lastname = contactModel.getLastName();  String personName = holder.firstname + " " + holder.lastname;  holder.tvFullName.setText(personName);  >> Make an instance of Holder class.
  • 42. >> Get layout as a view using inflate method. >> Get TextView reference from layout. >> Now setTag view which is ID. >> Set First Name and Last Name of holder class from ContactModel class. >> Finaly, set person name to TextView by merging first name and last name. 5.3 Update Record By long pressing on records you will ask for update or delete record  final CharSequence[] items = {Constants.UPDATE, Constants.DELETE};  inflateParentView.setOnLongClickListener(new View.OnLongClickListener() {  @Override  public boolean onLongClick(View v) {   AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);  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.
  • 43. >> 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. 5.3.1 onUpdateRecord()  private void onUpdateRecord(String firstname, String lastname) {  Intent intent = new Intent(MainActivity.this, TableManipulationActivity.class);  intent.putExtra(Constants.FIRST_NAME, firstname);  intent.putExtra(Constants.LAST_NAME, lastname);  intent.putExtra(Constants.DML_TYPE, Constants.UPDATE);  startActivityForResult(intent, Constants.UPDATE_RECORD);  }  Here, we are doing same that we have done on onAddRecord() for making instance of an intent.  We are passing first name and last name with intent to show it on edit text of TableManipulationActivity.  And at the end we are calling startActivityForResult() method with the request of UPDATE_RECORD. >> Start TableManipulationActivity with UPDATE_RECORD request. >> In TableManipulationActivity get Extra value that we have set on last activity.
  • 44.  String request = getIntent().getExtras().get(Constants.DML_TYPE).toString(); >> If request is for updating the record then set the text of the button as Update.  btnDML.setText(Constants.UPDATE); >> onButtonClick() method:  onButtonClick() method is the same method that we have shown at the time of AddRecord. >> onActivityResult(int requestCode, int resultCode, Intent data):  Here, onActivityResult() method will called with UPDATE_RECORD request.  else if (requestCode == Constants.UPDATE_RECORD) {   contact.setID(rowID);  sQLiteHelper.updateRecord(contact);  } >> Here, we already stored FirstName and LastName into ContactModel’s contact object. >> In update we also need rowID which is being affected. So here we also setting rowID. >> And Finally, calling updateRecord() method of SQLiteHelper class. 5.4 Delete Record >> For deleting a record long press on record and select Delete. >> You will be asked for confirmation if you would like to delete the record.  AlertDialog.Builder deleteDialogOk = new AlertDialog.Builder(MainActivity.this);
  • 45.  deleteDialogOk.setTitle("Delete Contact?");  deleteDialogOk.setPositiveButton("Ok", new DialogInterface.OnClickListener() {  @Override  public void onClick(DialogInterface dialog, int which) {  ContactModel contact = new ContactModel();  contact.setID(view.getTag().toString());  sQLiteHelper.deleteRecord(contact);   }  }  ); >> Here, we are making alert dialog for confirmation of deleting record. >> We are deleting the row based rowID, so we have just set the rowID to ContactModel class. >> And call deleteRecord() method of SQLiteHelper class by passing object of ContactModel class. Step 6 Get all table name list into array from sqlite database To get all the table names from the current database. copytextpop-up  public ArrayList<String> getAllTableName()  {  database = this.getReadableDatabase();  ArrayList<String> allTableNames=new ArrayList<String>();  Cursor cursor=database.rawQuery("SELECT name FROM sqlite_master WHERE type='table'",null);  if(cursor.getCount()>0)  {  for(int i=0;i<cursor.getCount();i++)
  • 46.  {  cursor.moveToNext();  allTableNames.add(cursor.getString(cursor.getColumnIndex("name")));  }  }  cursor.close();  database.close();  return allTableNames;  } 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.