在代碼中找不到錯誤。我相信,ID可能存在一些問題。也許查詢是錯誤的。有點新來這個東西。無法更新數據庫中的項目[sqlite]
MyDBHelper
public void onClick(DialogInterface dialog, int whichButton) {
String EditTextValue = edittext.getText().toString();
Task t = new Task(EditTextValue);
dbHandler.updateTask(t);
if (dbHandler.updateTask(t) == true){
Toast.makeText(MainActivity.this, "IR", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this, "naah", Toast.LENGTH_LONG).show();
}
displayTaskList();
}
更新功能:
public boolean updateTask(Task t){
boolean result = false;
String q = "SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = " + t.getID();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery(q, null);
if (c.moveToFirst())
{
String q2 = "UPDATE " + TABLE_NAME + " SET " + COLUMN_TASK + " = "
+ t.getTASK() + " WHERE " + COLUMN_ID + " = " + t.getID();
db.execSQL(q2);
result = true;
}
db.close();
return result;
}
任務等級:
public class Task {
private int _id;
private String _task;
public Task() {}
public Task(String task){
this._task = task;
}
public Task (int id, String task){
this._id = id;
this._task = task;
}
// SETS&GETS
public void setID(int id) {
this._id = id;
}
public int getID() {
return this._id;
}
public void setTASK(String task){
this._task = task;
}
public String getTASK(){
return this._task;
}
}
Mainactivity:
// To detect which list item is selected (by ID)
private long _id;
public void setID(long id) { this._id = id; }
public long getID() { return this._id; }
// Attaches a long click listener to the listview
private void setupListViewListener() {
lvTasks.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
item1.setVisible(true); item2.setVisible(true); item3.setVisible(true); // Showing all buttons
setID(id); //Catches the selected items ID
return true;
}
});
}
問題可能是它混合了ID的?例如在Mainactivity中,我得到的ID是選中的任務(onlongclick),但是在Task/MyDBHelper中,類ID是新創建的任務 - 即使它們沒有連接(?)。任何幫助將是一個偉大的。
你的錯誤是什麼?順便說一下,您當前的查詢使用原始級聯構建'WHERE'子句,從而使查詢容易受到SQL注入的影響。你應該參數化查詢。 –
@TimBiegeleisen你能給我一個提示嗎?問題是 - 沒有任何反應。我需要編輯任務,但它保持不變,問題是,更新函數返回false(這意味着,某些失敗,而不是更新並返回true) – JasonM