Wednesday, 16 January 2013

Simple SQLiteDatabase Example in Android

ScreenShots:
activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

</LinearLayout>

MainActivity.java:

package com.ram.simplesqlitedatabase;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

SQLiteDatabase db = openOrCreateDatabase("ramsdb", MODE_PRIVATE, null);

db.execSQL("create table if not exists sampletable(firstname varchar,lastname varchar)");

db.execSQL("insert into sampletable values('ram','babu')");

Cursor c = db.rawQuery("select * from sampletable", null);

c.moveToFirst();

//Getting data using column name
String fname = c.getString(c.getColumnIndex("firstname"));

//Getting data using column index number
String lname = c.getString(1);

Toast.makeText(getApplicationContext(), "firstname :"+fname+"\n"+"lastname :"+lname, Toast.LENGTH_LONG).show();

}