更新sqlite数据库中的错误项目

时间:2019-06-15 11:33:13

标签: java android

我创建了一个带有值的SQLiteDataBase,在列表视图上显示了这些值,现在我试图通过单击一行并将新值输入到Alertdialouge中来更新列表视图中的值。 但是总是碰巧更新最后一行。

我尝试使用

int id = cursor.getInt(0);
String strSQL = "UPDATE exp SET expense=" + newExpense + " WHERE _id = "+ id;
db.execSQL(strSQL);

 ContentValues values = new ContentValues();
values.put("expense",newExpense);
 db.update("exp",values,"_id" +id,null);

但它们不起作用

这是我的代码

@Override
    protected void onResume() {
        super.onResume();

        list = findViewById(R.id.List);
        Cursor c = helper.getReadableDatabase().query("exp", null, null,null,null,null,null);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(
                this,
                R.layout.exp_row,
                c,
                new String[] {"date", "item", "expense"},
                new int[] {R.id.dateOutput, R.id.itemOutput, R.id.expenseOutput}, 0);

        list.setAdapter(adapter);


        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                cursor = (Cursor)parent.getItemAtPosition(position);

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("date:    " + cursor.getString(1) +
                        "\nitem:    " + cursor.getString(2) + "\namount:  " + cursor.getInt(0));
                final EditText editText = new EditText(MainActivity.this);
                builder.setView(editText);

                builder.setNegativeButton("update", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        db = openOrCreateDatabase("expense.db", MODE_PRIVATE, null);
                        String newExpense = editText.getText().toString();
                        if(!isNumeric(newExpense)){
                            Toast.makeText(MainActivity.this,"please enter a number",Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                        else{
                            int id = cursor.getInt(0);
                            String strSQL = "UPDATE exp SET expense=" + newExpense + " WHERE _id = "+ id;
                            db.execSQL(strSQL);
                            recreate();
                        }
                    }
                });

                builder.setNeutralButton("back", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });
    }

0 个答案:

没有答案