我正在关注android SQLiteDatabase for android的教程,在这里按下计数按钮它对我来说不起作用。我添加了一些尝试方法,看看发生了什么,但它仍然无法正常工作。在这里我的代码:
public class MyDatabasaDemo extends Activity {
private static final String DATABASE_NAME = "JADB.db";
private static final String DATABASE_TABLE = "myTable";
private static final String DATABASE_CREATE = "create table"+ DATABASE_TABLE;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button butCreate = (Button) findViewById(R.id.myButCreate);
Button butAdd = (Button) findViewById(R.id.myButAdd);
Button butCount = (Button) findViewById(R.id.myButCount);
Button butShow = (Button) findViewById(R.id.myButShow);
butCreate.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
SQLiteDatabase myDB;
try{
myDB = openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
myDB.execSQL(DATABASE_CREATE);
myDB.close();
Toast.makeText(getApplicationContext(), "Table Creat", Toast.LENGTH_SHORT).show();
}catch(SQLException e){
Toast.makeText(getApplicationContext(), "SQLException", Toast.LENGTH_SHORT);
}
}
});
butAdd.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
SQLiteDatabase myDB;
myDB = openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
ContentValues newRow = new ContentValues();
newRow.put("col1", "ok");
myDB.insert(DATABASE_TABLE, null, newRow);
myDB.close();
Toast.makeText(getApplicationContext(), "row added", Toast.LENGTH_SHORT).show();
}
});
butCount.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
SQLiteDatabase myDB;
myDB = openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
String[] resultColumns = new String[]{"_id","col1"};
Cursor allRows = myDB.query(DATABASE_TABLE, resultColumns, null, null, null, null, null, null);
myDB.close();
Integer c = allRows.getCount();
Toast.makeText(getApplicationContext(), "count: "+c.toString(), Toast.LENGTH_SHORT).show();
}
});
}
数据库是创建的,但是frist按钮内的toast消息不起作用,所以我想知道它是否没有关闭。
三江源
答案 0 :(得分:1)
您正在尝试创建没有列的表,然后插入记录。您应该更改数据库创建sql:
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "col1";
private static final String DATABASE_CREATE = "create table "+ DATABASE_TABLE +" ("+
COLUMN_ID + " integer primary key autoincrement, " +
COLUMN_NAME +" text not null"
+");";