Working with SQLite on Android

From last few month, I was not able to post any new topic. So today thought to post something, but what? Then I remembered how much I had broken my head to start with the SQLite in android.

I had found few difficulties while learning because of:

  • All the database operation must has done from code only
  • Reading the data from database using ADB sell was difficult
  • If I am debugging from mobile, the data base is not accessible only

Later I manage to learn it and build a sample Application before I had to start my project. Here I am going to explain the same project which will insert record and display records in the same interface. It may be helpful for my readers.

Fig : Package Explorer of the example project

Here first step is to create a class that inherits from SQLiteOpenHelper class. This class provides three methods  two methods to override and one constructor of super class :

  • onCreate(SQLiteDatabase db): invoked when the database is created, this is where we can create tables and columns to them, create views or triggers.
  • onUpgrade(SQLiteDatabse db, int oldVersion, int newVersion): invoked when we make a modification to the database such as altering, dropping , creating new tables.
  • DatabaseHelper(Context context) : invokes to create database by providing the target context with database name and schema version.

 (It is better to put the entire database, tables and fields name in static variable so that writing code will be easier)

package com.student;

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

public class DatabaseHelper extends SQLiteOpenHelper {
static final String db_demo = "db_demo";
static final String tbl_student = "tbl_student";

static String name = "name";
static String t1 = "test1";
static String t2 = "test2";
static String t3 = "test3";

// method to create or connect to a database
public DatabaseHelper(Context context) {
super(context, db_demo, null, 2);

public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + tbl_student + "(id  INTEGER PRIMARY KEY, "
+ "name TEXT, " + t1 + " INTEGER, " + t2 + " INTEGER, " + t3
+ " INTEGER);");


public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.v("Constatnts :",
"Upgrading Data, Which Will Destroy All Old Data");
db.execSQL("DROP TABLE IF EXISTS  " + tbl_student);


So, here is the class which will take care of creating database, tables and upgrading the database.

Then we will create an Interface where we will write the code for insertion of the data into the table and selecting the data from same table.

The selected data I have displayed into the list view, as I have shown in one of my previous post.

package com.student;

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.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity implements OnClickListener {
EditText et_name, et_t1, et_t2, et_t3;
Button btn_save;
ListView listView;
String name, t1, t2, t3;

List<String> list_name = new ArrayList<String>();
List<Integer> list_t1 = new ArrayList<Integer>();
List<Integer> list_t2 = new ArrayList<Integer>();
List<Integer> list_t3 = new ArrayList<Integer>();
static String[] arr_name;
static Integer[] arr_t1;
static Integer[] arr_t2;
static Integer[] arr_t3;

public void onCreate(Bundle savedInstanceState) {

et_name = (EditText) findViewById(;
et_t1 = (EditText) findViewById(;
et_t2 = (EditText) findViewById(;
et_t3 = (EditText) findViewById(;
btn_save = (Button) findViewById(;

listView = (ListView) findViewById(;
listView.setAdapter(new EfficientAdapter(this));


public void onClick(View v) {

if (v == btn_save) {
if (et_name.length() <= 0 || et_t1.length() <= 0
|| et_t2.length() <= 0 || et_t3.length() <= 0) {
Toast.makeText(this, "Please fill each field",
name = et_name.getText().toString();
t1 = et_t1.getText().toString();
t2 = et_t2.getText().toString();
t3 = et_t3.getText().toString();

DatabaseHelper dbh = new DatabaseHelper(this);
SQLiteDatabase db = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(, name);
cv.put(dbh.t1, t1);
cv.put(dbh.t2, t2);
cv.put(dbh.t3, t3);
try {
// db.insert(dbh.tbl_student, null, cv); or
db.insertOrThrow(dbh.tbl_student, null, cv);
} catch (Exception ex) {
"Sorry data can't be saved. error:" + ex.toString(),
} finally {
Toast.makeText(this, "Data has been saved.", Toast.LENGTH_SHORT)
listView.setAdapter(new EfficientAdapter(this));

public void readDBdata() {
DatabaseHelper dbh = new DatabaseHelper(this);
SQLiteDatabase db = dbh.getWritableDatabase();
Cursor cursor = db.rawQuery("Select " + + "," + dbh.t1 + ","
+ dbh.t2 + "," + dbh.t3 + " from tbl_student;", null);

if (cursor.moveToFirst()) {
do {
} while (cursor.moveToNext());
if (cursor != null && !cursor.isClosed()) {
arr_name = new String[list_name.size()];
arr_t1 = new Integer[list_t1.size()];
arr_t2 = new Integer[list_t2.size()];
arr_t3 = new Integer[list_t3.size()];

for (int i = 0; i < list_name.size(); i++) {
arr_name[i] = list_name.get(i);
arr_t1[i] = list_t1.get(i);
arr_t2[i] = list_t2.get(i);
arr_t3[i] = list_t3.get(i);
// Toast.makeText(this, list_t3.toString(), Toast.LENGTH_SHORT).show();

private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;

public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);

public int getCount() {
return arr_name.length;

public Object getItem(int position) {
return position;

public long getItemId(int position) {
return position;

public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.three_col_row, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
holder.text2 = (TextView) convertView
holder.text3 = (TextView) convertView

} else {
holder = (ViewHolder) convertView.getTag();

holder.text2.setText(String.valueOf(arr_t1[position] + ", "
+ arr_t2[position] + ", " + arr_t3[position]));
+ arr_t2[position] + arr_t3[position]) / 3)));

return convertView;

static class ViewHolder {
TextView text1;
TextView text2;
TextView text3;
public void deleteDatabase() {
DatabaseHelper dbh = new DatabaseHelper(this);
SQLiteDatabase SQLDb = dbh.getWritableDatabase();
if (this.deleteDatabase(dbh.db_demo)) {
Log.d("Droped", "deleteDatabase(): database deleted.");
} else {
Log.d("Cant Drop", "deleteDatabase(): database NOT deleted.");

Fig: Output for the project

This is not the end of the project execution. After developing the SQlite project in android, running the application successfully is one another challenging job.

While running executing the application we should always check the log for the possible errors and exceptions.

To check the data in the database, we have to go through some few steps

Find the location of the database from Windows > Show View > Other > Android  > File Explorer

You can find database in,

data>data>com.<project name>.databases>your database

Now we have to use access same location from the ADB shell

To access database data base, go to command prompt and change location to platform-tools inside android-sdk .

Then execute the “adb shell” command and give the location to your database

“sqlite3 /data/data/com.<project_name>/databases/<database_name>”

Now you are into your database, you can execute the SQlite query for the database.

(Note: we can view the database only if we are executing the application in emulator, while executing in mobile viewing the database permission will not be there.)

13 Responses to Working with SQLite on Android

  1. Hal says:

    I’m not surprised that you had difficulty as you indicated in learning to use SQLite in Android. Most of the documentation on it is extremely poor, and unfortunately consists primarily of recipes for different specific applications rather than actual fundamentals. Even though I have used SQLite in both C#, and even in that most objectionable language Objective C with iPhone applications, I have had a devil of a time making sense of the vast majority of Android documentation on the use of SQLite.

  2. Abhinov says:


    i have a doudt on how to store and retrive images into database and show that in a listview with textviews….can u give me a breif description about that i have gone through many codes but i didnt get the exact output of what i want so please help me in doing that..

    thanks in advance

  3. joe says:

    main.xml and three_col_row code ?

  4. Saw says:

    Hi, I need your help. Why my data>data does not display the database? What should we do other than add in, and 2 xml file? Should I add SQLite on the project on Eclipse?

  5. Kevin says:

    Hi, I need some help. How can I insert parse xml data from the internet into sqlite?? I’m having a very hard time in this one. Can you send me codes for this?thanks.

    By the way, very nice tutorial you got there..

    • Prashant says:

      Sorry, I am quite busy these days to give you the source code.

      but if you can read the xml file from android, you can put the insertion into the loop and put them into sqlite

  6. Pingback: Populate data in EditText boxes : Android Community - For Application Development

  7. Harry says:

    Its awesome and so helpful. Can u help me to read the data in an activity which is inserted in another activity. I want to get data in my next activity in android which i insert in another activity. please help

    • Prashant says:

      I guess, static variables can be useful in this case. create a static variable in the next activity, and you can add data before you go to the activity.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: