Home > Android > How to use database in Android

How to use database in Android

Android supports SQLite database. In this example we will see these following
1. How to create or open database.
2. How to create table in database.
3. How to insert data in database table.
4. How to fetch data from database table and show.

I tested this example with ‘Andorid-2.2, sdk version-8’.
Packege Name: com.db.cw
Activity Name: DbActivity
File Name: DBActivity.java

Code starts here

package com.db.cw;//Packeage name

import android.app.Activity;
import android.os.Bundle;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.TextView;

public class DbActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
SQLiteDatabase myDB= null;
String TableName = “Profile”;
String ShowData=””;
/* This function create new database if not exists. */
try {
myDB = this.openOrCreateDatabase(“testdb”, MODE_PRIVATE, null);
/* Create a Table in the Database. */
+ TableName
+ ” (id INT(4),firstname VARCHAR,lastname VARCHAR);”);
/* Insert data to a Table*/
+ TableName
+ ” (id, firstname, lastname)”
+ ” VALUES (1, ‘Yaju’, ‘Kumar’);”);

/*Fetch data from database table */
Cursor c = myDB.rawQuery(“SELECT * FROM ” + TableName , null);

int id = c.getColumnIndex(“id”);
int fristName = c.getColumnIndex(“firstname”);
int lastName = c.getColumnIndex(“lastname”);

// Check result.
if (c != null) {
// Loop through all Results
do {
int personId = c.getInt(id);
String FirstName = c.getString(fristName);
String LastName = c.getString(lastName);
ShowData =ShowData +personId+” .) “+FirstName+” “+LastName+”\n”;
TextView tv = new TextView(this);
catch(Exception e) {
Log.e(“Error”, “Error”, e);
} finally {
if (myDB != null)


  1. Vivek Bhusal
    July 19, 2012 at 5:37 am

    great post…

  2. azul
    July 30, 2012 at 3:40 am

    so glad found this post, really help me a lot. thank you 🙂

  3. Abhishek kumar
    August 28, 2012 at 9:12 am

    i have done the same thing as u did, but it is not showing any database. It runs successfully but it only shows a blank activity. Am i missing something?

  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: