Tuesday, October 4, 2011

Android DataBase (Part1)


Contains classes to explore data returned through a content provider.

If you need to manage data in a private database, use the android.database.sqlite classes. These classes are used to manage the Cursor object returned from a content provider query. Databases are usually created and opened with openOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory) To make requests through content providers, you can use the content.ContentResolver class.

All databases are stored on the device in /data/data//databases



Class Overview

A helper class to manage database creation and version management.

You create a subclass implementing onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary.

SQLiteDatabase: provide methods insert(), update(), delete() and execSQL() which allow you to execute query directly.
ContentValue: Alllow to define Key/Values for insert and update. The Key is column and value is the value of the column.

(Source code main Class [ DataBaseDemo.java] ) is

package com.DataBase;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

public class DataBaseDemo extends Activity
public void onCreate(Bundle savedInstanceState) {
DataBaseHelper db_Helper=new DataBaseHelper(this);

(Source code [ DateBaseHelper.java] ) is

package com.DataBase;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class DataBaseHelper extends SQLiteOpenHelper {
public static String dataBase_name="MyFirstDb";
public static String table_name="Employee1";
public static String field1="Name";
public static String field2="Salary";
Context context;
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
public DataBaseHelper(Context c) {
super(c, dataBase_name, null, 1);

public void onCreate(SQLiteDatabase db) {
// Called when the database is created for the first time.
db.execSQL("CREATE Table "+table_name+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Salary REAL)");
public void insertValues(SQLiteDatabase db)
ContentValues cv=new ContentValues();
cv.put(field2, 1000);
long f=db.insert(table_name, null, cv);
Toast.makeText(context,"successfully Inserted",2).show();
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Called when the database needs to be upgraded.(Example create one more table)
db.execSQL("DROP TABLE IF EXISTS "+table_name);


output: can be successfully inserted or Error. check it.

No comments:

Post a Comment