为什么sqlite的删除方法无法正常工作?

时间:2017-06-21 14:59:43

标签: android sqlite android-sqlite

我的数据库处理程序有一个删除方法,用于删除数据库中的单行。但它没有正常工作。我的数据通过cardview显示在RecyclerView上。当我点击删除按钮时,它将被删除。但当我按意图去另一个活动并回到回收商的集装箱活动时,删除的数据又回来了!这意味着没有删除单行。

我的RecyclerViewAdapter:

    package ir.qadamgahi.ramzdar;

    import android.content.ClipData;
    import android.content.ClipboardManager;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.os.Build;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.widget.RecyclerView;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.util.List;
    import java.util.Objects;

    import ir.qadamgahi.ramzdar.database.model.DatabaseHandler;
    import ir.qadamgahi.ramzdar.database.model.Ramz;

    /**
     * Created by SMQ on 6/17/2017.
     Qadamgahi.ir
     @qadamgahiii instagram
     */

    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

        private List<Ramz> ramzList;
        private ClipboardManager myClipboard;
        private ClipData myClip;
        private AlertDialog.Builder removeBuilder;
        private AlertDialog removeAlert;
        private DatabaseHandler dbHelper;
        Ramz ramz = new Ramz();
        Ramz ramzObj = new Ramz();

        public class MyViewHolder extends RecyclerView.ViewHolder {
            public TextView ramzTxtView, goalTxtView, usernameTxtView, usernameTxt;
            public LinearLayout ramzUserLayout;
            private ImageView copyImageBtn, deleteImgBtn, editImageBtn;


            public MyViewHolder(View view) {
                super(view);
                ramzTxtView = (TextView) view.findViewById(R.id.ramzTxtView);
                goalTxtView = (TextView) view.findViewById(R.id.goalTxtView);
                usernameTxtView = (TextView) view.findViewById(R.id.usernameTxtView);

                copyImageBtn = (ImageView) view.findViewById(R.id.copyImgbutton);
                deleteImgBtn = (ImageView) view.findViewById(R.id.deleteImgBtn);
                //editImageBtn = (ImageView) view.findViewById(R.id.editImageBtn);


                usernameTxt = (TextView) view.findViewById(R.id.passUser);
                ramzUserLayout = (LinearLayout) view.findViewById(R.id.pass_user_l);

            }
        }
        public RecyclerViewAdapter(List<Ramz> ramzList) {
            this.ramzList = ramzList;
        }
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.card_row, parent, false);

            return new MyViewHolder(itemView);

        }

        @Override
        public void onBindViewHolder(final MyViewHolder holder, final int position) {
            ramz = ramzList.get(position);
            holder.ramzTxtView.setText(ramz.get_ramz());
            holder.goalTxtView.setText(ramz.get_goal());
            holder.usernameTxtView.setText(ramz.get_username());


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if (Objects.equals(ramz.get_username(), "")) {
                    holder.usernameTxtView.setVisibility(View.INVISIBLE);
                    holder.ramzUserLayout.setVisibility(View.INVISIBLE);
                    holder.usernameTxt.setVisibility(View.INVISIBLE);
                }
            }

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

                    myClipboard = (ClipboardManager) view.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                    myClip = ClipData.newPlainText("RAMZ", holder.ramzTxtView.getText().toString());
                    myClipboard.setPrimaryClip(myClip);
                    Toast.makeText(view.getContext(), R.string.makeSafe , Toast.LENGTH_LONG ).show();
                    Log.i("COPY", myClip.toString());
                }
            });



            holder.deleteImgBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View view) {

                    //Alert dialog///////////////////////////////////////////////
                    removeBuilder = new AlertDialog.Builder(view.getContext());
                    removeBuilder.setMessage(R.string.areusure);
                    removeBuilder.setCancelable(true);
                    removeBuilder.setPositiveButton(
                            R.string.are,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dbHelper = new DatabaseHandler(view.getContext());
                                    dbHelper.deleteRamz(ramz.get_id());
                                    ramzList.remove(position);
                                    notifyItemRemoved(position);
                                    notifyItemRangeChanged(position,getItemCount());
                                    Log.i("item deleted", String.valueOf(ramzList.size()));

                                }
                            }).setNegativeButton(
                            R.string.bikh,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();

                                }
                            });
                    removeAlert = removeBuilder.create();
                    ///////////////////////////////////////////////////////
                    removeAlert.show();


                }
            });

        }




        @Override
        public int getItemCount() {
            return ramzList.size();
        }

    }

我的DatabaseHandler:

    package ir.qadamgahi.ramzdar.database.model;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by SMQ on 6/17/2017.
 */

public class DatabaseHandler extends SQLiteOpenHelper{

    // All Static variables
    private static final int DATABASE_VERSION = 4;
    private static final String DATABASE_NAME = "ramzDB";
    private static final String TABLE_RAMZ = "ramz";
    private static final String KEY_ID = "id";
    private static final String KEY_RAMZ = "ramz";
    private static final String KEY_GOAL = "goal";
    private static final String KEY_USERNAME= "username";




    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }



    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_RAMZ + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_RAMZ + " TEXT,"
                + KEY_GOAL + " TEXT," + KEY_USERNAME + " TEXT" + ")";
        sqLiteDatabase.execSQL(CREATE_CONTACTS_TABLE);
    }
    // Adding new password
    public void addRamz(Ramz ramz) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_RAMZ, ramz.get_ramz());
        values.put(KEY_GOAL, ramz.get_goal());
        values.put(KEY_USERNAME, ramz.get_username());

        // Inserting Row
        db.insert(TABLE_RAMZ, null, values);
        db.close(); // Closing database connection
    }
    // Getting All passwords
    public List<Ramz> getAllRamz() {
        List<Ramz> ramzList = new ArrayList<Ramz>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_RAMZ;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Ramz ramz = new Ramz();
                ramz.set_id(Integer.parseInt(cursor.getString(0)));
                ramz.set_ramz(cursor.getString(1));
                ramz.set_goal(cursor.getString(2));
                ramz.set_username(cursor.getString(3));
                // Adding password to list
                ramzList.add(ramz);
            } while (cursor.moveToNext());
        }

        // return password list
        return ramzList;
    }

    // Getting single contact
    Ramz getRamz(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_RAMZ, new String[] { KEY_ID,
                        KEY_RAMZ, KEY_GOAL, KEY_USERNAME }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Ramz ramz = new Ramz(Integer.parseInt(cursor.getString(0)),cursor.getString(1),
                cursor.getString(2), cursor.getString(3));
        // return contact
        return ramz;
    }
    // Deleting single password
    public void deleteRamz(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_RAMZ, KEY_ID + " = ?",
                new String[] { String.valueOf(id) });
        db.close();
    }
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        // Drop older table if existed
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_RAMZ);

        // Create tables again
        onCreate(sqLiteDatabase);
    }



}

如果您想要更多描述,请告诉我为您描述更多内容。

1 个答案:

答案 0 :(得分:0)

你应该传递对象的KEY_ID以删除该对象而不是它在列表上的位置

Ramz ramz = new Ramz();

更新:

正如@Selvin所说,在你的适配器属性中删除这一行

onBindViewHolder

并将final Ramz ramz = ramzList.get(position); 中的这一行更改为:

transform