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

Viewed 64515

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();
        }
    }
10 Answers

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();

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");


}

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!

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.

Related