繁体   English   中英

如何从 sqlite 数据库中删除项目并在 java 上回收视图 android

[英]How to remove item from sqlite database and recycle view on java android

我试图启动 function,它从我的 sqlite 数据库中删除了我的一项,但没有任何变化。 据说在我的回收视图中的项目上有一个按钮充当删除按钮,用于从回收视图中删除 object。 但是每次我点击它,什么都没有改变。 关于如何解决它的任何提示?

这是我的回收视图

package com.example.myapplication.recyclerview;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.DBhelper;
import com.example.myapplication.R;

import java.util.ArrayList;

public class bookingRecycleView extends RecyclerView.Adapter<bookingRecycleView.ViewHolder> {

    // variable for our array list and context
    private ArrayList<Booking> BookingArrayList;
    private Context context;
    DBhelper db;
    String name;
    // constructor
    public bookingRecycleView(ArrayList<Booking> BookingArrayList, Context context) {
        this.BookingArrayList = BookingArrayList;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // on below line we are inflating our layout
        // file for our recycler view items.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rbooking_row, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // on below line we are setting data 
        // to our views of recycler view item.
        Booking modal = BookingArrayList.get(position);
        holder.tv_name.setText(BookingArrayList.get(position).getName());
        holder.tv_bookingBategory.setText(BookingArrayList.get(position).getNotes());
        holder.tv_paymentStatus.setText(BookingArrayList.get(position).getBookingCheck());
        holder.button_delete_booking.setOnClickListener(view -> {

            Toast.makeText(view.getContext(),String.valueOf(BookingArrayList.get(position).getBookingid()),Toast.LENGTH_SHORT).show();
            AlertDialog.Builder builder = new AlertDialog.Builder(context);

            // Set a title for alert dialog
            builder.setTitle("Are you sure you want to delete this ?");

            // Ask the final question
            builder.setMessage("Deleted data cannot be undone.");

            // Set the alert dialog yes button click listener
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override

                public void onClick(DialogInterface dialog, int which) {
                    db = new DBhelper(context);
                    db.deleteCourse(name);

                }

            });

            // Set the alert dialog no button click listener
            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });

            AlertDialog dialog = builder.create();
            // Display the alert dialog on interface
            dialog.show();

        });
    }

    @Override
    public int getItemCount() {
        // returning the size of our array list
        return BookingArrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        // creating variables for our text views.
        public TextView tv_name,tv_bookingBategory,tv_paymentStatus;
        public Button button_delete_booking;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views
            tv_name = itemView.findViewById(R.id.tv_nameCrew);
            tv_bookingBategory = itemView.findViewById(R.id.tv_crewProgress);
            tv_paymentStatus = itemView.findViewById(R.id.tv_crewQuantity);
            button_delete_booking = itemView.findViewById(R.id.button_delete_booking);
        }
    }
}

数据库助手

package com.example.myapplication;

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

import androidx.annotation.Nullable;

import com.example.myapplication.recyclerview.Booking;

import java.util.ArrayList;

public class DBhelper extends SQLiteOpenHelper {
    public static final  String DBNAME="database.db";
    private static final String TABLE_NAME = "booking";

    public DBhelper(@Nullable Context context) {
        super((Context) context,"database.db", null, 1);
    }

    public DBhelper(DialogInterface.OnClickListener onClickListener) {
        super((Context) onClickListener,"database.db", null, 1);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {

         db.execSQL("create table users(username TEXT primary key, password TEXT )");
         db.execSQL("create table "+TABLE_NAME+"(serviceID INTEGER , name TEXT,notes TEXT,email TEXT,phone TEXT,bookingcheck INTEGER )");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("drop table if exists users");
        db.execSQL("drop table if exists " + TABLE_NAME);
        onCreate(db);
    }

    public Boolean insertData(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("username",username);
        values.put("password", password);

        long result  = db.insert("users",null,values);
        if(result==-1)return false;
        else
            return true;




    }

    public void addNewBooking( int serviceID, String name,String notes, String phone, String email, int bookingcheck) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        // on below line we are passing all values
        // along with its key and value pair.

        values.put("serviceID", serviceID);
        values.put("name", name);
        values.put("notes", notes);
        values.put("phone", phone);
        values.put("email", email);
        values.put( "bookingcheck", bookingcheck);

        // after adding all values we are passing
        // content values to our table.
        db.insert(TABLE_NAME, null, values);

        // at last we are closing our
        // database after adding database.

    }


    public Boolean checkusername(String username){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from users where username = ?", new String[] {username});
        if(cursor.getCount()>0){
            return true;
        }else
            return false;






    }

    public Boolean checkuserpass(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from users where username =? and password =?", new String[] {username,password});
        if(cursor.getCount()>0){
            return true;
        }else
            return false;






    }

    public ArrayList<Booking> readCourses() {
        // on below line we are creating a
        // database for reading our database.
        SQLiteDatabase db = this.getReadableDatabase();

        // on below line we are creating a cursor with query to read data from database.
        Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);

        // on below line we are creating a new array list.
        ArrayList<Booking> courseModalArrayList = new ArrayList<>();

        // moving our cursor to first position.
        if (cursorCourses.moveToFirst()) {
            do {
                // on below line we are adding the data from cursor to our array list.
                courseModalArrayList.add(new Booking(cursorCourses.getInt(0),
                        cursorCourses.getString(1),
                        cursorCourses.getString(2),
                        cursorCourses.getString(3),
                        cursorCourses.getString(4),
                        cursorCourses.getInt(5)));
            } while (cursorCourses.moveToNext());
            // moving our cursor to next.
        }
        // at last closing our cursor
        // and returning our array list.
        cursorCourses.close();
        return courseModalArrayList;
    }

    public void deleteCourse(String name) {

        // on below line we are creating
        // a variable to write our database.
        SQLiteDatabase db = this.getWritableDatabase();

        // on below line we are calling a method to delete our
        // course and we are comparing it with our course name.
        db.delete(TABLE_NAME, "name=?", new String[]{name});
        db.close();
    }

}

这是我的预订活动(显示回收视图的位置)

package com.example.myapplication.booking;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.DBhelper;
import com.example.myapplication.R;
import com.example.myapplication.recyclerview.Booking;
import com.example.myapplication.recyclerview.bookingRecycleView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class BookingActivity extends AppCompatActivity {


    DBhelper db;

    LinearLayoutManager linearLayoutManager;


    public FloatingActionButton fbtn_createBooking;
    private bookingRecycleView BookingRecycleView;
    private ArrayList<Booking> BookingArrayList;
    private RecyclerView recyclerView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_booking);

        BookingArrayList = new ArrayList<>();
        db =new DBhelper(this);
        BookingArrayList = db.readCourses();


        BookingRecycleView = new bookingRecycleView(BookingArrayList, BookingActivity.this);
        recyclerView = findViewById(R.id. recycler_view);

        linearLayoutManager = new LinearLayoutManager(BookingActivity.this);
        recyclerView.setLayoutManager(linearLayoutManager);

        recyclerView.setAdapter(BookingRecycleView);
        BookingRecycleView.notifyDataSetChanged();



        fbtn_createBooking =findViewById(R.id.fbtn_createBooking);

        fbtn_createBooking.setOnClickListener(new View.OnClickListener() {
            String name;
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(BookingActivity.this, AddBookingDetail.class);

                startActivity(intent);



            }
        });
    }

}

我的猜测是您正在删除 sqlite 中的数据,而不是您已传递给适配器的BookingArrayList中的数据。 如果您向我们展示您的回收活动,那就很清楚了,但我认为您所做的是从 sqlite 获取数据并将它们添加到BookingArrayList 因此,当您删除数据时,您正在对 sql 数据库执行此操作。 您还需要将它从数组中删除并通知您的适配器,以便它对您的视图产生影响。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM