我在 android studio 中有一個 crud 應用程式專案。我已經完成了插入、更新、洗掉和查看所有操作。我唯一遇到的錯誤是搜索功能。搜索代碼對我來說看起來不錯,所以如果你能幫我找出我的錯誤,那就太好了。謝謝!
該表是這樣創建的:
public void onCreate(SQLiteDatabase DB) {
DB.execSQL("create Table ProdDetails(id INTEGER primary key, name TEXT, description TEXT, price NUMERIC, quantity INTEGER)");
}
search 方法接受來自 EditText 的輸入,該輸入被轉換為 int:
public Cursor searchData (int id)
{
SQLiteDatabase DB = this.getWritableDatabase();
Cursor cursor = DB.rawQuery("Select * from ProdDetails where id = ?", new String[]{String.valueOf(id)});
return cursor;
}
主類:
public class RUDActivity extends AppCompatActivity {
EditText prodId, name, description, price, quantity;
Button update, delete, view, search;
DBHelper DB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
prodId = (EditText) findViewById(R.id.prodId);
name = (EditText) findViewById(R.id.name);
description = (EditText) findViewById(R.id.description);
price = (EditText) findViewById(R.id.price);
quantity = (EditText) findViewById(R.id.quantity);
search = findViewById(R.id.btnSearch);
DB = new DBHelper(this);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int prodTXT = Integer.parseInt(prodId.getText().toString());
Cursor res = DB.searchData(prodTXT);
if(res.getCount()==0){
Toast.makeText(RUDActivity.this, "Product ID Not Found", Toast.LENGTH_SHORT).show();
return;
}
// app crash/restart after this line, am I doing this wrong?
prodId.setText("Product ID: " res.getString(0));
name.setText("Name: " res.getString(1));
description.setText("Description: " res.getString(2));
price.setText("Price: " res.getString(3));
quantity.setText("Quantity: " res.getString(4));
}
});
}
}
當我搜索不存在的 prodId 時,它會顯示 toast 訊息“未找到產品 ID”,并且應用程式不會崩潰/重新啟動。但是,如果我搜索確實存在的 prodId,應用程式將崩潰。
uj5u.com熱心網友回復:
moveToFirst()在檢索列的值之前,您缺少對該方法的呼叫:
res.moveToFirst();
prodId.setText("Product ID: " res.getString(0));
................................................
因為游標的索引最初位于結果的第一行之前。
或者,不要使用getCount()檢查游標是否回傳任何行,而是使用moveToFirst():
if (!res.moveToFirst()) {
Toast.makeText(RUDActivity.this, "Product ID Not Found", Toast.LENGTH_SHORT).show();
} else {
prodId.setText("Product ID: " res.getString(0));
................................................
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447988.html
標籤:爪哇 安卓 sqlite 安卓-sqlite 安卓光标
上一篇:如何從意圖回傳ArrayList
