Search code examples
javaandroidandroid-sqlite

How can I create a table in my DB, after dropping all of my tables in database?


I see my tables in the DB with this query,..

(SELECT name
FROM sqlite_master 
WHERE type ='table' AND name NOT LIKE 'sqlite_%';)

after (Dropping allmytable) I cant create a table ,...

package com.ariaz.amirmkaa.litner002;

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

public class DatabaseManager extends SQLiteOpenHelper {

public DatabaseManager(Context context)
{
    super(context, "myDB", null, 1);
}

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

    String card_tbl = "CREATE TABLE \"cards_tbl\" (\n" +
            "\t\"id\"\tINTEGER NOT NULL,\n" +
            "\t\"questiontx\"\tTEXT NOT NULL,\n" +
            "\t\"questionpic\"\tBLOB,\n" +
            "\t\"solutiontx\"\tTEXT NOT NULL,\n" +
            "\t\"solutionpic\"\tBLOB,\n" +
            "\t\"days\"\tINTEGER NOT NULL,\n" +
            "\t\"bookid\"\tINTEGER NOT NULL,\n" +
            "\t FOREIGN KEY (bookid)\n" +
            "       REFERENCES book_tbl (bookid)\n" +
            ");";

    db.execSQL(card_tbl);
}

Solution

  • I believe that your issue is that the onCreate method only runs when the database is first created (i.e. if the database file does not exist), it will not run as long as the database exists.

    Dropping all the tables as extracted from sqlite_master does not delete the database, the database will at the minimum have the sqlite_master table, which cannot be dropped as it is protected.

    When you drop all the tables you could call the onCreate method.

    • Typically when developing, after making changes to the schema of an App you either delete the App's data or Uninstal the App, this will result in the database being deleted and thus the onCreate method runs. When doing such changes after an App is published you then typically utilise the the database version (the 4th parameter passed in super(context, "myDB", null, 1);) along with suitable migration code in the opUpdate method.