I had success with creating an abstract base class with a database name / create statement and other general information, and then expanding it for each table. That way, I can separate all my CRUD methods (which I prefer). The only drawback is that the DATABASE_CREATE statement must be in the parent class and must include all tables, because after that new tables cannot be added, but, in my opinion, there is a small price to pay for saving CRUD methods for each individual table.
It was pretty easy to do, but here are a few notes:
- The create statement in the parent class must be split for each table, since db.execSQL cannot execute more than one statement.
- I changed all private vars / methods to protected, just in case.
- If you add tables to an existing application (not sure if this is specific to the emulator), the application needs to be removed and then reinstalled.
Here is the code for my abstract parent class, which was based on the Notepad tutorial. Kids just extend this by calling a super constructor (feel free to use this):
package com.pheide.trainose; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public abstract class AbstractDbAdapter { protected static final String TAG = "TrainOseDbAdapter"; protected DatabaseHelper mDbHelper; protected SQLiteDatabase mDb; protected static final String TABLE_CREATE_ROUTES = "create table routes (_id integer primary key autoincrement, " + "source text not null, destination text not null);"; protected static final String TABLE_CREATE_TIMETABLES = "create table timetables (_id integer primary key autoincrement, " + "route_id integer, depart text not null, arrive text not null, " + "train text not null);"; protected static final String DATABASE_NAME = "data"; protected static final int DATABASE_VERSION = 2; protected final Context mCtx; protected static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(TABLE_CREATE_ROUTES); db.execSQL(TABLE_CREATE_TIMETABLES); } @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 routes"); onCreate(db); } } public AbstractDbAdapter(Context ctx) { this.mCtx = ctx; } public AbstractDbAdapter open() throws SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } }
A slightly more detailed explanation is available here: http://pheide.com/page/11/tab/24#post13
phoxicle 03 Oct '10 at 19:48 2010-10-03 19:48
source share