Skip to content Skip to sidebar Skip to footer

Android Sqlite Database Is Not Created

The SQLite database is not created. I am playing with this for the past few hours but now i got tired a lot. I am not getting any errors or warnings in the Log Cat. Here is my code

Solution 1:

At last, I shot the problem directly into the head. But How?

The logic of the SQLiteOpenHelper is that it doesn't call the onCreate method by only creating its object.

  1. Whenever you try to access the database for retrieving or inserting data, if the database is not already created/available, it will call the onCreate method for the first time.
  2. The onUpgrade method will be called if the database is available but the version is lower than the one you provide.

I created a fillTable method in my MySQLiteHelper class where I tried to access the database for the first time for writing by calling getWritableDatabase method of the SQLiteOpenHelper. The definition of the fillTable method looks like this.

publicvoidfillTable(){
    db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(CITY_CODE, "333");
    db.insert(TABLE_NAME, null, values);
    db.close();
    readCity();
}

Call the fillTable method on a new instance of the class:

new MySQLiteHelper(MainActivity.this).fillTable();

Thanks to all those who tried to help me in comments.

Solution 2:

publicMySQLiteHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    cont = context;
    SQLiteDatabasedb=this.getReadableDatabase();
    Toast.makeText(cont, "constructor called", Toast.LENGTH_LONG).show();
}

Change the constructor code, then it will work...

Post a Comment for "Android Sqlite Database Is Not Created"