Android SQLite Database Example Tutorial - DigitalOcean
Android SQLite Database Example Tutorial - DigitalOcean
CONTENTS
Android SQLite
// Tutorial //
By Anupam Chugh
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 1/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you
have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the
bottom of the tutorial.
Welcome to Android SQLite Example Tutorial. Android SQLite is the mostly preferred way to store data
for android applications. For many applications, SQLite is the apps backbone whether it’s used directly
or via some third-party wrapper. Below is the final app we wil create today using Android SQLite
database.
Android SQLite
Android SQLite is a very lightweight database which comes with Android OS. Android SQLite combines a
clean SQL interface with a very small memory footprint and decent speed. For Android, SQLite is “baked
into” the Android runtime, so every Android application can create its own SQLite databases. Android
SQLite native API is not JDBC, as JDBC might be too much overhead for a memory-limited smartphone.
Once a database is created successfully its located in data/data//databases/ accessible from Android
Device Monitor. SQLite is a typical relational database, containing tables (which consists of rows and
columns), indexes etc. We can create our own tables to hold the data accordingly. This structure is
referred to as a schema.
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 2/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
Android has features available to handle changing database schemas, which mostly depend on using the
SQLiteOpenHelper class. SQLiteOpenHelper is designed to get rid of two very common problems.
1. When the application runs the first time - At this point, we do not yet have a database. So we wil
have to create the tables, indexes, starter data, and so on.
2. When the application is upgraded to a newer schema - Our database wil stil be on the old schema
from the older edition of the app. We wil have option to alter the database schema to match the
needs of the rest of the app.
SQLiteOpenHelper wraps up these logic to create and upgrade a database as per our specifications. For
that we’l need to create a custom subclass of SQLiteOpenHelper implementing at least the following
three methods.
1. Constructor : This takes the Context (e.g., an Activity), the name of the database, an optional
cursor factory (we’l discuss this later), and an integer representing the version of the database
schema you are using (typically starting from 1 and increment later).
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
2. onCreate(SQLiteDatabase db) : It’s called when there is no database and the app needs one. It
passes us a SQLiteDatabase object, pointing to a newly-created database, that we can populate
with tables and initial data.
3. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) : It’s called when the schema
version we need does not match the schema version of the database, It passes us a
SQLiteDatabase object and the old and new version numbers. Hence we can figure out the best
way to convert the database from the old schema to the new one.
We define a DBManager class to perform all database CRUD(Create, Read, Update and Delete)
operations.
Opening and C losing A ndr oid SQLit e D at abase C onnect ion
Before performing any database operations like insert, update, delete records in a table, first open the
database connection by calling getWritableDatabase() method as shown below:
public DBManager open() throws SQLException {
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
The dbHelper is an instance of the subclass of SQLiteOpenHelper . To close a database connection the
following method is invoked.
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 3/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
Inser t ing new Recor d int o A ndr oid SQLit e dat abase t able
The following code snippet shows how to insert a new record in the android SQLite database.
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
}
Content Values creates an empty set of values using the given initial size. We’l discuss the other
instance values when we jump into the coding part.
Updat ing Recor d in A ndr oid SQLit e dat abase t able
A Cursor represents the entire result set of the query. Once the query is fetched a call to
cursor.moveToFirst() is made. Calling moveToFirst() does two things:
It allows us to test whether the query returned an empty set (by testing the return value)
It moves the cursor to the first result (when the set is not empty)
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 4/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
Another way to use a Cursor is to wrap it in a CursorAdapter . Just as ArrayAdapter adapts arrays,
CursorAdapter adapts Cursor objects, making their data available to an AdapterView like a ListView .
Let’s jump to our project that uses SQLite to store some meaningful data.
A ndr oid SQLit e Example Pr oject St r uct ur e
In this application we wish to create records that store Country names and their respective currencies in
the form of a ListView. We cover all the features discusses above.
A ndr oid SQLit e Pr oject C ode
The application consists of 5 classes. We begin with defining with DatabaseHelper, which is a subclass
of SQLiteOpenHelper as follows: DatabaseHelper.java
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 5/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
package com.journaldev.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
// Table Name
public static final String TABLE_NAME = "COUNTRIES";
// Table columns
public static final String _ID = "_id";
public static final String SUBJECT = "subject";
public static final String DESC = "description";
// Database Information
static final String DB_NAME = "JOURNALDEV_COUNTRIES.DB";
// database version
static final int DB_VERSION = 1;
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
As discussed above we have overridden the onCreate() and onUpgrade() methods besides the
constructor. We’ve assigned the names to the database and the table as
JOURNALDEV_COUNTRIES.DB and COUNTRIES respectively. The index column is auto incremented
whenever a new row is inserted. The column names for country and currency are “subject” and
“description”. The DBManager classes is where the DatabaseHelper is initialized and the CRUD
Operations are defined. Below is the code for this class: DBManager.java
package com.journaldev.sqlite;
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 6/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public DBManager(Context c) {
context = c;
}
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 7/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
The CountryListActivity.java class is the activity which is launched when the application starts. Below
is layout defined for it: fragment_emp_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
android:padding="10dp" >
</ListView>
<TextView
android:id="@+id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/empty_list_text" />
</RelativeLayout>
Here a ListView component is defined to included the records stored in the database. Initial y the
ListView would be empty hence a TextView is used to display the same. CountryListActivity.java
package com.journaldev.sqlite;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 8/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
@Override
protected void onCreate(Bundle savedInstanceState) {
Premium CPU-Optimized Droplets are now available. Lear… We're hiring Blog Docs Get Support Contact Sales
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_emp_list);
Tutorials Questions Learning Paths For Businesses Product Docs Social Impact
Cursor cursor = dbManager.fetch();
listView.setAdapter(adapter);
String id = idTextView.getText().toString();
String title = titleTextView.getText().toString();
String desc = descTextView.getText().toString();
startActivity(modify_intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 9/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
int id = item.getItemId();
if (id == R.id.add_record) {
}
return super.onOptionsItemSelected(item);
}
In this activity the DBManager object is invoked to perform the CRUD Operations. A
SimpleCursorAdapter is defined to add elements to the list from the query results that are returned in an
Cursor Object. On list item click an intent is performed to open the ModifyCountryActivity class. The
menu contains an item to add a new record from the ActionBar. Here again an intent is performed to
open the AddCountryActivity class. Below is menu.xml code. menu.xml
<menu xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
tools:context="com.example.sqlitesample.MainActivity" >
<item
android:id="@+id/add_record"
android:icon="@android:drawable/ic_menu_add"
android:orderInCategory="100"
android:title="@string/add_record"
app:showAsAction="always"/>
</menu>
The xml layout and code of AddCountryActivity.java file are defined below: activity_add_record.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp" >
<EditText
android:id="@+id/subject_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_title" >
<requestFocus />
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 10/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
</EditText>
<EditText
android:id="@+id/description_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_desc"
android:inputType="textMultiLine"
android:minLines="5" >
</EditText>
<Button
android:id="@+id/add_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/add_record" />
</LinearLayout>
Two EditText components that take the inputs for country and currency along with a button to add the
values to the database and display it in the ListView are defined. AddCountryActivity.java
package com.journaldev.sqlite;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Add Record");
setContentView(R.layout.activity_add_record);
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add_record:
dbManager.insert(name, desc);
startActivity(main);
break;
}
}
The CRUD operation performed here is adding a new record to the database. The xml layout and code
of ModifyCountryActivity.java file are defined below: activity_modify_record.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<EditText
android:id="@+id/subject_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:ems="10"
android:hint="@string/enter_title" />
<EditText
android:id="@+id/description_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_desc"
android:inputType="textMultiLine"
android:minLines="5" >
</EditText>
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 12/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/btn_update" />
<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/btn_delete" />
</LinearLayout>
</LinearLayout>
It’s similar to the previous layout except that modify and delete buttons are added.
ModifyCountryActivity.java
package com.journaldev.sqlite;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Modify Record");
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 13/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
setContentView(R.layout.activity_modify_record);
_id = Long.parseLong(id);
titleText.setText(name);
descText.setText(desc);
updateBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_update:
String title = titleText.getText().toString();
String desc = descText.getText().toString();
case R.id.btn_delete:
dbManager.delete(_id);
this.returnHome();
break;
}
}
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 14/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
The CRUD operations performed here are updating and deleting a record. The below images are the
screenshots of the final output of our project. The first image is the output seen when the application is
launched for the first time.
The second image is the result of clicking the menu option from the ActionBar to add a new record as
shown below.
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 15/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
The fourth image shows the output when any list item is clicked to modify or delete a record :
The final image is the output when a record is deleted. In this example we delete the first record :
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 16/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 17/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
As we’ve discussed earlier in this tutorial, the database file is stored in the internal storage that is
accessible from the Android Device Monitor as visible in the pic below.
To view this database we need to pull this file from the device to our desktop. This is done by clicking
the menu option in the top right as seen in the image below :
To open this file download the SQLiteBrowser from this link. The snippets below show the schema and
tables in the browser.
To view the table go to the Browse Data tab on top. The following image is seen:
This brings an end to Android SQLite tutorial. The final Android SQLite Project is downloadable from
the below link.
Download Android SQLite Example Project
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute,
storage, networking, and managed databases.
Learn more about us ->
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 18/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
Still looking for an answer? Ask a question Search for more help
Comments
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 19/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
- sahid
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 20/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
- fgoraz
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 21/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
This work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Click below to sign up and get $200 of credit to try our products over 60 days!
Sign up
Popular Topics
Ubuntu
Linux Basics
JavaScript
Python
MySQL
Docker
Kubernetes
All tutorials ->
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 22/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
Become a
contributor
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 23/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
Featured on Community
Kubernetes Course Learn Python 3 Machine Learning in Python Getting started with Go
Intro to Kubernetes
DigitalOcean Products
DigitalOcean makes it simple to launch in the cloud and scale up as you grow – whether you’re running
one virtual machine or ten thousand.
Learn more ->
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 24/25
9/4/23, 10:28 AM Android SQLite Database Example Tutorial | DigitalOcean
Enter your email to get $200 in credit for your first 60 days with DigitalOcean.
Email address
Send My Promo
New accounts only. By submitting your email you agree to our Privacy Policy.
Company
Products
Community
Solutions
Contact
https://www.digitalocean.com/community/tutorials/android-sqlite-database-example-tutorial 25/25