Ormlite database helper - onCreate() not called

2019-06-27 20:40发布

问题:

I am using ormlite.android.4.31.jar I have typical DatabaseHelper

public class DatabaseHelper  extends OrmLiteSqliteOpenHelper {

    private static final String DATABASE_NAME = "realestate.db";
    private static final int DATABASE_VERSION = 1;

    private Dao<TabKraj, Integer> krajDao;

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

    @Override
    public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, TabKraj.class);
            initData();
        } catch (Exception e) {
            Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVer, int newVer) {
        try {
            TableUtils.dropTable(connectionSource, TabKraj.class, true);
            onCreate(sqliteDatabase, connectionSource);
        } catch (SQLException e) {
            Log.e(DatabaseHelper.class.getName(), "Unable to upgrade database from version " + oldVer + " to new " + newVer, e);
        }
    }

    public Dao<TabKraj, Integer> getKrajDao() throws SQLException{
        if (krajDao == null) {
            krajDao = getDao(TabKraj.class);
        }
        return krajDao;
    }

    private void initData(){
        Log.d(Constants.DEBUG_TAG, "data initiating");

        TabKraj k1 = new TabKraj();
        TabKraj k2 = new TabKraj();

        k1.setNazov("Kosicky kraj");
        k1.setId(1);
        try {
            getKrajDao().create(k1);
        } catch (SQLException e) {
            Log.e(Constants.DEBUG_TAG, "Data initialing ERROR");
        }
    }
}

app is uninstalled, data cleared ... I am running app in debug mode from eclipse, constructor of DatabaseHleper is called but onCreate() is not called.

Where could the problem be?

回答1:

As @k-mera said:

Database file will be created only if you did some operations in Database like "insert".



回答2:

Although you say the data is cleared, I suspect that Android thinks it has not. To completely remove the data, I would remove the application and re-install it.

Since your onUpgrade calls onCreate you could also increase the DATABASE_VERSION value which will cause the data to be dropped and re-created.