'When I press the button to delete an item from ListView it deletes the last one

I have next problem with a list view: So on the layout (prod_row) I set an image view(rvCls) that I want to delete an item while clicked. It deletes an item, but is always the last one. If I close this activity and I reopen it, it deletes the correct item, but what should I do to see the change instantly and not have to refresh the page?

on the Cos class I build logic for list view and cosAdapter is the Adapter class for my list view

COS class the one with the list view

public class Cos extends AppCompatActivity {
    ListView lvProd;
    SwipeMenuListView listView;
    Button btnTrm, btnCls;
    TextView tvTotal;
    DatabaseReference mDatabase;
    ArrayList<Produs> list = new ArrayList<Produs>();
    String email;
    Integer contor = 1;
    ImageView rvCls;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cos);
        FirebaseAuth mAuth;
        mAuth=FirebaseAuth.getInstance();
        FirebaseUser currentUser = mAuth.getCurrentUser();
        email = currentUser.getEmail();
        tvTotal = findViewById(R.id.tvTotal);
        btnTrm = findViewById(R.id.btnTrm);
        Intent i = getIntent();
        list = (ArrayList<Produs>) i.getSerializableExtra("set");
        Double total = 0.0;
        for(Produs p: list){
            total+= Double.valueOf(p.getPret()) * p.getQt();
        }
        Calendar rightNow = Calendar.getInstance();
        int hour = rightNow.get(Calendar.HOUR_OF_DAY);
        if(hour == 15){
            total /= 2;
        }
        tvTotal.setText("Total: " + String.valueOf(total) + " lei");
        btnTrm = findViewById(R.id.btnTrm);
        btnCls = findViewById(R.id.btnCls);
       // lvProd = findViewById(R.id.lvProd);
        listView = (SwipeMenuListView) findViewById(R.id.listView);
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Istoric");
        try {
            ArrayAdapter<Produs> adapter = new cosAdapter(this, 0 ,list);
            listView.setAdapter(adapter);
        }catch (Exception e){
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        btnCls.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                   intent.putExtra("set",(Serializable)list);
                    startActivity(intent);
                }catch (Exception e){
                    Toast.makeText(Cos.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
        btnTrm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for(Produs p : list){
                    IstoricData id= new IstoricData(email,p.getNume(),false,p.getQt());
                    Task t = mDatabase.push().setValue(id);
                    contor ++;
                    t.addOnCompleteListener(new OnCompleteListener() {
                        @Override
                        public void onComplete(@NonNull Task task) {
                            Toast.makeText(Cos.this, "Comanda a fost trimisa cu succes", Toast.LENGTH_SHORT).show();
                        }
                    });
                    t.addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(Cos.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                startActivity(new Intent(getApplicationContext(),MainActivity.class));
            }
        });
    }
}

COS adapter the adapter class for my list view adapter

public class cosAdapter extends ArrayAdapter<Produs> {
    private Context context;
    //private List<Produs> produse;
    ArrayList<Produs> produse;
    public cosAdapter(Context context, int resource, ArrayList<Produs> objects){
        super(context, resource, objects);
        this.context = context;
        this.produse = objects;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        RecyclerView.ViewHolder holder;LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        TextView rvNume, rvPret, rvCantitate, rvQT;
        ImageView rvImage;
        CardView cardView;
        ImageView rvCls;
        Produs model = produse.get(position);
        View view = inflater.inflate(R.layout.prod_row, null);
        View cos = inflater.inflate(R.layout.activity_cos, null);
        rvNume = view.findViewById(R.id.rvNume);
        rvCantitate = view.findViewById(R.id.rvCantitate);
        rvPret = view.findViewById(R.id.rvPret);
        rvImage = view.findViewById(R.id.rvImage);
        cardView = view.findViewById(R.id.cv);
        rvQT = view.findViewById(R.id.rvQT);
        rvCls = view.findViewById(R.id.rvCls);
        rvPret.setText("Pret: "+model.getPret()+ " lei");
        rvNume.setText(model.getNume());
        rvCantitate.setText("Cantitate: "+model.getCantitate()+" grame");
        rvQT.setText("Numar: x" +String.valueOf(model.getQt()));
        Picasso.get().load(model.getImage()).into(rvImage);
        rvCls.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                produse.remove(position);
                cosAdapter.super.notifyDataSetChanged();

            }
        });
        return view;
    }
}

My layout for each item in list view

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true">


    <ImageView
        android:id="@+id/rvCls"
        android:layout_width="34dp"
        android:layout_height="34dp"
        android:layout_alignParentRight="true"
        android:layout_gravity="right"
        android:layout_margin="5dp"
        android:layout_toRightOf="@+id/view"
        android:clickable="true"
        android:gravity="right"
        app:srcCompat="@drawable/ic_baseline_close_24" />

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/rvImage"
            android:layout_marginTop="5dp"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_weight="2"
            android:maxHeight="50dp"
            tools:srcCompat="@tools:sample/avatars" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/rvNume"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="TextView"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/rvCantitate"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="TextView" />

            <TextView
                android:id="@+id/rvPret"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="TextView" />

            <TextView
                android:id="@+id/rvQT"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="TextView" />
        </LinearLayout>
    </LinearLayout>

</androidx.cardview.widget.CardView>


Solution 1:[1]

There are 2 ways you could fix your code:

1.) Set position value as tag to your rvCls and fetch this tag for usage of position in your ClickListener

rvCls.setTag(position);
rvCls.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            produse.remove((int)v.getTag());
            notifyDataSetChanged();

        }
    });

2.) Use a variable finalPosition in getView and use that as position inside ClickListener.

final int finalPosition = position;
rvCls.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        produse.remove(finalPosition);
        notifyDataSetChanged();

    }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1