How to remove items from firebase RecyclerView
Asked Answered
C

4

5

I'm currently working on Adding Friends with the help of firebase RecyclerView in which if a user tap on ADD button, he is added in database n that tapped item is needed to be removed permanently.. so, how to achieve it through firebase model as we dont have any data list to remove from..

Here's the code

 @Override
public void onStart(){
    super.onStart();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    EmailPref=prefs.getString("EmailPref", EmailPref);
    if(EmailPref!=null){

        final Firebase ref = new Firebase(constants.FIREBASE_URL+"rootssahaj/authGplus");


        FirebaseRecyclerAdapter<FriendsData,FriendsViewHolder> adapter=new FirebaseRecyclerAdapter<FriendsData, FriendsViewHolder>(
                         FriendsData.class,
                         R.layout.chat_view_list,
                          FriendsViewHolder.class,
                         ref

                    ) {
            @TargetApi(Build.VERSION_CODES.KITKAT)
            @Override
            protected void populateViewHolder(FriendsViewHolder friendsViewHolder, FriendsData s, int position) {
                String key = this.getRef(position).getKey();
                Log.e("SahajLOG", "String Keyyy " + key + " n EmailPref" + EmailPref);

                if (!Objects.equals(key, EmailPref)) {
                    friendsViewHolder.mName.setText(s.getUserNAME());
                    Picasso.with(context).load(s.getPicurl()).transform(new CircleTransform()).into(friendsViewHolder.mImageProfile);


                    String keylocal = key;
                    Log.e("pavan", "Populate AddF key" + keylocal+" " + position);
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
                    prefs.getString("keylocal" + position, keylocal + position);
                    if (keylocal != null) {
                        prefs.edit().putString("keylocal" + position, keylocal + position).commit();
                    }
                } else {
                    friendsViewHolder.mCardView.setVisibility(View.GONE);
                    //friendsViewHolder.setVisibility(View.GONE);
                }

            }
        };

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new SlideInLeftAnimator());
        recyclerView.getItemAnimator().setAddDuration(1000);
        recyclerView.getItemAnimator().setRemoveDuration(1000);
        recyclerView.getItemAnimator().setMoveDuration(1000);
        recyclerView.getItemAnimator().setChangeDuration(1000);


        SlideInLeftAnimator animator = new SlideInLeftAnimator();
        animator.setInterpolator(new OvershootInterpolator());
        recyclerView.setItemAnimator(animator);
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(adapter);
        alphaAdapter.setDuration(500);
        alphaAdapter.setInterpolator(new OvershootInterpolator(.5f));
        alphaAdapter.setFirstOnly(false);
        recyclerView.setAdapter(new ScaleInAnimationAdapter(alphaAdapter));


    }
}

public class FriendsViewHolder extends RecyclerView.ViewHolder{
    ImageView mImageProfile;
    android.widget.TextView mName;
    private int mVisibility;
    Boolean CallAdd=false;
    Button mAdd;
    String keylocal;
    CardView mCardView;

    public FriendsViewHolder(View itemView) {
        super(itemView);
        mCardView=(CardView)itemView.findViewById(R.id.cardView);
        mImageProfile=(ImageView)itemView.findViewById(R.id.profilePICC);
        mName=(android.widget.TextView)itemView.findViewById(R.id.NameUSER);
        context = itemView.getContext();
        mAdd=(Button)itemView.findViewById(R.id.addButton);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        if(prefs.getBoolean("CallAdd", CallAdd)){
            AddaddButton();

        }

        mAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
               EmailPref = prefs.getString("EmailPref", EmailPref);
               keylocal=prefs.getString("keylocal"+getAdapterPosition(),keylocal+getAdapterPosition());

               final Firebase mFirebaseRef = new Firebase(constants.FIREBASE_URL + "rootssahaj/authGplus/"+ EmailPref);
                mFirebaseRef.child("friends").child(keylocal).setValue("true");
                Log.e("pavan", "Chat Adapter " + EmailPref + keylocal + " final key: " + keylocal);
                //remove(getAdapterPosition());

            }
        });
    }
    public void AddaddButton(){
        if (mAdd.getVisibility() == View.INVISIBLE) {
            mAdd.setVisibility(View.VISIBLE);
        }
    }

}
Chickenlivered answered 27/3, 2016 at 20:47 Comment(0)
S
7

If you look at this code, it removes a Note from Firebase when the Note is clicked. It seems straight forward if you understand a Firebase query. This will also update the RecyclerView once the RecyclerView adapter is setup correctly. You don't need a List of data, just the value of what you want to remove, like an ID or a key.

       @Override
        public void onLongClick(View v, int i) {
            mquery.orderByChild("text")
                    .equalTo((String) notes.get(i).getName())
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            if (dataSnapshot.hasChildren()) {
                                DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next();
                                firstChild.getRef().removeValue();
                            }
                        }

                        public void onCancelled(FirebaseError firebaseError) {
                        }
                    });

The FirebaseRecyclerAdapter.class from https://github.com/mmazzarolo/firebase-recyclerview works. I just copied and pasted, for the most part. This is an abstract class you can use to make a RecyclerView adapter for your Firebase database. All the code is on that GitHub repository for you. Here is a snippet from FirebaseRecyclerAdapter.class that removes the value from Firebase AND updates the recyclerView:

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        String key = dataSnapshot.getKey();

        if (mKeys.contains(key)) {
            int index = mKeys.indexOf(key);
            T item = mItems.get(index);

            mKeys.remove(index);
            mItems.remove(index);

            notifyItemRemoved(index);
            itemRemoved(item, key, index);
        }
    }

UPDATE: You can hide a view in the Viewholder of the RecyclerView adapter. look at these answers in stackoverflow Hiding views in RecyclerView

Succubus answered 10/4, 2016 at 4:39 Comment(1)
actually i dont want to remove data from firebase, just to stop showing of tht data in reclylerview ie the friend which i have addedChickenlivered
D
18

The FirebaseUI FirebaseRecyclerAdapter is a direct representation of the data in the underlying Query or Firebase location. To remove an item from the adapter (and view), you have to remove it from the Firebase location (or ensure it doesn't match the query anymore).

So when the user triggers the deletion (e.g. by clicking on an item at a certain position):

adapter.getRef(position).remove()

Also see this issue in the FirebaseUI Github repo.

Dulse answered 27/3, 2016 at 20:56 Comment(4)
ohh it means it would remove that node from database if i directly used that methodChickenlivered
I am using this exact line (although its really adapter.getRef(position).removeValue() ) when I perform a longClick. The item gets deleted, but the recyclerview does not update anymore. I might put this as a questionSuccubus
the same issue, how to take deleted item away from recyclerview?Collective
You need notify after delete, prefer on Adapter, adapter.notify()Cracked
S
7

If you look at this code, it removes a Note from Firebase when the Note is clicked. It seems straight forward if you understand a Firebase query. This will also update the RecyclerView once the RecyclerView adapter is setup correctly. You don't need a List of data, just the value of what you want to remove, like an ID or a key.

       @Override
        public void onLongClick(View v, int i) {
            mquery.orderByChild("text")
                    .equalTo((String) notes.get(i).getName())
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            if (dataSnapshot.hasChildren()) {
                                DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next();
                                firstChild.getRef().removeValue();
                            }
                        }

                        public void onCancelled(FirebaseError firebaseError) {
                        }
                    });

The FirebaseRecyclerAdapter.class from https://github.com/mmazzarolo/firebase-recyclerview works. I just copied and pasted, for the most part. This is an abstract class you can use to make a RecyclerView adapter for your Firebase database. All the code is on that GitHub repository for you. Here is a snippet from FirebaseRecyclerAdapter.class that removes the value from Firebase AND updates the recyclerView:

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        String key = dataSnapshot.getKey();

        if (mKeys.contains(key)) {
            int index = mKeys.indexOf(key);
            T item = mItems.get(index);

            mKeys.remove(index);
            mItems.remove(index);

            notifyItemRemoved(index);
            itemRemoved(item, key, index);
        }
    }

UPDATE: You can hide a view in the Viewholder of the RecyclerView adapter. look at these answers in stackoverflow Hiding views in RecyclerView

Succubus answered 10/4, 2016 at 4:39 Comment(1)
actually i dont want to remove data from firebase, just to stop showing of tht data in reclylerview ie the friend which i have addedChickenlivered
J
1

Now you can delete specific child easy

(1)- First Step create method copy below code:

private void deleteRef(String id) { 

    databaseRef.child(id).removeValue();

}

(2) - Second step call this method in where you want like alert dialog or firebase recycler adapter in AlertDialog copy below:

public void alertDelete(final String id) { 

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    LayoutInflater inflater = getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.warning_delete, null);
    dialogBuilder.setView(dialogView);
    final AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();

    final Button deete = dialogView.findViewById(R.id.delete);

    delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            deleteRef(id);
            alertDialog.dismiss();
            Toast.makeText(Teachers_Admin_Activity.this,"Delete Successfully",Toast.LENGTH_LONG).show();                 
        }
    });
}

(3) Or delete from recyclerview child node like this, but remember must call from ViewHolder:

@Override
protected void onBindViewHolder(@NonNull final BlogViewHolder holder, final int position, @NonNull final TeachersName model) {

    // this is method in viewholer where you next step to delete specific child node // 
    DatabaseReference itemRef = getRef(position);
    final String myKeyItem = itemRef.getKey();
}

(4)- Last step onclicklistener:

holder.deleteImage.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        alertDelete(myKeyItem);
        return true;
    }
});
Julian answered 4/11, 2019 at 22:9 Comment(0)
M
0

If you are not using FirebaseRecyclerAdapter, then you should try this code in your delete button or Alert Dialog:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
                Query query = ref.orderByChild("status").equalTo(usr.getStatus());

                ValueEventListener listener = new ValueEventListener()

                {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for(DataSnapshot ds : dataSnapshot.getChildren()){
                            //remove
                            ds.getRef().removeValue();
                            Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                };
                query.addValueEventListener(listener);
Methylnaphthalene answered 2/2 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.