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.)