我目前在使用我的应用程序时遇到了一个非常恼人的问题:目标是根据用户点击的按钮从列表视图中读取数据库中的不同信息。不幸的是,我的应用程序总是崩溃,我无法在stackoverflow上找到类似问题中的工作解决方案(尝试更改数据库版本,添加一些关于游标的行等)。
以下是我的代码的相关部分:
:一种。 DatabaseAdapter类:
public class DatabaseAdapter {
public static final String DATABASE_TABLE = "Restaurants";
public static final String COL_CAT1 = "cat1";
public static final String KEY_ROWID = "_id";
public static final String COL_CAT2 = "cat2";
public static final String COL_NAME = "name";
public static final String COL_COMMENTS = "comments";
private Context myContext;
private SQLiteDatabase myDatabase;
private DatabaseHelper dbHelper;
private Cursor c;
// Constructor
public DatabaseAdapter(Context context) {
this.myContext = context;
}
public DatabaseAdapter open() throws SQLException {
dbHelper = new DatabaseHelper(myContext);
// TODO: or maybe?
// database = dbHelper.getWritableDatabase();
try {
dbHelper.createDatabase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myDatabase = dbHelper.getReadableDatabase();
return this;
}
public void close() {
if (c != null) {
c.close();
}
try {
dbHelper.close();
myDatabase.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Cursor findNameInTable(int myVariable) {
c = myDatabase
.query(DATABASE_TABLE, new String[] { COL_NAME , COL_COMMENTS },
COL_CAT1+"=?",
new String[] { Integer.toString(myVariable) }, null,
null, null);
return c;
}
}
B中。 ResultListViewActivity(结果应该通过ListView中的此活动显示):
public class ResultListViewActivity extends Activity {
private SimpleCursorAdapter cursorAdapter;
private DatabaseAdapter dbHelper;
ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_list_view);
dbHelper = new DatabaseAdapter(this); // open() method is in DatabaseAdapter
dbHelper.open();
displayListView();
}
private void displayListView() {
Bundle bundle = getIntent().getExtras();
int myVariable = bundle.getInt("myVariable");
Cursor c = dbHelper.findNameInTable(myVariable);
// the desired columns to be bound
String[] columns = new String[] { DatabaseAdapter.COL_NAME,
DatabaseAdapter.COL_COMMENTS, };
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.name, R.id.comments, };
// create the adapter using the cursor pointing to the desired data
// as well as the layout information
cursorAdapter = new SimpleCursorAdapter(this, R.layout.poi_info, c,
columns, to, 0);
ListView listView = (ListView) findViewById(R.id.listview);
// Assign adapter to ListView
listView.setAdapter(cursorAdapter);
}
我的数据库图片:正如您所看到的,实际上有一个_id列:
最后,在以下情况下我的logcat图片:
如果您想查看我的代码的其他部分,请告诉我。提前感谢您的任何帮助!
答案 0 :(得分:1)
每个ListView在其选择查询中都需要一个_id列。您必须在列表查询中包含_id列
将您的查询更改为:
c = myDatabase
.query(DATABASE_TABLE, new String[] { KEY_ROWID,COL_NAME , COL_COMMENTS },
COL_CAT1+"=?",
new String[] { Integer.toString(myVariable) }, null,
null, null);