Как я могу решить проблему с данными, не отображаемыми из firebase-firestore в моем обзоре переработчика? - PullRequest
0 голосов
/ 03 апреля 2020

Пожалуйста, мне нужна помощь по вопросу отображения данных из Firebase Firestore на моем RecyclerView

. Я создаю приложение, которое должно отображать список пользователей с указанием их имени, изображения, статуса и последнего чата. на RecyclerView. Я написал адаптер и все необходимые классы POJO, и он прекрасно работает, когда заполняет его вручную из кода

Однако я продолжаю сталкиваться с трудностями при попытке сделать это автоматически из пожарного магазина Firebase

См. мои коды ниже и структура базы огня ниже

ЭТО МОЙ ПРОСТОЙ КЛАСС ПОЖО

package com.rhemaapp.rhematech.rhemahive.RhemaHiveMessagingPackage;

public class RhemaHiveUserMessageModel {

    public String senderId;
    public String receiverId;
    public String messageTimeStamp;
    public boolean isMessageStarred;
    public String messageStatus;
    public String userStatus;
    public String userIcon;
    public String userMessage;
    public String messageType;
    public String senderName;
    public String receiverName;
    public String user_church;
    public String receiverMessage;
    public String receiverTime;



    public RhemaHiveUserMessageModel(String senderId, String receiverId, String messageTimeStamp, boolean isMessageStarred, String messageStatus, String userStatus, String userIcon, String userMessage, String messageType, String churchName) {
        this.senderId = senderId;
        this.receiverId = receiverId;
        this.messageTimeStamp = messageTimeStamp;
        this.isMessageStarred = isMessageStarred;
        this.messageStatus = messageStatus;
        this.userStatus = userStatus;
        this.userIcon = userIcon;
        this.userMessage = userMessage;
        this.messageType = messageType;

    }

    public RhemaHiveUserMessageModel(String messageTimeStamp, String userMessage) {
        this.receiverTime = messageTimeStamp;
        this.userMessage = userMessage;
    }

    public RhemaHiveUserMessageModel() {
    }




    public RhemaHiveUserMessageModel(String messageTimeStamp, String messageStatus, String userMessage, String senderId, String receiverId, String messageType, boolean isMessageStarred, String church_name) {
        this.messageTimeStamp = messageTimeStamp;
        this.messageStatus = messageStatus;
        this.userMessage = userMessage;
        this.senderId = senderId;
        this.receiverId = receiverId;
        this.messageType = messageType;
        this.isMessageStarred = isMessageStarred;
        this.user_church = church_name;


    }

    public String getChurch_name() {
        return user_church;
    }

    public String getReceiverMessage() {
        return receiverMessage;
    }

    public String getReceiverTime() {
        return receiverTime;
    }

    public RhemaHiveUserMessageModel(String messageTimeStamp, String userIcon, String userMessage, String receiverName, String receiverId, String recStat) {
        this.messageTimeStamp = messageTimeStamp;
        this.userIcon = userIcon;
        this.userMessage = userMessage;
        this.receiverName = receiverName;
        this.receiverId = receiverId;
        this.userStatus = recStat;
    }

    public RhemaHiveUserMessageModel(String messageTimeStamp, String userStatus, String userMessage, String receiverMessage, String receiverTime) {
        this.messageTimeStamp = messageTimeStamp;
        this.userStatus = userStatus;
        this.userMessage = userMessage;
        this.receiverMessage = receiverMessage;
        this.receiverTime = receiverTime;
    }

    public String getSenderId() {
        return senderId;
    }

    public void setSenderId(String senderId) {
        this.senderId = senderId;
    }

    public String getReceiverId() {
        return receiverId;
    }

    public void setReceiverId(String receiverId) {
        this.receiverId = receiverId;
    }

    public String getMessageTimeStamp() {
        return messageTimeStamp;
    }

    public void setMessageTimeStamp(String messageTimeStamp) {
        this.messageTimeStamp = messageTimeStamp;
    }

    public boolean isMessageStarred() {
        return isMessageStarred;
    }

    public void setMessageStarred(boolean messageStarred) {
        isMessageStarred = messageStarred;
    }

    public String getMessageStatus() {
        return messageStatus;
    }

    public void setMessageStatus(String messageStatus) {
        this.messageStatus = messageStatus;
    }

    public String getUserStatus() {
        return userStatus;
    }

    public void setUserStatus(String userStatus) {
        this.userStatus = userStatus;
    }

    public String getUserIcon() {
        return userIcon;
    }

    public void setUserIcon(String userIcon) {
        this.userIcon = userIcon;
    }

    public String getUserMessage() {
        return userMessage;
    }

    public void setUserMessage(String userMessage) {
        this.userMessage = userMessage;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public String getSenderName() {
        return senderName;
    }

    public void setSenderName(String senderName) {
        this.senderName = senderName;
    }

    public String getReceiverName() {
        return receiverName;
    }

    public void setReceiverName(String receiverName) {
        this.receiverName = receiverName;
    }
}

ЭТО МОЙ АДАПТЕР КЛАСС

package com.rhemaapp.rhematech.rhemahive.RhemaHiveControllerPackage;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.rhemaapp.rhematech.rhemahive.GlideApp;
import com.rhemaapp.rhematech.rhemahive.R;
import com.rhemaapp.rhematech.rhemahive.RhemaHiveMessagingPackage.RhemaHiveUserMessageModel;

import java.util.ArrayList;

public class RhemaHiveMessageAdapter extends  RecyclerView.Adapter<RhemaHiveMessageAdapter.RhemaHiveMessageViewHolder> implements Filterable {
    private ArrayList<RhemaHiveUserMessageModel> rhemaHiveUserMessListMain = new ArrayList<>();
    private  RhemaHiveUserMessageModel rhemaModelMain;
    private ArrayList<RhemaHiveUserMessageModel> chatListFiltered;
    private View v;

    @NonNull
    @Override
    public RhemaHiveMessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_message_lay,parent, false);
        return new RhemaHiveMessageViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull RhemaHiveMessageViewHolder holder, int position) {
        rhemaModelMain = new RhemaHiveUserMessageModel();
        rhemaModelMain = rhemaHiveUserMessListMain.get(position);
        holder.tvName.setText(rhemaModelMain.getReceiverName());
        holder.tvTime.setText(rhemaModelMain.getMessageTimeStamp());
        holder.tvLastChat.setText(rhemaModelMain.getUserMessage());
        holder.tvRecvid.setText(rhemaModelMain.getReceiverId());
        if(!rhemaModelMain.getUserIcon().equals("")){
            GlideApp.with(v.getContext()).load(rhemaModelMain.getUserIcon()).centerCrop().fitCenter().into(holder.iv);
        }
        else{
            holder.iv.setImageResource(R.drawable.pic_upload);
        }


    }

    @Override
    public int getItemCount() {
        return rhemaHiveUserMessListMain.size();
    }


    /**
     * this method is implemented for performing filtering
     * @return
     */

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                //the user entry is retrieved and converted to String
                String searchString  = charSequence.toString();
                //a check is done for when entry is empty and then the list remains unchanged
                if(searchString.isEmpty()){
                    chatListFiltered = rhemaHiveUserMessListMain;
                }
                //otherwise a new list is created
                else{
                    ArrayList<RhemaHiveUserMessageModel> filteredChatListInternal = new ArrayList<>();
                    //a loop is carried out on the list
                    for(RhemaHiveUserMessageModel rModel : rhemaHiveUserMessListMain){
                        // a comparison is made to check if the list has entry from the search box
                        if(rModel.getReceiverName().toLowerCase().contains(searchString) || rModel.getUserMessage().toLowerCase().contains(searchString) || rModel.getUserStatus().toLowerCase().contains(searchString)){
                            //the new list is populated with this result
                            filteredChatListInternal.add(rModel);
                        }
                    }
                    //the new list is saved in the chatList
                    chatListFiltered = filteredChatListInternal;
                }
                //filter result is replaced and returned
                FilterResults filterResults = new FilterResults();
                filterResults.values = chatListFiltered;
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                //the results are published
                chatListFiltered = (ArrayList<RhemaHiveUserMessageModel>) filterResults.values;
                notifyDataSetChanged();
            }
        };
    }


    public class RhemaHiveMessageViewHolder extends RecyclerView.ViewHolder{

        TextView tvName, tvTime, tvLastChat,tvRecvid;
        ImageView iv;


        public RhemaHiveMessageViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.message_chat_name);
            tvTime = itemView.findViewById(R.id.message_time_sent);
            tvLastChat = itemView.findViewById(R.id.message_last_chat);
            iv = itemView.findViewById(R.id.message_user_icon);
            tvRecvid = itemView.findViewById(R.id.receivId);

        }


    }


    public RhemaHiveMessageAdapter(ArrayList<RhemaHiveUserMessageModel> rhemaHiveUserMessListMain) {
        this.rhemaHiveUserMessListMain = rhemaHiveUserMessListMain;
        this.chatListFiltered = rhemaHiveUserMessListMain;
    }
}

ЭТО МОЙ ФАЙЛ ДЛЯ РАЗВИТИЯ МОЕГО АДАПТЕРА

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="56dp"
        android:layout_height="56dp"
        app:cardCornerRadius="40dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:cardElevation="8dp"
        android:innerRadius="0dp"
        android:shape="ring"
        android:id="@+id/cv_message_img_card"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <ImageView
            android:layout_width="53dp"
            android:layout_height="53dp"
            android:id="@+id/message_user_icon"
            android:contentDescription="@string/sign_out_lab"
            app:srcCompat="@drawable/user_female"/>

    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/message_chat_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:fontFamily="@font/fauna_one"
        android:textStyle="bold"
        android:textAlignment="center"
        android:gravity="center"
        android:textSize="16sp"
        app:layout_constraintStart_toEndOf="@id/cv_message_img_card"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Samuel Iwuchukwu" />

    <TextView
        android:id="@+id/message_time_sent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginStart="88dp"
        android:layout_marginTop="8dp"
        android:textSize="12sp"
        android:fontFamily="@font/fauna_one"
        android:layout_marginEnd="8dp"
        app:layout_constraintStart_toEndOf="@id/message_chat_name"
        app:layout_constraintEnd_toEndOf="parent"
        android:textAlignment="textEnd"
        android:gravity="end"
        tools:text="3:10"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:fontFamily="@font/fauna_one"
        android:id="@+id/message_last_chat"
        tools:text="I am fine"
        android:drawableStart="@drawable/ic_good"
        app:layout_constraintTop_toBottomOf="@id/message_chat_name"
        app:layout_constraintStart_toEndOf="@id/cv_message_img_card"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/receivId"
        android:layout_marginTop="8dp"
        android:layout_marginStart="100dp"
        android:textSize="12sp"
        app:layout_constraintStart_toEndOf="@id/message_last_chat"
        app:layout_constraintTop_toBottomOf="@id/message_chat_name"
        android:textColor="@color/design_default_color_surface"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Это мой класс Fragment для отображения обзора переработчика

ЭТО ПОЛУЧАЕТ СПИСОК ЧАТОВ ИЗ FIRESTORE FIRESTORE

public void retrieveChatList(String church_name, String user_type){
    if (networkInfo != null && networkInfo.isConnectedOrConnecting() && networkInfo.isConnected()) {
    progressDialog.show();
    progressDialog.setMessage("Please wait while we retrieve the chats");
        collRef = fStore.collection("rhema_churches");
        collRef.whereEqualTo("user_church",church_name).whereEqualTo("user_type",user_type).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if(task.isSuccessful()){
                    //dismiss the dialog
                    for(DocumentSnapshot d : task.getResult()){
                        if(d.exists()) {


                                receiverPics = d.getString("user_pix");
                                retreiveRecId = d.getString("user_uid");
                                receiverName = d.getString("user_fName");
                                receiverStatus = d.getString("user_about");
                                messageTimeStamp = d.getString("user_address");
                                userMessage = d.getString("user_lName");
                                getAuto().getToast(getContext(), "ID : " + retreiveRecId, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
                            getAuto().getToast(getContext(), "name : " + receiverName, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
                            getAuto().getToast(getContext(), "Status : " + receiverStatus, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();

                            rhemaHiveUserMessageModels.add(new RhemaHiveUserMessageModel(messageTimeStamp, receiverPics, userMessage, receiverName, retreiveRecId, receiverStatus));
                            messageAdapter.notifyDataSetChanged();

                        }
                        else{
                            getAuto().getToast(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + " no documents found here", RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
                        }
                    }//end of for loop


                    progressDialog.dismiss();

                }
                else{
                    getAuto().getToast(getContext(),RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + task.getException().getLocalizedMessage(),RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
                }
            }
        });
    }

    else{
        getAuto().getToast(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + networkInfo.getReason(),RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
    }
    getAuto().getToast(getContext(), "ID : " + retreiveRecId, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
    getAuto().getToast(getContext(), "name : " + receiverName, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
    getAuto().getToast(getContext(), "Status : " + receiverStatus, RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
}

ЭТО СУЩЕСТВЕННЫЙ ВИД, ГДЕ УСТАНАВЛИВАЕТСЯ АДАПТЕР

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    try {
        setHasOptionsMenu(true);
        progressDialog = new ProgressDialog(getContext());
        recIdBund = new Bundle();
            arrRecId = new ArrayList<>();
        messageAreaIntent = new Intent(getContext(), RhemaHiveMessagingActivity.class);
        rhemaHiveUserMessageModels = new ArrayList<>();
        fAuth   = FirebaseAuth.getInstance();
        rhemaHiveUserMessageModel = new RhemaHiveUserMessageModel();
        fStore = FirebaseFirestore.getInstance();
        selRecID =  retrAllId();
        connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        //the NetworkInfo class gets the current state of the device network connection
        networkInfo = connMgr.getActiveNetworkInfo();
        v = inflater.inflate(R.layout.fragment_rhema_hive_message, container, false);
        rv = v.findViewById(R.id.rv_messaging);
        messageAdapter = new RhemaHiveMessageAdapter(rhemaHiveUserMessageModels);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
        rv.setLayoutManager(mLayoutManager);
        rv.setHasFixedSize(true);
        rv.setItemAnimator(new DefaultItemAnimator());
        rv.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        rv.setAdapter(messageAdapter);
        rv.addOnItemTouchListener(new RhemaHiveMessageTouchListenerClass(getContext(), rv, new RhemaHiveMessageTouchListenerClass.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                rhemaHiveUserMessageModel = rhemaHiveUserMessageModels.get(position);
                retreiveRecId = rhemaHiveUserMessageModel.getReceiverId();
                Toast.makeText(getContext(),"you are chatting with : " + rhemaHiveUserMessageModel.getReceiverName(),RhemaHiveClassReferenceConstants.TOAST_LONG_LEN).show();
                try {
                    //sendMessage("How are you",getCurrentDateTime(),RhemaHiveInstanceManagerClass.getRhemaHiveUserSubClass().getMessageType(0),false, getUid(),"hLqcai3Hn0YEGz2oINECMK0GGOF2",RhemaHiveInstanceManagerClass.getRhemaHiveUserSubClass().getMessageStatus(0),retrChurchName(getUid()));
                    //RhemaHiveMessageAreaFragment mFrag =  new RhemaHiveMessageAreaFragment();
                    recIdBund.putString("rId", retRecId());
                    messageAreaIntent.putExtras(recIdBund);
                    startActivity(messageAreaIntent);

                } catch (NullPointerException e) {
                    getAuto().getToast(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC  + e.getLocalizedMessage() , RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
                }

            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

        retrieveChatList(retrChurchName(getUid()),"RhemaHiveUser");

    } catch (Exception e) {
        Toast.makeText(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + e.getLocalizedMessage(),RhemaHiveClassReferenceConstants.TOAST_LONG_LEN).show();
    }
    return v;
}

ЭТО СПОСОБ ПОЛУЧЕНИЯ ИМЕНИ ЦЕРКВИ

public String retrChurchName(String uid) throws NullPointerException{
    if (networkInfo != null && networkInfo.isConnectedOrConnecting() && networkInfo.isConnected()) {
        collRef = fStore.collection("rhema_churches");
        collRef.whereEqualTo("user_uid", uid).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                if(!queryDocumentSnapshots.getDocuments().isEmpty()){
                    for(DocumentSnapshot doc : queryDocumentSnapshots.getDocuments()){
                        churchName = doc.getString("user_church");
                      //  getAuto().getToast(getContext(),"Church Retreived : " + churchName,RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();

                    }
                }
                else{
                    getAuto().getToast(getContext(), "Oops ! ! Sorry no chat to retreive", RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                getAuto().getToast(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + e.getLocalizedMessage(), RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
            }
        });

    }

    else{
        getAuto().getToast(getContext(), RhemaHiveClassReferenceConstants.ERROR_MESSAGE_GENERIC + networkInfo.getExtraInfo(), RhemaHiveClassReferenceConstants.TOAST_SHORT_LEN).show();
    }

    return churchName;

}

Пожарная база Firebase firebase image

...