Home > Mobile >  when deleting a filtered Item in a Recyclerview it reappears, how do I avoid this?
when deleting a filtered Item in a Recyclerview it reappears, how do I avoid this?

Time:12-18

I have a Recyclerview which has a search bar at the top to filter by "rut", but when filtering an item and then deleting it by pressing the red trash button, the item reappears when leaving the filter field empty again, I understand that It happens because the filter keeps a temporary array of the data, but how can I get the new list anyway if I delete an item? I have tried several ways but I could not solve it (if I reload the activity it is possible to see that the item was removed and it does not come out again)

left a sequence of photos of the procedure that I comment.

in the first photo there is a list of 3 items

in the second I filter by the rut "098"

in the third I remove the filtered item "098"

in the fourth I no longer There is this item

but in the fifth, when eliminating what is written in the edittext (filter), the item "098" appears again and it brings company, because the items are duplicated

Code of Adapter

    package com.example.psicoapp;

import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

public class Adapter extends RecyclerView.Adapter<Adapter.PacientesviewHolder>{

    Context context;
    ArrayList<Pacientes> list;
    String userID, userID_S;

    final Adapter.OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(Pacientes item);
    }


    public Adapter(Context context, ArrayList<Pacientes> list, OnItemClickListener listener) {
        this.context = context;
        this.list = list;
        this.listener = listener;
        userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
        userID_S = userID.substring(0,5);
    }

    @NonNull
    @Override
    public PacientesviewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
        return new PacientesviewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull PacientesviewHolder holder, int position) {
        Pacientes paciente = list.get(position);

        holder.cv.setAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_transition));

        holder.textViewRut.setText(paciente.getRut());
        holder.textViewNombre.setText(paciente.getNombre());
        holder.textViewApellidos.setText(paciente.getApellidos());

        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatabaseReference ref = FirebaseDatabase.getInstance().getReference() // Firebase reference to after remove item
                        .child("Pacientes" userID_S)
                        .child(paciente.getKey());

                new AlertDialog.Builder(context)
                        .setIcon(R.drawable.ic_warning)
                        .setTitle("¿Seguro desea borrar a este paciente?") // to confirm deletion
                        .setCancelable(false)
                        .setNegativeButton(android.R.string.cancel, null)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                int newPosition = holder.getAdapterPosition();
                                list.remove(newPosition);
                                notifyItemRemoved(newPosition);
                                notifyItemRangeChanged(newPosition, list.size());

                                ref.removeValue();
                                list.clear();

                                notifyDataSetChanged();

                                /*Intent intent = new Intent(v.getContext(), mostrarActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                                v.getContext().startActivity(intent);*/

                                //ActivityOptions options  = ActivityOptions.makeSceneTransitionAnimation((Activity) v.getContext());
                            }
                        }).show();
            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onItemClick(paciente);
            }
        });
    }

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

    public static class PacientesviewHolder extends RecyclerView.ViewHolder {

        TextView textViewRut, textViewNombre, textViewApellidos;
        CardView cv;
        ImageView delete;

        public PacientesviewHolder(@NonNull View itemView) {
            super(itemView);
            textViewRut = itemView.findViewById(R.id.textview_rut);
            textViewNombre = itemView.findViewById(R.id.textview_nombre);
            textViewApellidos = itemView.findViewById(R.id.textview_apellidos);
            cv = itemView.findViewById(R.id.cv);

            delete = itemView.findViewById(R.id.ic_delete);

        }
    }

    public void filterList(ArrayList<Pacientes> filteredList) { // Filter
        list = filteredList;
        notifyDataSetChanged();
    }
}

Code where the recycler view is shown and where the filter is

    package com.example.psicoapp;

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

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class mostrarActivity extends AppCompatActivity {

    RecyclerView recyclerPa;
    DatabaseReference database;
    Adapter adapter;
    public ArrayList<Pacientes> list;
    String userID, userID_S;
    EditText editSearch;

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

        ocultarUpBar();

        userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
        userID_S = userID.substring(0,5);

        recyclerPa = findViewById(R.id.RecyclerPa);
        database = FirebaseDatabase.getInstance().getReference("Pacientes" userID_S);
        recyclerPa.setHasFixedSize(true);
        recyclerPa.setLayoutManager(new LinearLayoutManager(this));

        list = new ArrayList<>();
        adapter = new Adapter(this, list, new Adapter.OnItemClickListener() {
            @Override
            public void onItemClick(Pacientes item) {
                move(item);
            }
        });
        recyclerPa.setAdapter(adapter);

        database.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                    Pacientes pacientes = dataSnapshot.getValue(Pacientes.class);

                    pacientes.setKey(dataSnapshot.getKey());

                    list.add(pacientes);

                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

        editSearch = findViewById(R.id.editSearch);
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                filter(s.toString());
            }
        });
    }

    // Funciones

    private void filter(String text) {
        ArrayList<Pacientes> filteredList = new ArrayList<>();

        if (text.isEmpty()){
            Toast.makeText(this, "vacio", Toast.LENGTH_SHORT).show();

        }

        for (Pacientes item : list) {
            if (item.getRut().toLowerCase().contains(text.toLowerCase())) {
                filteredList.add(item);
            }
        }
        adapter.filterList(filteredList);
    }

    public void move(Pacientes item){
        Intent intent = new Intent(this, FichaPacientes_Activity.class);
        intent.putExtra("pacienteDetalles", item);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    private void ocultarUpBar(){
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
    }

    @Override
    public void finish() {
        super.finish();
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

}

CodePudding user response:

Try using

notifyItemRemoved(i);
notifyDataSetChanged();

Where i is the index of the item that was removed.

CodePudding user response:

Almost Done Dude simple mistake cause this issue

database.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
            // Clear list here your Activity class list
            list.clear()
                for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                    Pacientes pacientes = dataSnapshot.getValue(Pacientes.class);

                    pacientes.setKey(dataSnapshot.getKey());
                    // One more thing you can do is verify object
                    if(!list.containes(pacientes)){ // Check if not contains then add
                       list.add(pacientes);
                    }


                }
                // add this method in  your adapter and then 
                adapter.updateList(list)
                // No need if you call notifydatasetChanged here if call in above method
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

Adapter Update list method

    // Sorry for kotlin :-)
    fun updateList(it: List<ModelItem>) {
        if (it != null) {
            list = it
        }
        notifyDataSetChanged()
    }
  • Related