使用Android中的SQLite建立一个数据库BookStore,加了一张Book表,然后我要增加一个Category表,按照《第一行代码》中的6.4.2所示代码写完后,点击App后直接闪退。(我用的是Andro Studio3.1版本,使用真机开发,系统Androi8.1)。代码如下
主活动代码:
public class MainActivity extends AppCompatActivity {
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper=new MyDatabaseHelper(this,"BookStore.db",null,2);
Button createDatabase=(Button)findViewById(R.id.create_database);
createDatabase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dbHelper.getWritableDatabase();
}
});
}
}
定义一个数据库类MyDatabaseHelper继承SQLiteOpenHelper
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK="create table Book("
+"id integer primary key autoincrement,"
+"author text"
+"price real"
+"pages integer"
+"name text)";
public static final String CREATE_CATEGORY="create table Category("
+"id integer primary key autoincrement"
+"category_name text"
+"category_code integer)";
private Context mContext;
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){
super(context,name,factory,version);
mContext=context;
}
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext,"Create succeeded",Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
}
}