Thursday, 7 February 2013

SQLite Database in Android

These are memory available in android device's.
  • Internal 
  • SD-Card
  • External-SD-Card(Removable) 
External-SD-Card is not available in All device. 

                                              How to create Database in Internal Memory

Database file.

import java.io.File;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MyDatabase extends SQLiteOpenHelper
{
        public static final String  DATABASE_NAME = "mytest";
        public final static String NAME ="name";
public final static String ADDRESS ="address";
public final static String CITY ="city";
Context  context = null;

public MyDatabase (final Context context) {
super(context,DATABASE_NAME, null, 1);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL( "CREATE TABLE mylistdata(_id INTEGER PRIMARY KEY           AUTOINCREMENT,name TEXT, address TEXT,city TEXT);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP Table mylistdata");
onCreate(db);
}

@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
try{
File path = context.getDatabasePath(DATABASE_NAME);
db = SQLiteDatabase.openOrCreateDatabase(path, null);
}

catch(SQLiteException e){
Log.e("Error",""+e.getMessage());
}}
}

Explanation:-

Your class will extends the SQLiteOpenHelper.
SQLiteIOpenHelper having these override method's.
  1. onCreate(SQLiteDatabase db)
  2. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
  3. onOpen(SQLiteDatabase db)
  4. close() 
  5. getReadableDatabase()
  6. getWritableDatabase()
  7. onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion)
First two must override in Database Class.

1- onCreate(SQLiteDatabase)

When you create object of database class in android activity to read/write the database. i.e

MyDatabase database = new MyDatabase(this);
database.getWritableDatabase();

 getWritableDatabase()  first time this is called, the database will be opened andonCreate(SQLiteDatabase)onUpgrade(SQLiteDatabase, int, int) and/or onOpen(SQLiteDatabase) will be called.


first time onCreate(SQLiteDatabase) will be called, after this it will never called again until  you ll not upgrade the Database.(this is optional if we want to call this onUpgrade(db))


2-onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

This method is responsible for upgrade the Database version. you need to set version number in your constuctor. i.e


public MyDatabase (final Context context) {
super(context,DATABASE_NAME, null, 2 /*this is version number*/);
this.context = context;
}

After it if you want update any thing in our previous table ,you can do inside the upgrade method. I ll explain it later.
Note. until you don't increase the version number ,onUpgrade(db)  will not call.

                            Using This class in Activity.


import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Toast;

public class MyActivityClass extends Activity {

 SQLiteDatabase sqldb = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
               saveData();
               readData();
}

 /**
* insert data in to database
*/
public void saveData( ) {

MyDatabase mydb = new MyDatabase (this);
  sqldb = mydb.getWritableDatabase();

//Content value for insert data values.

  ContentValues insertData = new ContentValues();
insertData.put(MyDatabase .NAME, etname.getText().toString());
insertData.put(MyDatabase .ADDRESS, etadd.getText().toString());
insertData.put(MyDatabase .CITY, etcity.getText().toString());

sqldb.insert("mylistdata", MyDatabase.NAME , insertData);
sqldb.close();
Toast.makeText(this,"Data saved", Toast.LENGTH_SHORT).show();
}

/**
* read data from database
*/
public void readData( )
{
MyDatabse mydb = new MyDatabse(this);
 readdata = mydb.getReadableDatabase();

//Cursor will contain all data related selected table.

    Cursor c = readdata.rawQuery("select * from mylistdata", null);
if(c !=null)
{
c.moveToFirst();
while(c.isAfterLast() == false)
{
String name = c.getString(c.getColumnIndex(MyDatabase .NAME));
String address = c.getString(c.getColumnIndex(MyDatabase .ADDRESS));
String city = c.getString(c.getColumnIndex(MyDatabase .CITY));
 
 //check your logcat in eclipse for output
   Log.v("Data read", "Name--"+name+" ,Address--"+address+" City --"+city);

c.moveToNext();
}
   c.close();
}
readdata.close();
}
}


No comments:

Post a Comment