SQLiteOpenHelper 未能调用创建?

2022-09-01 10:11:29

我正在尝试使用在Android手机上创建本地数据库。sqlite

我有一个帮助器类,如下所示,用于创建数据库并提供“帮助”。

我想在代码的主要部分创建一个此类的对象,它也在那里创建数据库和表。

问题:

每当我创建类的对象时,它似乎都没有在帮助器中调用该方法。我认为这是应该发生的。我认为这基本上是该类的构造函数(我相信我错了)onCreateonCreate

  • 那么,为什么它不调用该方法呢?onCreate
  • 或者我如何让它创建数据库和表,我正在创建类的对象?
  • 如果这不是一个好方法,那么更好的方法是什么?

public class SmartDBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "smart_lite_db.db";
    private static final int DATABASE_VERSION = 2;
    private static final String NOTIFY_TABLE_NAME = "user_notify_data";
    private static final String HR_TABLE_NAME = "user_hr_data";
    private static final String NOTIFY_TABLE_CREATE = 
        "CREATE TABLE " + NOTIFY_TABLE_NAME + 
        " (counter INTEGER PRIMARY KEY, " + 
        "userresponse INTEGER, " + 
        "notifytime INTEGER);";
    private static final String DATA_TABLE_CREATE = 
        "CREATE TABLE " + HR_TABLE_NAME +
        " (counter INTEGER PRIMARY KEY, " +
        "hr INTEGER, " +
        "act INTEGER, " +
        "timestamp INTEGER);";      

    public SmartDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        Log.v("smartdbhelper", "before creation");
        db.execSQL(NOTIFY_TABLE_CREATE);
        Log.v("smartdbhelper", "middle creation");
        db.execSQL(DATA_TABLE_CREATE);
        Log.v("smartdbhelper", "after creation");
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

public class SmartApp extends Activity implements OnSharedPreferenceChangeListener {
   private SmartDBHelper dBHelper;
   public void onCreate(Bundle savedInstanceState) {
      //where i am wanting to create the database and tables
      dBHelper = new SmartDBHelper(getContext());
   }
}

答案 1

不是数据库类的构造函数。仅当您尝试打开不存在的数据库时,才会调用它。要打开/创建数据库,您需要添加对以下方法之一的调用:onCreate

public class SmartApp extends Activity implements OnSharedPreferenceChangeListener {
   private SmartDBHelper dBHelper;
   public void onCreate(Bundle savedInstanceState) {
      //where i am wanting to create the database and tables
      dBHelper = new SmartDBHelper(getContext());
      // open to read and write
      dBHelper.getWritableDatabase();
      // or to read only
      // dBHelper.getReadableDatabase();
   }
}

它有点大,但这是我的数据库适配器,你可以看看:http://saintfeintcity.org/projects/sfc/repository/entry/trunk/src/org/saintfeintcity/database/GameDbAdapter.java


答案 2

您必须致电 或 .getWritableDatabase()getReadableDatabase()


推荐