即使在构造函数中调用getWritableDatabase()之后也没有调用OnCreate()
package com.example.user.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DB_Test dbTest = new DB_Test(getApplicationContext());
}
}
尝试在构造函数中调用getWritableDatabase()但是没有工作
package com.example.user.myapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by user on 11-Mar-16.
*/
public class DB_Test extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "productDB.db";
public DB_Test(Context context) {
super(context, DATABASE_NAME, null,DATABASE_VERSION);
Log.v("MainActivity", "Constructor Working");
getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.v("MainActivity","onCreate Working");
String CREATE_PRODUCTS_TABLE = "CREATE TABLE products(column_id INTEGER PRIMARY KEY,column_product_name TEXT,column_quantity INTEGER)";
db.execSQL(CREATE_PRODUCTS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.v("MainActivity", "OnUpgrade Working");
db.execSQL("DROP TABLE IF EXISTS products");
onCreate(db);
}
}
答案 0 :(得分:2)
如果您的数据库已创建,则不会调用它。如果更改版本号,则将调用onUpdate。