Thursday 27 December 2012

SQLiteOpenHelper Demo



1.Activity:

package com.venkool.databasedemo;

import android.app.Activity;

public class DatabaseDemoActivity extends Activity {
      /** Called when the activity is first created. */

      MyDatabase database;

      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            database = new MyDatabase(this, "MyDB.sqlite", null, 1);

            database.insert("venkool", "2000");
      }
}

2.Database Class:
public class MyDatabase extends SQLiteOpenHelper {

      SQLiteDatabase sqliteDatabase;

      public MyDatabase(Context context, String name, CursorFactory factory,
                  int version) {
            super(context, name, factory, version);
            // TODO Auto-generated constructor stub
      }

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

            db.execSQL("create table MyTable(name text,salary text)");

      }

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

      }

      public void open() {
            sqliteDatabase = getWritableDatabase();
      }

      public void close() {
            sqliteDatabase.close();
      }

      public void insert(String name, String salary) {

            open();
           
            try {
                  ContentValues values = new ContentValues();
                  values.put("name", name);
                  values.put("salary", salary);

                  sqliteDatabase.insert("MyTable", null, values);
            } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }

            close();
      }
}

No comments:

Post a Comment