Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

android - 从表中删除一条记录,从而从第二个表中删除所有对应的数据(Deleting a single record from a table which deletes all corresponding data from a second table)

I have two tables SignUpInfo and DetailInfo, what I am trying to achieve is when I delete a record from SignUpInfo, all corresponding DetailInfo should also be deleted.

(我有两个表SignUpInfo和DetailInfo,我要达到的目的是当我从SignUpInfo删除记录时,所有相应的DetailInfo也应删除。)

It might be 1 record in DetailInfo or many under single SignUpInfo record.

(它可能是DetailInfo中的1条记录,也可能是单个SignUpInfo记录中的许多条记录。)

I am pasting my Database Handler Class(code by RAVI TAMADA on https://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/ ) and My infoRecyclerView class code where I have implemented delete code.

(我正在粘贴我的数据库处理程序类(RAVI TAMADA在https://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/上的代码)和我已实现删除的infoRecyclerView类代码码。)

The error that I am getting is, when I implement the delete function, item does get deleted, the recyclerview gets updated, but again reappears when reopening the activity, and corresponding data is not getting deleted also.

(我得到的错误是,当我实现删除功能时,项目确实被删除,recyclerview得到更新,但是在重新打开活动时再次出现,并且相应的数据也没有被删除。)

public class InfoRecyclerView extends RecyclerView.Adapter<InfoRecyclerView.ViewHolder> {
    private Context context;
    private List<Info> infos;
    private LayoutInflater layoutInflater;
    private AlertDialog.Builder alertDialogBuilder;
    private AlertDialog dialog;


    public InfoRecyclerView(Context context, List<Info> infos) {
        this.context = context;
        this.infos = infos;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.signup_list_row, parent, false);

        return new ViewHolder(view, context);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        Info info = infos.get(position);

        holder.name.setText(info.getName());
        holder.mobile.setText(info.getMobile());
        holder.email.setText(info.getEmail());
    }



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

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView name;
        public TextView mobile;
        public TextView email;
        public Button editButton;
        public Button deleteButton;
        public int id;

        public ViewHolder(View view, Context ctx) {
            super(view);
            context = ctx;

            name = view.findViewById(R.id.list_name);
            mobile = view.findViewById(R.id.list_mobile);
            email = view.findViewById(R.id.list_email);
            editButton = view.findViewById(R.id.list_edit_button);
            deleteButton = view.findViewById(R.id.list_delete_button);

            editButton.setOnClickListener(this);
            deleteButton.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.list_edit_button:
                    int position = getAdapterPosition();
                    Info info = infos.get(position);
                    editItem(info);
                    Toast.makeText(context, "Edit Button Clicked", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.list_delete_button:
                    position = getAdapterPosition();
                    info = infos.get(position);
                    Toast.makeText(context, "Delete Button Clicked", Toast.LENGTH_SHORT).show();
                    deleteItem(info.getId());
                    break;
            }

        }

        public void deleteItem(final int id) {
            final Info infor = new Info();
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage("Are you sure you want to delete the student !").setCancelable(false)
                    .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            // delete the student
                            DataBaseHandler db = new DataBaseHandler(context);
                            db.deleteAllInfoDetail(infor,true);
//                            db.deleteSignUpInfo(id);
                            infos.remove(getAdapterPosition());
                            notifyItemRemoved(getAdapterPosition());
                            dialogInterface.dismiss();
                        }
                    })
                    .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    });
            builder.show();

        }

        private void editItem(final Info info) {
            alertDialogBuilder = new AlertDialog.Builder(context);
            layoutInflater = LayoutInflater.from(context);
            View view = layoutInflater.inflate(R.layout.edit_popup, null);

            final EditText name = view.findViewById(R.id.enter_student_name);
            final EditText mobile = view.findViewById(R.id.enter_mobile);
            final EditText email = view.findViewById(R.id.enter_email);
            final Button saveButton = view.findViewById(R.id.popup_save_button);

            // above content will be build and inflated
            alertDialogBuilder.setView(view);
            dialog = alertDialogBuilder.create();
            dialog.show();

            saveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                DataBaseHandler dataBaseHandler = new DataBaseHandler(context);
                info.setName(name.getText().toString());
                info.setMobile(mobile.getText().toString());
                info.setEmail(email.getText().toString());
                dataBaseHandler.updateSignUpInfo(info);
                    notifyItemChanged(getAdapterPosition(),info);
                    Toast.makeText(context, "Editing Successfull", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            });


        }
    }
}

Now my DataBase Handler Class

(现在我的数据库处理程序类)

public class DataBaseHandler extends SQLiteOpenHelper {

    // Database to Handler
    private static final String DATABASE_NAME = "StudentInfo";
    private static final int VERSION = 1;
    private static final String KEY_ID = "id";

    // Table Names
    private static final String TABLE_SIGNUP = "SignUpForm";
    private static final String TABLE_DETAIL = "DetailForm";
    private static final String TABLE_SIGNUP_DETAIL = "SignUp_Detail";
    // SignUp Form Table
    private static final String NAME = "name";
    private static final String MOBILE = "mobile";
    private static final String EMAIL = "email";
    private static final String IMAGE = "image";
    // SignUp Detail Table
    private static final String AGE =  "age";
    private static final String CLASS = "class";
    private static final String SUBJECT = "suject";
    // SignUp and Detail Table
    private static final String KEY_SIGNUP_ID = "signUpId";
    private static final String KEY_DETAIL_ID = "detailId";

    // Creating Sign Up Table
    private static final String CREATE_TABLE_SIGNUP = "CREATE TABLE "
            + TABLE_SIGNUP + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + NAME + " TEXT,"
            + MOBILE + " TEXT,"
            + EMAIL + " TEXT,"
            + IMAGE + " BLOB"
            + ")";
    // Creating Detail Table
    private static final String CREATE_TABLE_DETAIL = "CREATE TABLE "
            + TABLE_DETAIL + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + NAME + " TEXT,"
            + AGE + " TEXT,"
            + CLASS + " TEXT,"
            + SUBJECT + " TEXT"
            + ")";
    // Creating Combined Table SignUp and Detail
    private static final String CREATE_TABLE_SIGNUP_DETAIL = "CREATE TABLE "
            + TABLE_SIGNUP_DETAIL + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + KEY_SIGNUP_ID + " INTEGER,"
            + KEY_DETAIL_ID + " INTEGER"
            + ")";


    public DataBaseHandler(Context context) {
        super(context, DATABASE_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_TABLE_SIGNUP);
        sqLiteDatabase.execSQL(CREATE_TABLE_DETAIL);
        sqLiteDatabase.execSQL(CREATE_TABLE_SIGNUP_DETAIL);


    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_SIGNUP);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_DETAIL);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_SIGNUP_DETAIL);


        onCreate(sqLiteDatabase);

    }
    /*
     CRUD OPERATIONS for SIGNUP INFO
     */

    public long insertData(Info info, long [] detailIDs) {
        // getting writable datebase
        SQLiteDatabase db = this.getWritableDatabase();

        // new method content values to insert data into Info Class
        ContentValues contentValues = new ContentValues();

        contentValues.put(NAME, info.getName());
        contentValues.put(MOBILE, info.getMobile());
        contentValues.put(EMAIL, info.getEmail());
        contentValues.put(IMAGE, info.getImage());
        // insert new row
        long signUp_id = db.insert(TABLE_SIGNUP,null,contentValues);

        for (long detail_id : detailIDs){
            createSignUpDetail(signUp_id, detail_id);
        }
        return signUp_id;
    }

    public Info getInfo (long signUp_id){
        SQLiteDatabase db = this.getReadableDatabase();

        String selectQuery = "SELECT * FROM " + TABLE_SIGNUP + " WHERE "
                + KEY_ID + " = " + signUp_id;
        Cursor c = db.rawQuery(selectQuery, null);

        if ( c != null )
            c.moveToFirst();
        Info info = new Info();
        info.setId(c.getInt(c.getColumnIndex(KEY_ID)));
        info.setName(c.getString(c.getColumnIndex(NAME)));
        info.setEmail(c.getString(c.getColumnIndex(EMAIL)));
        info.setMobile(c.getString(c.getColumnIndex(MOBILE)));
        info.setImage(c.getBlob(c.getColumnIndex(IMAGE)));
        return info;
    }

    public List<Info> getAllInfo (){
        List<Info> infoList = new ArrayList<>();
        String selectQuery = "SELECT * FROM " + TABLE_SIGNUP;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list.
        if ( c.moveToFirst() ){
            do {
                Info info = new Info();
                info.setId(c.getInt(c.getColumnIndex(KEY_ID)));
                info.setName(c.getString(c.getColumnIndex(NAME)));
                info.setEmail(c.getString(c.get

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe that your issue is centred around the use of final Info infor = new Info();

(我相信您的问题集中在final Info infor = new Info();的使用上final Info infor = new Info();)

ie a new empty/constrcuted with default values Info object and that you then pass infor to the deleteAllInfoDetail method via db.deleteAllInfoDetail(infor,true);

(即一个新的空/用默认值Info对象constrcuted并且您然后通过传递的InfordeleteAllInfoDetail方法db.deleteAllInfoDetail(infor,true);)

The item appears to get deleted as you then remove the clicked item from the RecyclerView using infos.remove(getAdapterPosition());

(当您使用infos.remove(getAdapterPosition());从RecyclerView中删除单击的项目时,该项目似乎将被删除infos.remove(getAdapterPosition());)

.

(。)

Hence it is apparently deleted but then will re-appear if the RecyclerView is rebuilt from the database.

(因此,它显然已删除,但是如果从数据库重建RecyclerView,它将重新出现。)

You perhaps want to use

(你也许想用)

db.deleteAllInfoDetail(infos.get(getAdapterPosition()),true);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...