Android Tutorial – Step By Step Learning Android Sqlite Database for Beginner

Seegatesite – Today i will share an article about  Android Tutorial – Step By Step Learning Android Sqlite Database for Beginner . To learn android sqlite database, it is good we know the various data storage media which are owned by the android. Most applications require a medium for storing information inside. There are a lot of data storage options of android.

Here are the locations that can be used to store data permanent and most commonly used :

  • Shared Preferences : Permanent data storage in the form of key pair.
  • Internal Storage : locations where we can store files in the internal storage of the device. By default, files will be stored in the internal storage that is part of the application. When uninstalling the application, then the internal storage will also be deleted.
  • Local cache : if we want to cache data and open the store, we need a method getCacheDir () on the object activity or context.
  • External Storage : such as SD Cards and other external media.
  • Database Sqlite : A reliable database which I will discuss in this article.

Introduction Sqlite Database

Sqlite database is open source embedded database on android. To use sqlite in android application, available package by name android.database.sqlite. There are three main components that are used to handle sqlite in android


SQLiteOpenHelper used to determine the name and version of the database that will be used, in this class there is a onCreate() and onUpgrade() method. onCreate() invoked if the database doesn’t exist. Moreover this method is used to update the database schema the most recent.

SQLiteOpenHelper have getReadableDatabase() and getWritableDatabase() method  in order to access to the object SQLiteDatabase, either in read or write mode


SQLiteDatabase is the base class for sqlite database in android. This method is used to execute multiple SQL syntax such as query, update, insert and delete. SQLiteDatabase have many methods such as insert(), update(), delete() and also execSQL() used for the execution of the database directly.

In order the insert() and update() can work well, we need to define the object ContentValues key / value to the table. Key presented the identity column in the table. Value present the records in the table in the column.

A query can be made using the rawQuery() and query() method through SQLiteQueryBuilder class. Method rawQuery() accepts a SQL statement as input. While the method query() has a structured interface to specify the SQL query.  SQLiteQueryBuilder is a class that allows you to create SQL queries.


Cursor cursor = getReadableDatabase();
rawQuery("select * from table where address = ?",new String[]{id});


return database.query(database_table,new String[]{key_1,key_3,key_2},null,null,null,null,null);


Query function to return the cursor object, so that the cursor is the result of a query, one row (record) of the query results. With android cursor can perform buffer query results with efficient because it doesn’t need to load data into memory.

Several methods are commonly used

  • getCount() : To get the number of elements of the query results.
  • moveToFirst() : to move to the beginning of the line
  • moveToNext() : to move to the next line.
  • isAfterLast() : to check whether the last record of a query

Immediately, we learn through examples

Step By Step Learning Android Sqlite Database with Simple Example

1. Create a new android project with the name SqlDatabase. Read the introduction of android studio for beginners if you don’t understand how to create a new project on android studio.

2. Create a new java file named and copy the following script

package com.example.seegate.sqldatabase; // change with your package name

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

 * Created by seegate on 1/17/2016.
public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "ProfileDb";
    private static final String TABLE_PERSON = "t_person";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_COUNTRY = "country";

    public DatabaseHandler(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    public void onCreate(SQLiteDatabase db) {
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_COUNTRY + " TEXT" + ")";
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    public void save(Person person){
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put(KEY_NAME, person.getName());
        values.put(KEY_COUNTRY, person.getCountry());

        db.insert(TABLE_PERSON, null, values);

    public Person findOne(int id){
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor cursor=db.query(TABLE_PERSON, new String[]{KEY_ID,KEY_NAME,KEY_COUNTRY},
                KEY_ID+"=?", new String[]{String.valueOf(id)}, null, null, null);
        return new Person(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2));

    public List<Person> findAll(){
        List<Person> listperson=new ArrayList<Person>();
        String query="SELECT * FROM "+TABLE_PERSON;

        SQLiteDatabase db=this.getReadableDatabase();
        Cursor cursor=db.rawQuery(query, null);

                Person person=new Person();

        return listperson;

    public void update(Person person){
        SQLiteDatabase db=this.getWritableDatabase();

        ContentValues values=new ContentValues();
        values.put(KEY_NAME , person.getName());
        values.put(KEY_COUNTRY, person.getCountry());

        db.update(TABLE_PERSON, values, KEY_ID+"=?", new String[]{String.valueOf(person.getId())});

    public void delete(Person person){
        SQLiteDatabase db=this.getWritableDatabase();
        db.delete(TABLE_PERSON, KEY_ID+"=?", new String[]{String.valueOf(person.getId())});

Explanation :

Learning Sqlite Android How To Create Save Method For Beginner

Method save() is used to store the new data into the database. This method has a parameter in the form of an object from the Person class. ContentValues used to assign values to the table column. Furthermore, the process of storing data only call methods insert() owned by SQLiteOpenHelper.

The inserts() has the following parameters

public long insert (String table, String nullColumnHack, ContentValues values).

For details please visit

Learning Sqlite Android How To Create Update Method For Beginner

Method update() is used to update old data in the database. The update process has the following parameters

public int update (String table, ContentValues values, String whereClause, String[] whereArgs)

For details please visit

Learning Sqlite Android How To Create Delete Method For Beginner

Delete method used to remove data from the database. Sqlite delete process has the following parameters

public int delete (String table, String whereClause, String[] whereArgs)

For details please visit

Android Tutorial Learning Sqlite Android How To Show Table From Query Method Sqlite

The following method is tasked takes one row of data in the database with the parameters held in the form id. This method returns an object that has a class book that corresponds to the parameter id.

Android Tutorial Learning Sqlite Android How To Show Cursor From Arraylist Sqlite Android

Taking all the available data in the database need to iterate on Cursor and then turn them into objects of persons and put on a list.

3. Creating an entity As usual when it will perform the operation associated with the data we modeled the data into a Java class along with its property that adapts to a column in the table that we have made above.

package com.example.seegate.sqldatabase; // change with your package name

 * Created by sigit on 18/01/16.
public class Person {
    private int id;
    private String name;
    private String country;

    public Person(){}

    public Person(String name,String country){;;

    public Person(int id,String name,String country){;;;

    public int getId() {
        return id;
    public void setId(int id) { = id;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String getCountry() {
        return country;
    public void setCountry(String country) { = country;

4. Class to manipulate the data in the database is finished we make. Then we will finish the entire code and create a class above the main class / In this example we will see if the results DatabaseHandler class that we make are correct or not?. We checked through the Debug Log on android studio. Please copy the following code on

package com.example.seegate.sqldatabase; // change with your package name

import android.os.Bundle;
import android.util.Log;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

        DatabaseHandler databaseHandler=new DatabaseHandler(this);

        Log.d("insert", "inserting data"); Person("Sigit", "Indonesia")); Person("Linus Torvalds","Finlandia"));

        Log.d("reading", "reading all data");
        List<Person> listPerson=databaseHandler.findAll();
        for(Person b:listPerson){
            Log.d("data", "ID :"+b.getId()+" | Name :"+b.getName()+" | Country :"+b.getCountry());

        Log.d("reading","reading one data");
        Person b=databaseHandler.findOne(2);
        Log.d("data", "ID :"+b.getId()+" | Name :"+b.getName()+" | Country :"+b.getCountry());

        Log.d("update","updating data");
        b.setName("Sigit Prasetya Nugroho");
        Log.d("reading","reading one data after update");
        Person bUpdate=databaseHandler.findOne(2);
        Log.d("data", "ID :"+bUpdate.getId()+" | Name :"+bUpdate.getName()+" | Country :"+bUpdate.getCountry());

        Log.d("delete", "deleting data");
        Log.d("reading", "reading all data after delete");
        List<Person> listPerson2=databaseHandler.findAll();
        for(Person b2:listPerson2){
            Log.d("data", "ID :"+b2.getId()+" | Name :"+b2.getName()+" | Country :"+b2.getCountry());

Explanation :

To see the results of the activity above, please refer to the debug log you

Android Tutorial Learning Sqlite Android Showing Log Debug On Android Studio

The results are as shown below

Android Tutorial Step By Step Learning Android Sqlite Database For Beginner

How do I display the query results table sqlite to listview?

Learning Sqlite Android How To Show Table Result To Listview Android

1. Create a new layout with the name list_item.xml and copy the following code

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="" android:id="@+id/TableLayout1" android:layout_width="match_parent" android:layout_height="match_parent" >

    <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="4dp" >

        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Name : " android:id="@+id/textView3" android:layout_column="3" />

        <TextView android:id="@+id/outname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dp" android:text="Name" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="4" />


    <TableRow android:layout_width="match_parent" android:layout_height="match_parent">

        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Country : " android:id="@+id/textView2" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="3" />

        <TextView android:id="@+id/outaddress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dp" android:text="Address" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="4" />

    <TableRow android:layout_width="match_parent" android:layout_height="match_parent">



Table row above will be displayed as a list of items in the ListView

2. Add listview on your activity_main.xml

<ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="305dp" app:listitem="@layout/list_item" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" />

To add list_item.xml the ListView using the following code


3. Add scripts on we have made as follows:

public ArrayList<ArrayList<Object>> ambilSemuaBaris() {

        ArrayList<ArrayList<Object>> dataArray = new ArrayList<ArrayList<Object>>();
        Cursor cur;
        try {
            SQLiteDatabase db=this.getReadableDatabase();
            cur = db.query(TABLE_PERSON, new String[] { KEY_NAME, KEY_COUNTRY },
                    null, null, null, null, null);
            if (!cur.isAfterLast()) {
                do {
                    ArrayList<Object> dataList = new ArrayList<Object>();
                } while (cur.moveToNext());


        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.e("DEBE ERROR", e.toString());
        return dataArray;

4. Create a new class with the name to display the query results in a TextView in the list_item.xml.

package com.example.seegate.sqldatabase; // change with your package name

 * Created by sigit on 20/01/16.
import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class PersonAdapter extends BaseAdapter {
    private static ArrayList<Person> searchArrayList;

    private LayoutInflater mInflater;

    public PersonAdapter(Context context, ArrayList<Person> results) {
        searchArrayList = results;
        mInflater = LayoutInflater.from(context);

    public int getCount() {
        return searchArrayList.size();

    public Object getItem(int p) {
        return searchArrayList.get(p);

    public long getItemId(int p) {
        return p;

    public View getView(int p, View v, ViewGroup parent) {
        ViewHolder holder;

        if (v == null) {
            v = mInflater
                    .inflate(R.layout.list_item, null);
            holder = new ViewHolder();

   = (TextView) v.findViewById(;
            holder.address = (TextView) v.findViewById(;

        } else {
            holder = (ViewHolder) v.getTag();
        return v;

    static class ViewHolder {
        TextView name, address;



5. To display the data in a ListView, we will change the code on MainActivity.xml that we created earlier. Please copy the following script

package com.example.seegate.sqldatabase;

import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Person komponenperson;
    ArrayList<Person> isiperson = new ArrayList<Person>();

    private ListView listcontent = null;
    protected void onCreate(Bundle savedInstanceState) {
        DatabaseHandler databaseHandler=new DatabaseHandler(this); Person("Sigit", "Indonesia")); Person("Linus Torvalds", "Finlandia"));

        listcontent=(ListView) findViewById(;

    private void tampilPerson() {
        // TODO Auto-generated method stub
        DatabaseHandler databaseHandler=new DatabaseHandler(this);
        ArrayList<ArrayList<Object>> data =  databaseHandler.ambilSemuaBaris();

        for (int p = 0; p < data.size(); p++) {
            komponenperson = new Person();
            ArrayList<Object> baris = data.get(p);
            Log.e("baris", baris.get(0).toString());
            Log.e("baris", baris.get(1).toString());
        PersonAdapter datakamus = new PersonAdapter(MainActivity.this,isiperson);

Thus article about Android Tutorial – Step By Step Learning Android Sqlite Database for Beginner, hope useful

The following two tabs change content below.
This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.


 Add your comment
  1. This tutorial is good for ones who only want to use SQLite directly. I think it is better to use an ORM.

  2. Thank you so much for this Tutorial, It really helped a lot!!

  3. Thanks Id Like your post, but, I have some problems creating my database, can you help me??
    I need to create a database that saves information from a checkbox like a yes o no, o true and false, please help me!!!

  4. I can’t download source code

Leave a Comment

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

%d bloggers like this: