Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove items from firebase RecyclerView

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);
        }
    }

}
like image 540
Sahaj Rana Avatar asked Mar 27 '16 20:03

Sahaj Rana


2 Answers

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.

like image 137
Frank van Puffelen Avatar answered Oct 19 '22 17:10

Frank van Puffelen


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

like image 25
ChrisR Avatar answered Oct 19 '22 17:10

ChrisR