recyclerview在对象删除时更新视图,除了最后一个对象

gkn4icbw  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(289)

在我的应用程序中,我有一个活动,它在recyclerview中显示学生的arraylist。学生存储在firebase实时数据库中。用户可以添加或删除学生。当用户删除一个学生时,recyclerview会更新并显示剩余的学生。
但我有个问题。例如,假设我有5个学生。我想删除所有5个,所以我删除他们一个接一个。其中4名学生删除正确,recyclerview更新并反映了这一点。只有当我删除最后一个学生时,recyclerview才不会更新,学生cardwiew才会保留在那里。我收到了一条toast消息,确认该学生被删除了,我可以看到他们在数据库中被删除了。如果我导航回 Jmeter 板并返回学生列表,cardview就会消失。奇怪。
我试着在每次删除后再次调用onstart,但都没用。有什么想法吗?
我的活动:

public class StudentListActivity extends AppCompatActivity {

//firebase auth
private FirebaseAuth mAuth;

//public variables
public String currentUserAccount;
public String teacherAccountNav = "Teacher";
public String currentUserId;

//recyclerView variables
DatabaseReference ref;
ArrayList<Student> list;
RecyclerView recyclerView;
SearchView searchView;

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_student_list);

    //get current user
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    //assert current user is not null and get current users id
    assert user != null;
    currentUserId = user.getUid();

    //getting firebase reference of current users students
    ref = FirebaseDatabase.getInstance().getReference().child("students").child(currentUserId);

    //initialise views
    recyclerView = findViewById(R.id.rv);
    recyclerView.setHasFixedSize(true);
    searchView = findViewById(R.id.searchView);

}

@Override
protected void onStart() {
    super.onStart();
    if(ref != null){
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                //add students from firebase to an array list
                if(dataSnapshot.exists()){
                    list = new ArrayList<>();
                    for(DataSnapshot ds : dataSnapshot.getChildren()){
                        list.add(ds.getValue(Student.class));
                    }

                    //sort by name
                    Collections.sort(list, Student.myName);

                    //make recycler view
                    recyclerView.setLayoutManager(new LinearLayoutManager(StudentListActivity.this));
                    StudentAdapterClass studentAdapterClass = new StudentAdapterClass(list);
                    recyclerView.setAdapter(studentAdapterClass);

                    //click listeners for buttons
                    studentAdapterClass.setOnItemClickListener(new StudentAdapterClass.OnItemClickListener() {

                        @Override
                        public void onUpdateClick(int position) {
                            //handle update click in here
                            Student student = list.get(position);

                            //show update dialog here
                            showUpdateDialog(student.getStudentId(), student.getStudentName(), student.getStudentEmail());
                        }

                        @Override
                        public void onDeleteClick(int position){
                            //handle delete click in here
                            Student student = list.get(position);

                            //show delete dialog here
                            showDeleteDialog(student.getStudentId());
                        }

                    });

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(StudentListActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }//if

}

//dialog box for deleting student
private void showDeleteDialog(final String studentId){
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

    LayoutInflater inflater = getLayoutInflater();

    //dialog XML
    final View dialogView = inflater.inflate(R.layout.delete_student_dialog, null);

    dialogBuilder.setView(dialogView);

    final ImageButton buttonNo = dialogView.findViewById(R.id.imageButtonNo);
    final ImageButton buttonYes = dialogView.findViewById(R.id.imageButtonYes);

    final AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();

    buttonNo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            alertDialog.dismiss();
        }
    });

    buttonYes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            deleteStudent(studentId);

            alertDialog.dismiss();
        }
    });
}

//delete student method
private void deleteStudent(String id){
    //get current user
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    //assert current user is not null and get current users id
    assert user != null;
    currentUserId = user.getUid();

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("students").child(currentUserId).child(id);

    databaseReference.removeValue();

    Toast.makeText(this, "Student Deleted", Toast.LENGTH_LONG).show();

    //clear and get new list
    onStart();

}

我的适配器:

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

private ArrayList<Student> list;

private OnItemClickListener mListener;

public interface OnItemClickListener{
    //click method for update button
    void onUpdateClick(int position);
    //click method for delete button
    void onDeleteClick(int position);

}

public void setOnItemClickListener(OnItemClickListener listener){
    mListener = listener;
}

public StudentAdapterClass(ArrayList<Student> list){

    this.list = list;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
     View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_holder, viewGroup, false);
     return new MyViewHolder(view, mListener);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
    myViewHolder.name.setText(list.get(i).getStudentName());
    myViewHolder.email.setText(list.get(i).getStudentEmail());

}

@Override
public int getItemCount() {

    return list.size();
}

static class MyViewHolder extends RecyclerView.ViewHolder {
    TextView name, email;
    ImageButton update, delete;
    MyViewHolder(@NonNull View itemView, final OnItemClickListener listener) {
        super(itemView);
        name = itemView.findViewById(R.id.studentName);
        email = itemView.findViewById(R.id.studentEmail);
        update = itemView.findViewById(R.id.updateButton);
        delete = itemView.findViewById(R.id.deleteButton);

        //update click listener
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null){
                    int position = getAdapterPosition();
                    if(position != RecyclerView.NO_POSITION){
                        listener.onUpdateClick(position);
                    }
                }

            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null){
                    int position = getAdapterPosition();
                    if(position != RecyclerView.NO_POSITION){
                        listener.onDeleteClick(position);
                    }
                }
            }
        });
    }
}
nzk0hqpo

nzk0hqpo1#

每次更改recyclerview数据时,都必须调用adapter方法 notifyDataSetChanged() ,否则,recyclerview无法正确刷新。你可以在里面打电话 deleteStudent() 像这样的方法。

recyclerView.getAdapter().notifyDataSetChanged()

相关问题