Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLiteOpenHelper onCreate method is not called

The onCreate method is not called even after deinstalling the app and then reinstalling it.

Database.java:

public class Database extends SQLiteOpenHelper {
    public static SQLiteDatabase db;
    public Database(Context context) {
        super(context,"db", null, 1);
        Log.i("DB", "dbManager");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i("DB", "dbOnCreate");
        String s = "CREATE TABLE test(id INTEGER);";
        db.execSQL(s);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        Log.i("DB", "dbOnUpgrade");
    }
}

I call this:

Database db = new Database(this);

Output:

07-17 12:42:03.053 16448-16448/com.package.app I/DB: dbManager

What is this problem and how to resolve it?


2 Answers

public class Database extends SQLiteOpenHelper {
    public static SQLiteDatabase db;
    public Database(Context context) {
        super(context,"db", null, 1);
        getReadableDatabase(); // <-- add this, which triggers onCreate/onUpdate
        Log.i("DB", "dbManager");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i("DB", "dbOnCreate");
        // ...
    }
    // ...
}

Explanation: The update is only triggered if the db is accessed for writing or reading. Since you don't attempt that, onCreate is never called.

Usually, you would just call a method of your Database class somewhere (for example for querying entities) and that is the moment when onCreate/(or onUpdate) would be called.

Since, you don't have such methods (for now), just call it inside the Database constructor.

Or:

Alternatively, and maybe more clean would be to call getReadableDatabase() right after the creation of your Database object:

Database db = new Database(this);
db.getReadableDatabase();
like image 137
Willi Mentzel Avatar answered Dec 14 '25 20:12

Willi Mentzel


@Override
public void onCreate(SQLiteDatabase db) {
   // ...
}

onCreate Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.

Try with

String s = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY);";

Uninstall app and run again. Then check

like image 39
IntelliJ Amiya Avatar answered Dec 14 '25 21:12

IntelliJ Amiya