Lena Bru
Lena Bru

Reputation: 13947

SQLITE Database Tables in Android

I want to create several tables in one database, in my android app.

Each table is named differently, and the I don't find out the name until after the program starts running, so it's all dynamic.

However, the first table gets created, and any new ones, don't I get "no such table" error.

This is what I do to create the table:

private class SQLiteHelper extends SQLiteOpenHelper {
    private static final String TAG = "SQLiteHelper";
    private String DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS "
            + helper.getTableName() + "(" + helper.getTableColumns() + ");";


    public SQLiteHelper(Context context) {
        super(context, helper.getDatabaseName(), null, helper
                .getDatabaseVersion());
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);
        Log.d(TAG, "database created");

    }

    @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 " + helper.getTableName());
        onCreate(db);
    }

}

helper is an object that is passed to the DB constructor

public ProductDB(Context context, IDatabaseHelper helper) {
    this.context = context;
    this.helper = helper;
}

The first time the db is created, everything works and everything as fine, but as soon as I need to add a second table, when I try accessing it, it crashes

What can I do to fix this?

Upvotes: 1

Views: 227

Answers (1)

Nizam
Nizam

Reputation: 5731

Try this:

 SQLiteDatabase db;
 SQLiteHelper dbHelper = new SQLiteHelper(context);
 db = dbHelper.getWritableDatabase();

        db.execSQL("CREATE TABLE IF NOT EXISTS "
            + helper.getTableName() + "(" + helper.getTableColumns() + ")");

Upvotes: 1

Related Questions