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 {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(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. */
myDB.execSQL(“CREATE TABLE IF NOT EXISTS “
+ TableName
+ ” (id INT(4),firstname VARCHAR,lastname VARCHAR);”);
/* Insert data to a Table*/
myDB.execSQL(“INSERT INTO “
+ 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.
c.moveToFirst();
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”;
}while(c.moveToNext());
}
TextView tv = new TextView(this);
tv.setText(ShowData);
setContentView(tv);
}
catch(Exception e) {
Log.e(“Error”, “Error”, e);
} finally {
if (myDB != null)
myDB.close();
}
}
}
great post…
so glad found this post, really help me a lot. thank you
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?