0

I am trying to remove item from firebaseRecyelerAdapter in populateViewHolder method. I am using item.setVisibility(view.GONE) but that again shows value when come back in that fragment. here is my code:

public class ChatsFragment extends Fragment {

private RecyclerView mConvList;

private DatabaseReference mConvDatabase;
private DatabaseReference mMessageDatabase;
private DatabaseReference mUsersDatabase;

private FirebaseAuth mAuth;

private String mCurrent_user_id;

private View mMainView;
private ProgressDialog pd;


public ChatsFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    mMainView = inflater.inflate(R.layout.fragment_chats, container, false);

    mConvList = (RecyclerView) mMainView.findViewById(R.id.conv_list);
    mAuth = FirebaseAuth.getInstance();

    mCurrent_user_id = mAuth.getCurrentUser().getUid();

    mConvDatabase = FirebaseDatabase.getInstance().getReference().child("Chat").child(mCurrent_user_id);

    mConvDatabase.keepSynced(true);
    mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
    mMessageDatabase = FirebaseDatabase.getInstance().getReference().child("messages").child(mCurrent_user_id);
    mUsersDatabase.keepSynced(true);

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
    linearLayoutManager.setReverseLayout(true);
    linearLayoutManager.setStackFromEnd(true);

    mConvList.setHasFixedSize(true);
    mConvList.setLayoutManager(linearLayoutManager);


    // Inflate the layout for this fragment
    return mMainView;
}


@Override
public void onStart() {
    super.onStart();

    Query conversationQuery = mConvDatabase.orderByChild("timestamp");

    final FirebaseRecyclerAdapter<Conv, ConvViewHolder> firebaseConvAdapter = new FirebaseRecyclerAdapter<Conv, ConvViewHolder>(
            Conv.class,
            R.layout.users_single_layout,
            ConvViewHolder.class,
            conversationQuery
    ) {
        @Override
        protected void populateViewHolder(final ConvViewHolder convViewHolder, final Conv conv, final int i) {

            final String list_user_id = getRef(i).getKey();

            Query lastMessageQuery = mMessageDatabase.child(list_user_id).limitToLast(1);

            lastMessageQuery.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                    String data = dataSnapshot.child("message").getValue().toString();
                    convViewHolder.setMessage(data, conv.isSeen());

                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });


            mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    final String userName = dataSnapshot.child("name").getValue().toString();
                    String userThumb = dataSnapshot.child("thumb_image").getValue().toString();

                    if(dataSnapshot.hasChild("online")) {

                        String userOnline = dataSnapshot.child("online").getValue().toString();
                        convViewHolder.setUserOnline(userOnline);

                    }

                    convViewHolder.setName(userName);
                    convViewHolder.setUserImage(userThumb, getContext());

                    convViewHolder.mView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {


                            Intent chatIntent = new Intent(getContext(), ChatActivity.class);
                            chatIntent.putExtra("user_id", list_user_id);
                            chatIntent.putExtra("user_name", userName);
                            startActivity(chatIntent);

                        }
                    });

                    convViewHolder.mView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View view) {
                            Toast.makeText(getContext(), "long clicked", Toast.LENGTH_SHORT).show();
                        firebaseConvAdapter.getRef(i).removeValue()
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        Toast.makeText(getContext(), "deleted", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            return false;

                        }
                    });


                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

        }
    };

    mConvList.setAdapter(firebaseConvAdapter);

}

public static class ConvViewHolder extends RecyclerView.ViewHolder {
Context context;
    View mView;

    public ConvViewHolder(View itemView) {
        super(itemView);

        mView = itemView;



    }
          public void setMessage(String message, boolean isSeen){

        TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
        userStatusView.setText(message);

        if(!isSeen){
            userStatusView.setTypeface(userStatusView.getTypeface(), Typeface.BOLD);
        } else {
            userStatusView.setTypeface(userStatusView.getTypeface(), Typeface.NORMAL);
        }

    }

    public void setName(String name){

        TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
        userNameView.setText(name);

    }

    public void setUserImage(String thumb_image, Context ctx){

        CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
        Picasso.with(ctx).load(thumb_image).placeholder(R.mipmap.default_image).into(userImageView);

    }

    public void setUserOnline(String online_status) {

        ImageView userOnlineView = (ImageView) mView.findViewById(R.id.user_single_online_icon);

        if(online_status.equals("true")){

            userOnlineView.setVisibility(View.VISIBLE);

        } else {

            userOnlineView.setVisibility(View.INVISIBLE);
        }
    } }}

I am trying to remove the value on LongClicked method.thanks. I also tried to used item.remove() method but that is not remove() method is not recogninzing in this method. Please help me

Msb Says
  • 11
  • 1
  • 7
  • 1
    If you are trying to remove an item from adapter better to remove that item from data set instead marking that item visibility GONE. – Krishna Sharma Jul 28 '18 at 06:37
  • can you elaborate please? – Msb Says Jul 28 '18 at 06:40
  • how can i implement that? – Msb Says Jul 28 '18 at 06:48
  • once you delete the item from database you also need to refresh your adapter. for more see this [how-to-remove-items-from-firebase-recyclerview](https://stackoverflow.com/questions/36252478/how-to-remove-items-from-firebase-recyclerview) – Krishna Sharma Jul 28 '18 at 06:53
  • no the item still shows when data is deleted from database. I am using chat fragment. If i delete chat from database the item still appears – Msb Says Jul 28 '18 at 06:56
  • Thats fine, but did you also update the ChatFragment list adapter on database item delete ? – Krishna Sharma Jul 28 '18 at 07:00
  • To keep them both in sync database and list view you have to update both of them,means deleting item from database also need to update/refresh the adapter. Bettor to add database delete callback listener and onSuccess update your adapter. – Krishna Sharma Jul 28 '18 at 07:03

2 Answers2

1

You need the firebaserecycleradapter and then find the position of the data by getting the reference of the data in firebase database. Then just remove it. Just try it. May be it will help you :)

 firebaseConvAdapter.getRef(i).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()){
                            //Your data is removed successfully!
                        }
                    }
                });
Gourango Sutradhar
  • 1,461
  • 10
  • 16
  • i also tried this before but it show that "firebaseConvAdapter might not have been initialized" what to do with this?? – Msb Says Jul 28 '18 at 06:09
  • Just declare it after your activity class as public variable. and use it. – Gourango Sutradhar Jul 28 '18 at 06:11
  • i am posting full code please view my updated question. – Msb Says Jul 28 '18 at 06:13
  • There is a simpler way to populate firebaserecycleradapter than yours!. You may follow the link provided firebase-ui [link is here](https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md) – Gourango Sutradhar Jul 28 '18 at 06:14
  • view my code now. You see where i use firebaseConvAdapter.getRef() in longClick() method. I give error that firebaseConvAdapter might not have been initiazled – Msb Says Jul 28 '18 at 06:16
  • There is a simple mistake brother. You should handle your recyclerview events inside of onBindViewHolder. I am posting a code with firebase recycler adapter in my next answer below. It will be useful for you. – Gourango Sutradhar Jul 28 '18 at 06:21
  • I have added another answer. Review it please. – Gourango Sutradhar Jul 28 '18 at 06:27
0

In your build.gradle

implementation 'com.firebaseui:firebase-ui-database:4.1.0'

In your action class:

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.gstech.merge.disasterapp.R;
import com.gstech.merge.disasterapp.holder.DisasterHolder;
import com.gstech.merge.disasterapp.model.DisasterModel;
import com.squareup.picasso.Picasso;


public class AdminPanel extends AppCompatActivity {
    RecyclerView recyclerView;
    FirebaseRecyclerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_panel);
        recyclerView = findViewById(R.id.recycler);
        Query query = FirebaseDatabase.getInstance().getReference().child("disatsers");
        FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<DisasterModel>()
                .setQuery(query, DisasterModel.class)
                .build();


        adapter = new FirebaseRecyclerAdapter<DisasterModel, DisasterHolder>(options) {
            @Override
            public DisasterHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.recycler_disaster_view, parent, false);

                return new DisasterHolder(view);
            }

            @Override
            protected void onBindViewHolder(DisasterHolder holder, int position, final DisasterModel model) {
                // Bind the Chat object to the ChatHolder
                // ...
                holder.type.setText("দুর্যোগের ধরণঃ " + model.getDisaster_type());
                holder.address.setText("Division: " + model.getDivision()
                        + ", District: " + model.getDistrtct()
                        + ", Upazilla: " + model.getUpazilla()
                        + ", Union: " + model.getUnion()
                        + ", Ward: " + model.getWard()
                );
                holder.datetime.setText("Date: " + model.getDate() + ", Time: " + model.getTime());
                holder.details.setText("আহতের সংখ্যাঃ " + model.getInjured() + ", মৃতের সংখ্যাঃ " + model.getDeath()
                        + ", পরিবারের সংখ্যাঃ " + model.getTotalfamily() + ", পাকা বাড়ির সংখ্যাঃ " + model.getPakabar()
                        + ", কাঁচা বাড়ির সংখ্যাঃ " + model.getKachabari() + ", গবাদি পশুর সংখ্যাঃ " + model.getAnimals());
                holder.others.setText("অন্যান্যঃ " + model.getOthers());
                Picasso.get().load(model.getPhotourl()).placeholder(R.drawable.loading).into(holder.image);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));


    }

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }
}

And create another class for view holder:

public class NewsHolder extends RecyclerView.ViewHolder {
    public ImageView cover;
    public TextView title;
    public CardView newscard;
    public NewsHolder(@NonNull View itemView) {
        super(itemView);

        cover = itemView.findViewById(R.id.cover);
        title = itemView.findViewById(R.id.title);
        newscard = itemView.findViewById(R.id.newscard);

    }
}

And your xml layout for the recyclerview:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/darker_gray">

            <TextView
                android:id="@+id/datetime"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:text="TextView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/address" />

            <TextView
                android:id="@+id/details"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:text="TextView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/datetime" />

            <TextView
                android:id="@+id/others"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:text="TextView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/details" />

            <TextView
                android:id="@+id/address"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:text="TextView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/type" />

            <ImageView
                android:id="@+id/image"
                android:layout_width="0dp"
                android:layout_height="120dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:scaleType="centerCrop"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/others"
                app:srcCompat="@drawable/bd_gov_logo" />

            <TextView
                android:id="@+id/type"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:text="TextView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>

Thatz it!!! edit the classes as your need. Thanks brother :)

Gourango Sutradhar
  • 1,461
  • 10
  • 16