Android SQLiteOpenHelper: Why onCreate() method is not called?

JavaAndroidAndroid Sqlite

Java Problem Overview


I am trying to make my first Android app. I noticed that the SQLiteOpenHelper.onCreate() method is not called to create tables if the database not exists. However, the onCreate() method did not work even thought I tried to debug.

Please look at the code below and give me any suggestions. Any help will be appreciated.

public class NameToPinyinActivity extends Activity {

	DatabaseOpenHelper helper = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nametopinyin);

		Button searchButton = (Button) findViewById(R.id.search);
		searchButton.setOnClickListener(new ButtonClickListener());
		
		helper = new DatabaseOpenHelper(NameToPinyinActivity.this);
	}

public class DatabaseOpenHelper extends SQLiteOpenHelper {

	/** DB Name */
	private static final String DB_NAME = "pinyin";

	/** CREATE TABLE SQL */
	private static final String CREATE_TABLE_SQL = "CREATE TABLE UNICODE_PINYIN"
			+ "(ID INTEGER PRIMARY KEY AUTOINCREMENT, "
			+ "UNICODE TEXT NOT NULL, PINYIN TEXT NOT NULL)";

	public DatabaseOpenHelper(Context context) {
		super(context, DB_NAME, null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.beginTransaction();
		try {
			db.execSQL(CREATE_TABLE_SQL);
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
		}
	}

Java Solutions


Solution 1 - Java

I have also had trouble with the SQLiteOpenHelper. What worked for me was storing a member variable

SQLiteDatabase db;

In the SQLiteOpenHelper subclass and calling

 db = getWritableDatabase();

in the constructor.

The answer to this question also includes helpful information: https://stackoverflow.com/questions/5024223/sqliteopenhelper-failing-to-call-oncreate

I hope this helps!

Solution 2 - Java

Until you call the method getWritableDatabase() or getReadableDatabase() of SQLiteOpenHelper class, database won't be created.

as simple as that database will be created in memory when you actually need that.:)

Solution 3 - Java

I had a similar problem where onCreate wasn't executed. Maybe this is of any use for someone even though it turned out being a different problem.

I was working on the database before and had already created one long time before. So now after making changes in onCreate() I was hoping to find the new tables created. But the SQLiteOpenHelper never called onCreate() again. Reason was, the database already existed. I was still working with the same device as before and consequently with the already existing (old) databse.

But there is hope. When the system sees a database with that name already exists, it also checks whether the version number is correct. In that case I simply forgot the database already existed. My solution was simply changing the version number. So onUpgrade() was called offering options for onCreate() changes.

So options were either uninstalling the complete app (and with it the database) or call onCreate again after upgrading the version number (and for example dropping) the old table and calling onCreate() again.

In any case, if onCreate() is not called, check twice if the database exists. Otherwise it's not called again.

Solution 4 - Java

I had a similar problem however it was not the OnCreate call that was the issue.

In the example code above, Kevin explained that the OnCreate is not called if the database already exists. However if, like me, you are using multiple tables from separate activities, then though you may have created the database already, the table associated with this activity may yet have not been created. Hence when you attempt to set the cursor data on a non-existent table, you will invoke an exception.

My solution was define a separate class called CreateTable which is called both from the OnCreate override and from the constructor after the

db = getWritableDatabase();

Solution 5 - Java

Call getWritableDatabase(); in the constructor

public DataBaseH(@Nullable Context context) {
    super(context, dataBaseName, null, dataBaseVersion);
    SQLiteDatabase db=this.getWritableDatabase();

}

@Override
public void onCreate(SQLiteDatabase db) {
 String createTable="CREATE TABLE IF NOT EXISTS "+tableName+                              " ( "+
            id+  " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"+
            name+                              " TEXT,"+
            familyName+                        " TEXT,"+
            age+                           " INTEGER);";

    db.execSQL(createTable);

     Log.i(TAG,"db.exect");


}

Solution 6 - Java

I was having a similar problem with onCreate() not executing when the app was very first run, so my database never got created. This is NOT the same as when onCreate() is not executing because the database already existed, because the database did not yet exist. Specifically, my DataProvider onCreate() was not executing, so the OpenHelper never got called either.

I verified I had everything set up the way that everyone described in the previous answers, but nothing resolved my problem. Posting this answer in case anyone else forgets one small detail like I did.

What resolved the problem for me was adding a entry in AndroidManifest.xml for my Data Provider, nested inside the tags, along with all of my entries. The only attributes I needed were:

  • android:name=".DataManagement.DbDataProvider"
  • android:authorities="com.example.myApplicationName.DataManagement.DbDataProvider"
  • android:exported="false"

(Make sure to change the values for the above attributes to match your project)

I cleaned, built, ran, and onCreate() methods for the data provider and open helper classes executed properly, and the database was created on first application launch!

Solution 7 - Java

I had the same problem.. the resolution for me was to add .db as extension of the database name

Solution 8 - Java

In my case, it was not being called because the database already existed! So, if possible, make sure to delete your app and install it back and only then check if it is being called or not.

Solution 9 - Java

I had the same problem where it seemed that the onCreate was not executed. I thought so because my logs were not displayed. Turned out that there was something wrong with the blank spaces in my SQL_create String.

@Override
public void onCreate(SQLiteDatabase db) {
    try {
        Log.d(LOG_TAG, "A table is created with this SQL-String: " + SQL_CREATE + " angelegt.");
        db.execSQL(SQL_CREATE);
    }
    catch (Exception ex) {
        Log.e(LOG_TAG, "Error when creating table: " + ex.getMessage());
    }
}

This is my corrected SQL-String:

enterpublic static final String SQL_CREATE =
        "CREATE TABLE " + TABLE_VOCAB_LIST +
                "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_GERMAN + " TEXT NOT NULL, " +
                COLUMN_SPANISH + " INTEGER NOT NULL, "+
                COLUMN_LEVEL + " INTEGER NOT NULL);)"; code here

I had forgotten one blank space and when I added it everything worked fine.

Solution 10 - Java

You can change AUTOINCREMENT to AUTO INCREMENT

Note SQLiteOpenHelper Called onCreate when the database is created for the first time. If you create table in onCreate method you can't create new SQLiteDatabase. You can see example

    @Override
    public void onCreate(SQLiteDatabase db) {
        String stringCreateTable = "CREATE TABLE "+"tblUser"+" ( " +
                "id TEXT PRIMARY KEY, " +
                "name TEXT )";
        db.execSQL(stringCreateTable);
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzonoView Question on Stackoverflow
Solution 1 - JavaKevin KingView Answer on Stackoverflow
Solution 2 - JavaJatin MalwalView Answer on Stackoverflow
Solution 3 - JavaTobias ReichView Answer on Stackoverflow
Solution 4 - JavaspleenView Answer on Stackoverflow
Solution 5 - JavaAnwarView Answer on Stackoverflow
Solution 6 - Javadanny_on_the_runView Answer on Stackoverflow
Solution 7 - JavaHelLViS69View Answer on Stackoverflow
Solution 8 - JavarscView Answer on Stackoverflow
Solution 9 - Java2blond2codeView Answer on Stackoverflow
Solution 10 - Javauser3313585View Answer on Stackoverflow