从firebaseRecyclerAdapter

时间:2018-07-28 05:48:03

标签: android firebase firebase-realtime-database android-recyclerview recycler-adapter

我正在尝试从populateViewHolder方法中的firebaseRecyelerAdapter中删除项目。我正在使用 item.setVisibility(view.GONE),但是当再次返回该片段时,它再次显示了价值。  这是我的代码:

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

我正在尝试删除 LongClicked 方法上的值。谢谢。 我也尝试使用item.remove()方法,但不是 remove()方法无法在此方法中识别。请帮助我

2 个答案:

答案 0 :(得分:0)

您需要 firebaserecycleradapter ,然后通过获取Firebase数据库中数据的引用来找到数据的位置。然后将其删除。 去尝试一下。也许会对您有帮助:)

 firebaseConvAdapter.getRef(i).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()){
                            //Your data is removed successfully!
                        }
                    }
                });

答案 1 :(得分:0)

在您的build.gradle中

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

在您的动作课中:

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

并为视图持有者创建另一个类:

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

    }
}

以及用于recyclerview的xml布局:

<?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 !!!!根据需要编辑类。谢谢兄弟:)