我在一个活动中有一个数据库,我想在另一个活动中打开,同样在此活动中我希望创建一个列表视图:
我的代码如下
messagedb=context.openOrCreateDatabase("message",0, null);
messagedb.execSQL(
"CREATE TABLE IF NOT EXISTS tab( " +
" _id INTEGER PRIMARY KEY AUTOINCREMENT ," +
" nickname varchar,sender INT(13),body varchar)");
messagedb.execSQL("INSERT INTO tab VALUES('"+nickname+"','"+sender+"','"+sb+"')");
messagedb.close();
mydb.close();
当我插入值时,它表示您的数据库有4列,但您已经输入3列值.............我怎样才能自动从表中添加_id ...... / p>
我的listView活动如下
public class ListView extends ListActivity {
SQLiteDatabase messagedb;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.my_list);
messagedb=ListView.this.openOrCreateDatabase("message",0, null);
messagedb.execSQL(
"CREATE TABLE IF NOT EXISTS tab(" +
" _id INTEGER PRIMARY KEY AUTOINCREMENT," +
" nickname varchar,sender INT(13),body varchar)");
Cursor cur = messagedb.rawQuery("select _id, nickname, body from tab", null);
String[] from = new String[] { "nickname", "body" };
int[] to = new int[] { R.id.sender_entry, R.id.body_entry};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.my_list_entry, cur, from, to);
this.setListAdapter(mAdapter);
cur.close();
messagedb.close();
}
protected void onListItemClick(android.widget.ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String nickName = ((TextView) v.findViewById(R.id.sender_entry)).getText().toString();
String body = ((TextView) v.findViewById(R.id.body_entry)).getText().toString();
Intent intent = new Intent(ListView.this,MessageViewPage.class);
Bundle b = new Bundle();
b.putString("nick", nickName);
b.putString("body", body);
intent.putExtras(b);
startActivity(intent);
finish();
}
}
答案 0 :(得分:0)
此:
" _id INTEGER PRIMARY KEY ,"
如果您希望数据库自动为您处理主键,则应该是这样:
" _id INTEGER PRIMARY KEY AUTOINCREMENT,"
否则,您需要在插入时手动添加“_id”。
到目前为止,使用autoincrement
是更容易的解决方案。
然后,如果您想要记录中的所有数据,只需执行以下操作:
Cursor cur = messagedb.rawQuery("select * from tab", null);
如果您只想要特定位,只需要调用它们(但请记住,当使用大多数Android小部件时,必须在光标中有_id
,即使您没有显示它)。因此,如果您只想要昵称,您的查询可能如下所示:
Cursor cur = messagedb.rawQuery("select _id, nickname from tab", null);
您也应该只有代码在一个地方创建表。在两个地方拥有它是不好的。看起来现在发生的事情是你改变了一个而不是另一个,你没有改变的那个是先被调用,创建表没有你的改变然后当第二个被调用时,表alre4ady存在所以它没有做出改变。至少您需要将两个表创建语句更改为相同。更好的解决方案是摆脱其中一个。
您还应该使用ContentValues来执行插入...
ContentValues initialValues = new ContentValues();
initialValues.put("nickname", nickname);
initialValues.put("sender", sender);
initialValues.put("body", sb);
messagedb.insertWithOnConflict(tab, null, initialValues, SQLiteDatabase.CONFLICT_IGNORE);
哦,如果在列表仍处于活动状态时关闭光标,则会出现问题。在获得光标后立即取消cur.close()
调用,而不是所有startManagingCursor(cur);
。这样系统就会为你管理光标。
答案 1 :(得分:0)
尝试将您的ID设置为自动增量:
ID整数主键自动增量
我还建议使用ContentValues使用方法sqlDB.insert(table,nullColumnHack,values)将值插入到DB中。它更容易,更不容易出错。