11

I am writing a database in my android app, but my tables aren't being created. I added break points at my onCreate method, and my getWriteableDatabase, and getWritableDatabase is called, but onCreate is not.

package com.fslade.app;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "applicationdata";
    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_TABLE = "peopleT";

    // Database creation sql statement
    private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " (_id integer primary key autoincrement, "
            + "company_name text not null, name text not null, city text not null, vertical text not null, title text not null, email text not null, bio text not null, photo text not null, status text not null);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    // Method is called during an upgrade of the database, e.g. if you increase
    // the database version
    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion,
            int newVersion) {
        Log.w(DatabaseHelper.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS todo");
        onCreate(database);
    }
}

And in my database helper I call getWriteableDatabse():

package com.fslade.app;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ContentStorageHelper {
    public static final String KEY_ID = "_id";
    public static final String KEY_COMPANY_NAME = "company_name";
    public static final String KEY_PERSON_NAME = "name";
    public static final String KEY_CITY = "city";
    public static final String KEY_VERTICAL = "vertical";
    public static final String KEY_TITLE = "title";
    public static final String KEY_EMAIL = "email";
    public static final String KEY_BIO = "bio";
    public static final String KEY_PHOTO = "photo";
    public static final String KEY_STATUS = "status";

    private static final String[] COLUMNS = { KEY_ID, KEY_COMPANY_NAME,
            KEY_PERSON_NAME, KEY_CITY, KEY_VERTICAL, KEY_TITLE, KEY_EMAIL,
            KEY_BIO, KEY_PHOTO, KEY_STATUS };

    private Context context;
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;

    public ContentStorageHelper(Context context) {
        this.context = context;
    }

    public ContentStorageHelper open() throws SQLException {
        dbHelper = new DatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
        // dbHelper.onCreate(database);
// I added this onCreate() to see if it helped, but when I ran it
// it said that the database had already been created
        return this;
    }

    public void close() {
        dbHelper.close();
    }

/**
 * Create a new person If the person is successfully created return the new
 * rowId for that person, otherwise return a -1 to indicate failure.
 */
public long createPerson(String company_name, String name, String city,
        String vertical, String title, String email, String bio,
        String photo, String status) {
    ContentValues initialValues = createContentValues(company_name, name,
            city, vertical, title, email, bio, photo, status);

    return database.insert(DatabaseHelper.DATABASE_TABLE, null,
            initialValues);
}

/**
 * Return a Cursor over the list of all people in the database
 * 
 * @return Cursor over all notes
 */
public Cursor fetchPeopleByVertical(String vertical) {
    String selection = KEY_VERTICAL+"="+vertical;
        Cursor result = database.query(DatabaseHelper.DATABASE_TABLE, COLUMNS,
                selection, null, null, null, null);
        return result;
    }

    private ContentValues createContentValues(String company_name, String name,
            String city, String vertical, String title, String email,
            String bio, String photo, String status) {
        ContentValues values = new ContentValues();
        values.put(KEY_COMPANY_NAME, company_name);
        values.put(KEY_PERSON_NAME, name);
        values.put(KEY_CITY, city);
        values.put(KEY_VERTICAL, vertical);
        values.put(KEY_TITLE, title);
        values.put(KEY_EMAIL, email);
        values.put(KEY_BIO, bio);
        values.put(KEY_PHOTO, photo);
        values.put(KEY_STATUS, status);
        System.out.print("test: " + status);
        return values;
    }
}
1

5 Answers 5

19

The creation only happens once (that's the whole sense of an database helper).

Did you check whether your database was created? It's located at /data/data/your.package.name/databases/dbname.

If you clear your application data in the android application settings, your onCreate should be called again...

4
  • This is exactly what the problem was. I had already run onCreate earlier in development, but with a malformed sql create command. How do I clear out the application settings in Eclipse?
    – Francesca
    Commented Sep 23, 2011 at 20:01
  • I don't understand why you want to do in eclipse since there's nothing changed because it's your code only. If you want to remove the existing application data from device go to Android Settings > Application > Manage Applications > Your App > Delete data (sorry if the names don't match, my menu is in german)
    – Knickedi
    Commented Sep 23, 2011 at 20:07
  • In case you do not want to remove all application data (if there are other databases that work fine that you do not want to delete for example) I recommend going in via the Android Debug Monitor and delete just the offending SQLite database file. This worked like a charm for me when I was in this position.
    – Godsmith
    Commented Jul 8, 2013 at 21:24
  • it would be better to use theContext.getDatabasePath(DB_NAME).toString() instead of the Hardcoding path
    – DeveloperX
    Commented Dec 28, 2013 at 12:46
11

It's a rather stupid implementation limitation. :-) Make sure the database name has a .db extension. onCreate() will not be called if it has no extension.

3
  • 1
    wow...thank you so much! This was driving me crazy!...Stupid indeed!
    – Mahm00d
    Commented Aug 2, 2014 at 12:04
  • 1
    Not even inside the Android Documentation. The example they have does not have it. developer.android.com/training/search/search.html
    – Neta
    Commented Jun 13, 2015 at 14:18
  • WOOOOOOOOOOW THX SO MUCH! this thing was making me crazy ! +1 dude you rulz Commented Jan 25, 2017 at 2:08
0

I had the same problem. I fund 2 solutions

  1. Restart the emulator and check 'Wipe user Data' My emulator is slow restarting so ...
  2. Change the Version Number of your database and it called 'OnCreate' again and gave me a curret version of my database. I lost the stored info (no big Deal)

Good Luck

0

I was having the same problem. I had forgotten a space in between two sql commands in my SQL_Create string and so the column I needed wasn't implemented correctly, but when I found and fixed the error in the String, it didn't fix the issue, because the App already registered that database as having that table. So onCreate was never called. For me, the simplest solution was to update the version number. This created a new db and table (correctly), and fixed the app.

0
0

SQLiteOpenHelper.onCreate() is called back after SQLiteOpenHelper.getWritableDatabase() (or after SQLiteOpenHelper.getReadableDatabase() ) only when the database does not exist in the application's persistent storage (ie. SD card). In other words, onCreate() is called only once, if the code successfully creates a database - which is stored in persistent storage. If the database exists in persistent storage, but you're changing its schema,

you use SQLiteOpenHelper.onUpgrade(), which is called back when you open a database by name but with a version number that wasn't used before. In which you drop the old schema objects, and then in which you can call SQLiteOpenHelper.onCreate() to create your new schema. And if you want to run code whenever the database is opened (code called back by SQLiteOpenHelper.get[Writable,Readable]Database() ), implement onOpen() . Then call a method that initializes your database (or code initialized against your database) that's called from each of SQLiteOpenHelper.onCreate() and SQLiteOpenHelper.onOpen().

For example, you might want to use a reference to the SQLiteDatabase , against which to call data management methods like SQLiteDatabase.execSQL() .

In each of

SQLiteOpenHelper.onCreate(SQLiteDatabase db)

and

SQLiteOpenHelper.onOpen(SQLiteDatabase db)

call something like

void initDB(SQLiteDatabase db)
{
    this.db = db;
}

There are other object lifecycle events that callback handlers in your code that you should handle, as Android multitasks your process. But at a minimum your database handling code has to handle SQLiteOpenHelper.onCreate() and SQLiteOpenHelper.onOpen().

Not the answer you're looking for? Browse other questions tagged or ask your own question.