-2

How to open database in Android programming ?

2 Answers 2

6

Extend the SQLiteOpenHelper class like so:

private static class MyDbHelper extends SQLiteOpenHelper
{

    public MyDbHelper(Context context, String description, CursorFactory factory, int version)
    {
        super(context, description, factory, version);          
    }

    @Override
    public void onCreate(SQLiteDatabase _db)
    {
        _db.execSQL(CREATE_TABLE_1);
        _db.execSQL(CREATE_TABLE_2);
        _db.execSQL(CREATE_TABLE_3);
        ..etc
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion)
    {
        // Log the version upgrade.
        Log.w("MyDbAdapter", "Upgrading from version " + oldVersion + " to " +
                newVersion + ", which will destroy all old data.");

        _db.execSQL("DROP TABLE IF EXISTS " + TBL_ONE);
        _db.execSQL("DROP TABLE IF EXISTS " + TBL_TWO);
        _db.execSQL("DROP TABLE IF EXISTS " + TBL_THREE);

        onCreate(_db);          
    }

}

Create a data adapter class that uses the dbhelper:

private SQLiteDatabase db;  
private MyDbHelper dbHelper;

public MyDbAdapter(Context context)
{       
    dbHelper = new MyDbHelper(context, DATABASE_NAME, null, DB_VERSION);
}


public MyDbAdapter open() throws SQLException
{
    try
    {
        db = dbHelper.getWritableDatabase();
    }
    catch (SQLiteException ex)
    {
        db = dbHelper.getReadableDatabase();
    }

    return this;
}

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

And then it can be used thus:

 public class ListsDAO
 {
private Context mContext;
private MyDbAdapter db;

public ListsDAO(Context context)
{
    mContext = context;
    db = new MyDbAdapter(mContext);
}

public List<MyObject> getAllObjects()
{
    List<MyObject> objects = new ArrayList<MyObject>();

    db.open();
    Cursor cursor = db.getAllObjects();     

    if (cursor.moveToFirst())
    {

... etc Once you've got the cursor on a list of rows you can step through them getting the various columns in the table:

e.g. description = cursor.getString(descriptionColumn);

The static strings such as CREATE_TABLE_1 are basically SQL statements for creating the tables. You may also want a less drastic database upgrade route than simply dropping all the tables and recreating them again.

0

Damned! John J Smith has a more complete and faster answer!

Android comes with SQLite, which is a very light on-board database engine.

You can find lots of resources and tutorials on the Android Developer site or elsewhere on the internet, for example :

Below is some code defining a class to cleanly manage a database (partially copied from the notepad tutorial referenced above).
To open the database, instantiate a MyDb object an call its open() method.

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDb {
    private class MyDbHelper extends SQLiteOpenHelper {   
        MyDbHelper(Context context) {
            super(context, "myfirstdatabase", null, 1);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            String createDbRequest = "CREATE TABLE .... "; // write the SQL query to create the first table
            db.execSQL(createDbRequest);
            // add other queries for more tables
        }
    }

    private MyDbHelper mDbHelper;
    private SQLiteDatabase mDb;
    private Context mContext;

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public MyDb(Context ctx) {
        mContext = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDb open() throws SQLException {
        mDbHelper = new MyDbHelper(mContext);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.