我尝试了所有的事情:直到使用数据库查询获取id但错误。
数据库名称:测验
表名:字典
数据库列:_id,word,含义
问题:如何获取行的_id-column值,其中word-column匹配Abiotic
或字符串m
传递给函数dbBackend.getQuizByWord(m);
public int getQuizByword(String m)
{
int originalPosition;
Log.d("MYINT", "Here: "+m);
String query="select * from dictionary where word ='"+m+"'";
Cursor cursor=this.getDbConnection().rawQuery(query, null);
if(cursor.moveToFirst()){
do {
originalPosition = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
}while(cursor.moveToNext());
}
cursor.close();
return originalPosition;
}
我从哪里传递这个字符串:
String m;
filterText=(EditText)findViewById(R.id.editText1);
filterText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
m=s.toString();
MainActivity.this.listAdapter.getFilter().filter(s);
}
@Override
public void afterTextChanged(Editable s) {
}
和项目监听器
itemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// make Toast when click
Toast.makeText(getApplicationContext(), "Position "+position, Toast.LENGTH_LONG).show();
//long data=parent.getSelectedItemId
//Log.d("MYINT", "First------------- "+data);
//int a=dbBackend.getQuizByword(m);
DbBackend dbBackend1 = new DbBackend(MainActivity.this);
Log.d("MYINT", "Here: "+dbBackend1.getQuizByword(m));
int a=position;
Log.d("MYINT", "First------------- "+a);
Toast.makeText(getApplicationContext(), "New Position "+a, Toast.LENGTH_LONG).show();
Intent i = new Intent(MainActivity.this, MeaningActivity.class);
//i.putExtra("DICTIONARY_ID", position);
i.putExtra("DICTIONARY_ID", a);
startActivity(i);
}
答案 0 :(得分:1)
1)SQL注入不好。修复您的查询。
2)你可能不需要循环。
3)尝试捕捉抛出的异常
public long getQuizByword(String m)
String query="select * from dictionary where word =?";
Cursor cursor=this.getDbConnection().rawQuery(query, new String[] { m });
long id = -1;
try {
if(cursor.moveToFirst()){
id = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor!=null) cursor.close();
}
return id;
}
如果返回-1,则找不到任何内容,或者出现错误
我不确定getDbConnection()
返回了什么,但您应该将此方法移到SQLiteOpenHelper中,并将其替换为getReadableDatabase()
编辑
关于您使用ArrayAdapter和过滤器所做的任何事情,您可能更愿意使用CursorAdapter
,并将带有过滤数据的其他Cursor
加载到ListView
}。不要与指标和arraylists来回跳跃。