简体   繁体   中英

How to delete item from RecycleView when that recycle is on Fragment?

I try to delete one Item from my RecyclerView with OnDeleteData. but i have an error on Adapter file. (if i use this method for Activity its fine , but i change my activity to fragments)

Adapter File :

public class menuUserAdapter extends RecyclerView.Adapter<menuUserAdapter.ViewHolder> {
public interface dataListener{
    void onDeleteData(Transaksi transaksi , int position);
}
dataListener listener;

public menuUserAdapter(ArrayList<Transaksi> listtransaksi, Context context) {
    this.listtransaksi = listtransaksi;
    //this.listuser = listuser;
    this.context = context;
    listener = (homeFragment) context;
}
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
   holder.listitem.setOnLongClickListener(new View.OnLongClickListener() {
       public boolean onLongClick(final View v) {
          listener.onDeleteData(listtransaksi.get(position),position);
        }
   };
 }
}

on Fragments file :

  public class homeFragment extends Fragment implements menuUserAdapter.dataListener {


public void onDeleteData(Transaksi transaksi, int position) {
    if(reference != null){
        reference.child("transaksi").child(transaksi.getKey()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Toast.makeText(getActivity(), "Data Berhasil Dihapus", Toast.LENGTH_SHORT).show();
            }
        });
      }
  }


}

listener = (homeFragment) context; i have erorr on this line

Please help me

As your fragment is implementing the interface so initialize it with the fragment, context is the Activity context that holds the homeFragment.

public menuUserAdapter(ArrayList<Transaksi> listtransaksi, Context context, homeFragment fragment) {
    this.listtransaksi = listtransaksi;
    this.context = context;
    listener = fragment;
}

in your fragment

menuUserAdapter adapter = menuUserAdapter(listtransaksi, getActivity(), this);

Hope it helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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