引自免费微信小程序:皆我百晓生
在分析这段代码时,我们需要检查以下几个方面来找出为何会显示"No activity found with that name"。
- 数据库连接:确保已成功打开并获取到可读数据库。
- SQL 查询语句:确认查询条件是否正确匹配了数据库中的数据。
- 查询结果处理:检查当查询结果为空时的逻辑是否正确。
首先,确保 myHelper
是一个正确的 SQLiteOpenHelper 类的实例,并且已经成功创建了一个名为 "information" 的表。接下来,我们对代码进行一些优化,简化错误处理并改进逻辑:
else if (id == R.id.bt_query) {
name = et_name.getText().toString().trim();
if (name.isEmpty()){
tv_show.setText("Error: Activity name is empty.");
return;
}
db = myHelper.getReadableDatabase();
Cursor cursor = db.query(
"information",
new String[]{"name", "content"},
"name = ?",
new String[]{name},
null,
null,
null
);
if (cursor != null) {
int count = cursor.getCount();
if (count > 0) {
cursor.moveToFirst();
String content = cursor.getString(cursor.getColumnIndex("content"));
tv_show.setText("Name: " + name + "\nContent: " + content);
} else {
tv_show.setText("No activity found with that name.");
}
cursor.close(); // 关闭游标
}
// 不需要额外判断数据库是否打开,因为 close() 方法会自动关闭未关闭的数据库连接
db.close();
}
在这个版本中:
- 我们将要查询的列名明确指定为 "name" 和 "content",这样可以避免在获取 "content" 字段时可能出现的问题。
- 使用
getCount()
检查查询结果的数量,如果大于 0,则获取并显示数据。否则,显示 "No activity found with that name."。 - 将
finally
块中的关闭操作移到 if (cursor != null)
判断内,确保无论是否发生异常,都会正确关闭游标。
如果你仍然遇到问题,那么可能是数据库中的数据不匹配输入的 name
,或者 "information" 表不存在、没有被正确初始化,或者 myHelper
对象有问题。建议你检查这些方面,或者提供更多的上下文信息以便进一步排查。