Tuesday, July 10, 2012

Connect SQLite Database from Android



Click Here to download source code

Package name  :  db.com

Project name   :  DBAdapter

Version            :  1.5 (Supports 1.5 and above versions)


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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>



DBAdapterActivity.java


package db.com;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.database.Cursor;

public class DBAdapterActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        DBAdapter db = new DBAdapter(this);
       
        db.open();
        long id = db.insertContact("android","www.androidprogramz.in");
        id = db.insertContact("Blog","androidprogramz.blogspot.in");
        Log.d("","insert done");
        db.close();
       
        db.open();
        Cursor c = db.getAllContacts();
        Log.d("","select done");
        if (c.moveToFirst())
        {
        do {
        DisplayContact(c);
        } while (c.moveToNext());
        }
        db.close();
        }
        public void DisplayContact(Cursor c)
        {
        Toast.makeText(this,
       "id:" + c.getString(0) +"\n" +"Name:" + c.getString(1) +"\n" +
       "Website:" + c.getString(2),
        Toast.LENGTH_LONG).show();
        }
       
       
       
    }
 



DBAdapter.java

package db.com;
import android.content.ContentValues;
import android.content.Context;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter
{
    public static final String KEY_ROWID ="_id";
    public static final String KEY_NAME ="name";
    public static final String KEY_SITE ="website";
    private static final String TAG ="DBAdapter";
    private static final String DATABASE_NAME ="MyDb";
    private static final String DATABASE_TABLE ="contacts";
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_CREATE =
            "create table contacts (_id integer primary key autoincrement,name text not null, website text not null);";
    private final Context context;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;
    public DBAdapter(Context ctx)
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            Log.d("","constructor done");
        }
        @Override
        public void onCreate(SQLiteDatabase db)
        {
            try {
                db.execSQL(DATABASE_CREATE);
                Log.d("","create done");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            Log.w(TAG,"Upgrading database from version" + oldVersion +" to"
                    + newVersion +", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }
    //    ---opens the database---
    public DBAdapter open() throws SQLException
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }
//    ---closes the database---
    public void close()
    {
        DBHelper.close();
    }
//    ---insert a contact into the database---
    public long insertContact(String name, String email)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_SITE, email);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }
//---deletes a particular contact---
    public boolean deleteContact(long rowId)
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID +"=" + rowId, null) > 0;
    }
//    ---retrieves all the contacts---
    public Cursor getAllContacts()
    {
        return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
                KEY_SITE}, null, null, null, null, null);
       
    }
//---retrieves a particular contact---
    public Cursor getContact(long rowId) throws SQLException
    {
        Cursor mCursor =
                db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                        KEY_NAME, KEY_SITE}, KEY_ROWID +"=" + rowId, null,
                        null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
     //    ---updates a contact---
    public boolean updateContact(long rowId, String name, String email){
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);
        args.put(KEY_SITE, email);
        return db.update(DATABASE_TABLE, args, KEY_ROWID +"=" + rowId, null) > 0;
        }
        }


OUTPUT:







Click Here to download source code


1 comment:

  1. Take a look on a free tool -- Valentina Studio. Amazing product! IMO this is the best manager for SQLite for all platforms. http://www.valentina-db.com/en/valentina-studio-overview

    ReplyDelete