首页 > 解决方案 > 如何在 SQLite 中搜索显示错误索引以更新和删除的值?

问题描述

搜索功能

mSearchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.d("data", charSequence.toString());
            }

            @Override
            public void onTextChanged(CharSequence charSequence2, int i, int i1, int i2) {
                String select = "SELECT * FROM RECORD WHERE name LIKE '"+charSequence2+"%'";
                Cursor cursor = mSQLiteHelper.getData(select);

                mList.clear();
                while(cursor.moveToNext()) {
                    int id = cursor.getInt(0);
                    String name = cursor.getString(1);
                    String phone = cursor.getString(2);
                    mList.add(new Model(id,name,phone));
                }

                mAdapter.notifyDataSetChanged();


            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

更新:这是 LongClickListener,我点击以更新和删除我插入的数据

 mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {

                //Alert dialog to display options of update and delete

                final CharSequence [] items = {"Update","Delete","Call"};

                AlertDialog.Builder dialog = new AlertDialog.Builder(RecordListActivity.this);

                dialog.setTitle("Choose an Action");

                dialog.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if(i == 0){
                            //update
                            Cursor c = mSQLiteHelper.getData("SELECT id FROM RECORD");

                            ArrayList<Integer> arrID = new ArrayList<Integer>();
                            while(c.moveToNext() ){
                                arrID.add(c.getInt(0));
                            }
                            //Show update Dialog
                            showDialogUpdate(RecordListActivity.this,arrID.get(position));
                        }
                        if(i==1){
                                //delete
                            Cursor c = mSQLiteHelper.getData("SELECT id FROM RECORD");
                            ArrayList<Integer> arrID = new ArrayList<Integer>();

                            while(c.moveToNext()){
                                arrID.add(c.getInt(0));
                            }
                            showDialogDelete(arrID.get(position));
                        }

                                //Call try
                        if(i==2){

                            TextView tvPhone = view.findViewById(R.id.textphone);
                            String phone = tvPhone.getText().toString();
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse("tel:" + phone));
                            getBaseContext().startActivity(intent);
                        }

                    }
                });
                dialog.show();
                return true;
            }
        });

型号:这是型号

public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

数据库

public void updateData(String name, String phone, int id){
        SQLiteDatabase database = this.getWritableDatabase();

        //Query to update record

        String sql = "UPDATE RECORD SET name=? , phone=? WHERE id=?";

        SQLiteStatement statement = database.compileStatement(sql);



        statement.bindString(1,name);
        statement.bindString(2,phone);
        statement.bindDouble(3,(double)id);


        statement.execute();
        database.close();

    }

    //Delete Data

    public void deleteData(int id){

        SQLiteDatabase database = this.getWritableDatabase();

        //query to delete record using id
        String sql = "DELETE FROM RECORD WHERE id=?";

        SQLiteStatement statement = database.compileStatement(sql);
        statement.clearBindings();
        statement.bindDouble(1,(double)id);

        statement.execute();
        database.close();

    }

    //Getting Data

    public Cursor getData(String sql){

        SQLiteDatabase database = this.getReadableDatabase();
            return database.rawQuery(sql,null);

    }

对话

//DeleteDialog
    private void showDialogDelete(final int idRecord) {

        AlertDialog.Builder dialogDelete =new AlertDialog.Builder(RecordListActivity.this);
        dialogDelete.setTitle("Warning!!");
        dialogDelete.setMessage("Are you sure you want to delete this?");
        dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener(){


            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                try{
                    mSQLiteHelper.deleteData(idRecord);
                    Toast.makeText(getApplicationContext(), "Delete Successfully", Toast.LENGTH_SHORT).show();
                }catch (Exception error){
                    Log.e("Delete error",error.getMessage());
                }


            }
        });

        dialogDelete.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                dialogInterface.dismiss();

            }
        });

        dialogDelete.show();
    }


                //UpdateDialog
    private void showDialogUpdate(Activity activity, int position){

        Dialog dialog = new Dialog(activity);
        dialog.setContentView(R.layout.update_dialog);
        dialog.setTitle("Update");

       final EditText updateNameId = dialog.findViewById(R.id.updateNameId);
       final EditText updatePhoneId = dialog.findViewById(R.id.updatePhoneId);
       final Button updatebuttonId = dialog.findViewById(R.id.updatebuttonId);

        //get Data Row Clicked  from SQLite

        Cursor cursor  = mSQLiteHelper.getData("SELECT * FROM RECORD WHERE id="+position);
        mList.clear();
        while(cursor.moveToNext()){
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            updateNameId.setText(name);
            String phone = cursor.getString(2);
            updatePhoneId.setText(phone);
            mList.add(new Model(id,name,phone));

        }


        //set width of dialog
        int width = (int)(activity.getResources().getDisplayMetrics().widthPixels * 0.95);
        //set height of dialog
        int height = (int)(activity.getResources().getDisplayMetrics().heightPixels * 0.7);
        dialog.getWindow().setLayout(width,height);
        dialog.show();



        updatebuttonId.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {

                try{

                    mSQLiteHelper.updateData(
                            updateNameId.getText().toString().trim(),
                            updatePhoneId.getText().toString().trim(),
                            position);

                    dialog.dismiss();
                    Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
                }catch(Exception error){
                    Log.e("Update error",error.getMessage());
                }
                updateRecorderList();

            }
        });

    }

    private void updateRecorderList() {

        //get all data from SQLite

        Cursor cursor = mSQLiteHelper.getData("SELECT * FROM RECORD");
        mList.clear();
        while(cursor.moveToNext()){
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            String phone = cursor.getString(2);

            mList.add(new Model(id,name,phone));
        }
        mAdapter.notifyDataSetChanged();

    }

当我在搜索栏中搜索任何数据时,它会显示搜索到的数据,但是当我单击更新它时,它会显示要更新的第一行数据,并且当我单击删除时,它会显示要删除的第一行,其中是我的错误逻辑你能启发我吗?任何人

标签: android-studioandroid-sqlitecrud

解决方案


您错误地使用了 ID,因为您使用的位置总是在变化并且无法与数据相关联。

您不必去数据库获取 ID,因为您已经拥有它:

if (i == 0) {
   //update
   int contactId = mList.get(position).getId();
   showDialogUpdate(RecordListActivity.this, contactId);
}
if (i == 1) {
   //delete
   int contactId = mList.get(position).getId();
   showDialogDelete(contactId);
}

推荐阅读