我想搜索数据库中存在的特定关键字并将其展示出来。
这是我的搜索类代码:
String s = kw.getText().toString();
sqlhandler show = new sqlhandler(this);
show.open();
String rname = show.getName(s);
show.close();
tv.setText(rname);
这是我的数据库类:
public String getName(String kw) {
String[] columns = new String[] {NAME, APRICE, DPRICE, VENDOR, KEYWORD };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, "DPRICE like " + "'%"+ kw+"%'", null, null, null, null);
String sresult = "";
int iname = c.getColumnIndex(NAME);
int iap = c.getColumnIndex(APRICE);
int idp = c.getColumnIndex(DPRICE);
int ivendor = c.getColumnIndex(VENDOR);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
sresult = sresult + c.getString(iname)+ " "+c.getString(iap)
+ " " + c.getString(idp) + " " + c.getString(ivendor)
+ "\n";
}
return sresult;
}
这里有什么问题?每次运行它时我都会一直强行关闭。
答案 0 :(得分:0)
由于你还没有发布你的LogCat,我只能猜测,但你的WHERE子句看起来很可疑:
"DPRICE like ..."
我认为DPRICE
是一个变量,而不是实际的列名:
DPRICE + " like ..."
我也有一些建议:
selectionArgs
参数来阻止SQL injection attacks。所有在一起:
public String getName(String kw) {
String[] columns = new String[] {NAME, APRICE, DPRICE, VENDOR};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, DPRICE + " like ?", new String[] {"'%" + kw + "%'"}, null, null, null, null);
int iname = c.getColumnIndex(NAME);
int iap = c.getColumnIndex(APRICE);
int idp = c.getColumnIndex(DPRICE);
int ivendor = c.getColumnIndex(VENDOR);
// moveToNext() returns true when there is more data to read
// or false when the cursor isAfterLast()
StringBuilder builder = new StringBuilder();
while (c.moveToNext()) {
builder.append(c.getString(iname).append(" ")
.append(c.getString(iap).append(" ")
.append(c.getString(idp).append(" ")
.append(c.getString(ivendor).append("\n");
}
return builder.toString();
}
以下是关于如何使用带有自定义布局的ListView来显示数据库信息的tutorial。