开发者

onCreate() is not called by getWritableDatabase()

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
    p开发者_C百科ublic 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;
    }
}


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...


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.


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜