Monday, 10 September 2012

SQLite database tutorial in android | How to use SQLite database in android

Step-1
Create DBSampleActivity.java in your project.


package com.dbsample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.dbsample.database.DbHelper;

public class DBSampleActivity extends Activity {
    /** Called when the activity is first created. */
Button btn_submit, btn_show;
EditText txt_name, txt_mobile, txt_salary;
DbHelper dbhelper;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        btn_submit=(Button)findViewById(R.id.btn_submit);
        btn_show=(Button)findViewById(R.id.btn_show_data);
     
        txt_name=(EditText)findViewById(R.id.txt_name);
        txt_mobile=(EditText)findViewById(R.id.txt_mobile);
        txt_salary=(EditText)findViewById(R.id.txt_salary);
     
        btn_submit.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub

dbhelper=new DbHelper(DBSampleActivity.this);

ContentValues cv=new ContentValues();
if(txt_name.getText().toString()!=null && txt_mobile.getText().toString()!=null && txt_salary.getText().toString()!=null)
{
cv.put(DbHelper.EMP_NAME, txt_name.getText().toString().trim());
cv.put(DbHelper.EMP_MOBILE, txt_mobile.getText().toString().trim());
cv.put(DbHelper.EMP_SALARY, txt_salary.getText().toString().trim());


try
{
dbhelper.insertEmpData(cv);
} catch (SQLiteException e) {
// TODO: handle exception
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
});
     
        btn_show.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
Cursor c=null;
try {
AlertDialog.Builder al=new AlertDialog.Builder(DBSampleActivity.this);
c=dbhelper.showData();

if(c.getCount()>0)
{
for (c.moveToFirst();!c.isAfterLast(); c.moveToNext())
{
//c.getInt(0);
c.getString(1);
c.getString(2);
c.getString(3);


al.setTitle("EMP Details").setMessage("NAME : "+c.getString(1)+" \nMOBILE : "+c.getString(2)+" \nSALARY : "+c.getString(3));
al.setCancelable(true);

}

al.show();
c.close();
}
else
{
Log.d("", "No value to display");
}


} catch (Exception e) {
// TODO: handle exception
c.close();
e.printStackTrace();
}


}
});
            }
}

Step-2

main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >





    <EditText
        android:id="@+id/txt_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter name"
        android:inputType="textPersonName" >

        <requestFocus />

    </EditText>




    <EditText
        android:id="@+id/txt_mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Mobile number"
        android:inputType="number" />




    <EditText
        android:id="@+id/txt_salary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Salary"
        android:inputType="number" />






    <Button
        android:id="@+id/btn_submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Submit" />





    <Button
        android:id="@+id/btn_show_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Data" />

</LinearLayout>

screen shot for main.xml



Step-3:
Create a new java class DbHelper.java


package com.dbsample;

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

public class DbHelper extends SQLiteOpenHelper{

public static String DATABASE_NAME="testdb";
public static String TBL_EMP_DETAILS="records";
public static String EMP_NAME="emp_name";
public static String EMP_MOBILE="emp_mobile";
public static String EMP_SALARY="emp_salary";
private String TAG;

public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
// TODO Auto-generated constructor stub



}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

String query="CREATE TABLE "+TBL_EMP_DETAILS+" ( _id integer primary key autoincrement, "+EMP_NAME+" text not null, "+EMP_MOBILE+" text not null, "+EMP_SALARY+ " text not null )";

db.execSQL(query);

Log.d(TAG, "query executed");

}


public void insertEmpData(ContentValues cv)
{
SQLiteDatabase db=getWritableDatabase();

db.insert(TBL_EMP_DETAILS, null, cv);
}

public Cursor showData()
{
SQLiteDatabase db=getReadableDatabase();

return db.rawQuery("SELECT * FROM "+TBL_EMP_DETAILS, null);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}


}

Step-4:

Now, You run your android project and then insert details then click on show button then you see the output onto the emulator.






Thanks

Regards-
Lalit



7 comments:

  1. thanks for sharing the post....very interesting information, thanks.

    ReplyDelete