Firestore适配器可获取所有用户文档,而不会获取当前用户文档以显示在RecyclerView中

时间:2018-07-19 21:10:21

标签: android firebase android-recyclerview google-cloud-firestore recycler-adapter

我正在将Cloud Firestore用作数据库,以将所有用户另存为“用户”集合中的文档。我想将“用户”集合中的所有用户显示到我的RecyclerView中,但当前正在使用该应用程序的当前用户除外。我进行了大量搜索以找到整个Internet上的解决方案,但找不到任何解决方案。因此,请帮助我,谢谢。我是一个初学者,所以真的需要您的帮助。再次感谢。

这是我的Firestore适配器:

mQuery = FirebaseFirestore.getInstance().collection("users");
                    FirestoreRecyclerOptions<NearbyUserRecyclerModel> options = new FirestoreRecyclerOptions.Builder<NearbyUserRecyclerModel>()
                            .setQuery(mQuery,NearbyUserRecyclerModel.class)
                            .setLifecycleOwner(getActivity())
                            .build();

                    FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<NearbyUserRecyclerModel,NearbyProfilesViewHolder>(options) {
                        @Override
                        protected void onBindViewHolder(@NonNull final NearbyProfilesViewHolder holder, int position, @NonNull final NearbyUserRecyclerModel model) {
                            holder.itemBuddyState.setText("0");

                            Glide.with(getActivity()).load(model.getThumb_pictures()).into(holder.itemImage);

                            holder.itemDisplayName.setText(model.getFirst_name());

                            holder.itemOnline.setVisibility(View.VISIBLE);

                            DocumentSnapshot snapshot = getSnapshots().getSnapshot(position);
                            if (snapshot.contains("online")){
                                Boolean onlineState = snapshot.getBoolean("online");

                                if (onlineState == true){
                                    holder.itemOnline.setVisibility(View.VISIBLE);
                                }
                                else {
                                    holder.itemOnline.setVisibility(View.INVISIBLE);
                                }
                            }

                            final String user_id = snapshot.getId();

                            mChatRequestCollection.document(current_user_id).collection("request_received")
                                    .document(user_id).get().addOnCompleteListener(getActivity(),
                                    new OnCompleteListener<DocumentSnapshot>() {
                                        @Override
                                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                            if (task.isSuccessful()){
                                                DocumentSnapshot document = task.getResult();
                                                if (document.contains("received_time")){

                                                    holder.itemBuddyState.setText("3");

                                                }else {
                                                    Log.d("REQUEST RECEIVED", "onComplete: received field doest exist, "+task.getException());
                                                }

                                            }else {
                                                Log.d("REQUEST RECEIVED", "onComplete: Document doesn't exist, "+ task.getException());
                                            }

                                        }
                                    });

                            mChatRequestCollection.document(current_user_id).collection("request_sent")
                                    .document(user_id).get().addOnCompleteListener(getActivity(),
                                    new OnCompleteListener<DocumentSnapshot>() {
                                        @Override
                                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                            if (task.isSuccessful()){
                                                DocumentSnapshot document = task.getResult();

                                                if (document.contains("sent_time")){

                                                    holder.itemBuddyState.setText("2");

                                                }else {
                                                    Log.d("REQUEST SENT", "onComplete: sent field doesn't exist, "+ task.getException());
                                                }

                                            }else {
                                                Log.d("REQUEST SENT", "onComplete: Document doesn't exist,");
                                            }
                                        }
                                    });

                            mChatHolderCollection.document(current_user_id+"/user_chats/"+user_id)
                                    .get().addOnCompleteListener(getActivity(),
                                    new OnCompleteListener<DocumentSnapshot>() {
                                        @Override
                                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                            if (task.isSuccessful()){
                                                DocumentSnapshot document = task.getResult();
                                                if (document.contains("timestamp")){

                                                    holder.itemBuddyState.setText("1");

                                                }else {
                                                    Log.d("CHAT_HOLDERDOC", "onComplete: timeStamp field doesn't exist, "+task.getException());
                                                }

                                            }else {
                                                Log.d("CHAT_HOLDERDOC", "onComplete: chat buddy doesn't exist, "+task.getException());
                                            }
                                        }
                                    });

                            holder.itemImage.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    userPopupDialog(model, user_id);
                                    //  popupIntent(user_id);
                                }
                            });

                            holder.itemButton.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(final View v) {

                                    String message = holder.itemEditText.getText().toString();

                                    if (holder.itemBuddyState.getText().equals("0")){

                                        if (!TextUtils.isEmpty(message)) {

                                            WriteBatch request_batch = mRootStore.batch();

                                            Map<String, Object> sentMap = new HashMap<>();
                                            sentMap.put("sent_time", FieldValue.serverTimestamp());
                                            sentMap.put("message", message);

                                            Map<String, Object> receivedMap = new HashMap<>();
                                            receivedMap.put("received_time", FieldValue.serverTimestamp());
                                            receivedMap.put("message", message);

                                            Map<String, Object> notificationMap = new HashMap<>();
                                            notificationMap.put("from", current_user_id);
                                            notificationMap.put("type", "request");

                                            DocumentReference sentRef = mRootStore.collection("chat_requests").document(current_user_id + "/request_sent/" + user_id);
                                            request_batch.set(sentRef, sentMap, SetOptions.merge());

                                            DocumentReference receivedRef = mRootStore.collection("chat_requests").document(user_id + "/request_received/" + current_user_id);
                                            request_batch.set(receivedRef, receivedMap, SetOptions.merge());

                                            DocumentReference notificationRef = mRootStore.collection("users/" + user_id + "/notifications").document();
                                            request_batch.set(notificationRef, notificationMap, SetOptions.merge());

                                            request_batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {
                                                    if (task.isSuccessful()) {

                                                        //------------Request Sent------------//
                                                        holder.itemEditText.setText("");

                                                        holder.itemBuddyState.setText("2");

                                                        Log.d("REQUEST_LOG", "onComplete: Request sent Successfully");
                                                        Log.d("REQUEST_LOG", "onComplete: Notification sent Successfully");

                                                        Snackbar.make(v, "Request sent Successfully", Snackbar.LENGTH_LONG).show();
                                                    } else {
                                                        Snackbar.make(v, "Failed Sending Request", Snackbar.LENGTH_LONG).show();

                                                        Log.d("REQUEST_LOG", "onComplete: Failed sending request" + task.getException());


                                                    }
                                                }
                                            });
                                        }

                                    }

                                    if (holder.itemBuddyState.getText().equals("3")){
                                        holder.itemEditText.setText("");
                                        Snackbar.make(v, "Request already received by user", Snackbar.LENGTH_LONG).show();
                                    }

                                    if (holder.itemBuddyState.getText().equals("2")){
                                        holder.itemEditText.setText("");
                                        Snackbar.make(v, "Request already sent", Snackbar.LENGTH_LONG).show();
                                    }

                                    if (holder.itemBuddyState.getText().equals("1")){
                                        holder.itemEditText.setText("");
                                        Snackbar.make(v,"User already chat buddy", Snackbar.LENGTH_LONG).show();
                                    }

                                }
                            });

                        }

                        @NonNull
                        @Override
                        public NearbyProfilesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.nearby_profiles_recycler_items, parent, false);

                            final AppCompatImageButton button_send = view.findViewById(R.id.itemSendButton_id);
                            final AppCompatEditText editText_message =  view.findViewById(R.id.itemEditText_id);

                            Drawable drawable = getResources().getDrawable(R.drawable.ic_send_new);
                            drawable = DrawableCompat.wrap(drawable);
                            DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorTabUnselected));
                            button_send.setImageDrawable(drawable);
                            button_send.setEnabled(false);

                            editText_message.addTextChangedListener(new TextWatcher() {
                                @Override
                                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                                }

                                @Override
                                public void onTextChanged(CharSequence s, int start, int before, int count) {
                                    String message = editText_message.getText().toString();

                                    if (TextUtils.isEmpty(message)){
                                        Drawable drawable = getResources().getDrawable(R.drawable.ic_send_new);
                                        drawable = DrawableCompat.wrap(drawable);
                                        DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorTabUnselected));

                                        button_send.setImageDrawable(drawable);
                                        button_send.setEnabled(false);
                                    }
                                    else {
                                        Drawable drawable = getResources().getDrawable(R.drawable.ic_send_new);
                                        drawable = DrawableCompat.wrap(drawable);
                                        DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorTabSelected));

                                        button_send.setImageDrawable(drawable);

                                        button_send.setEnabled(true);
                                    }

                                }

                                @Override
                                public void afterTextChanged(Editable s) {

                                }
                            });

                            return new NearbyProfilesViewHolder(view);
                        }
                    };

                    nearbyRecycler.setAdapter(adapter);

2 个答案:

答案 0 :(得分:2)

通过以下方法更改IF条件

 public void getUserData(){
    db.collection("users")
            .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    Log.d(TAG, document.getId() + " => " + document.getData());
                    if(document.getData().get("userID").equals(userID)){
                       // User user = (User)document.getData();
                       // Log.e(TAG, "onComplete: "+user.getUserName()+ user.getDescription() + user.isGender());
                        Map<String, Object> user = new HashMap<>();
                        user.put("name", document.getData().get("name"));
                        user.put("userID", document.getData().get("userID"));
                        user.put("email", document.getData().get("email"));
                        user.put("companyName",document.getData().get("companyName"));
                        user.put("officeAddress", document.getData().get("officeAddress"));
                        user.put("phoneNumber", document.getData().get("phoneNumber"));
                        user.put("gender",document.getData().get("gender"));
                        user.put("isProfileComplete",document.getData().get("isProfileComplete"));
                        user.put("profilePicUrl", document.getData().get("profilePicUrl"));
                        user.put("description", document.getData().get("description"));

                       /* if(document.getData().get("isProfileComplete")){
                            LoginActivity loginActivity = (LoginActivity)mContext;
                            loginActivity.navigateToHome();
                        }else{
                             LoginActivity loginActivity = (LoginActivity)mContext;
                            loginActivity.navigateToHome();
                        }*/
                       boolean check = (Boolean) document.getData().get("isProfileComplete");

                       if(check){
                           LoginActivity loginActivity = (LoginActivity)mContext;
                           loginActivity.navigateToHome();
                       }else{
                           LoginActivity loginActivity = (LoginActivity)mContext;
                           loginActivity.navigateToOnBoarding();
                       }

                        Log.e(TAG, "onComplete:GET DADA "+ user.get("isProfileComplete"));
                    }else{
                        Log.e(TAG, "onComplete:ID "+document.getData().get("userID") );
                        LoginActivity loginActivity = (LoginActivity)mContext;
                        loginActivity.navigateToOnBoarding();
                    }
                }
            } else {
                Log.w(TAG, "Error getting documents.", task.getException());
            }
        }
    });
}

答案 1 :(得分:1)

无法使用DECLARE @T TABLE (ROW_NUM INT, AMOUNT MONEY,N_AMOUNT MONEY, NEEDED_RESULT MONEY) INSERT INTO @T SELECT * FROM (VALUES (1, 100.00, NULL ,100), (2, 300.00, NULL ,200), (3, 300.00, -400.00 ,0 ) ) a(ROW_NUM , AMOUNT ,N_AMOUNT , NEEDED_RESULT ) ;WITH x AS ( SELECT *, [R] = SUM(Amount) OVER (ORDER BY ROW_NUM DESC) + SUM(N_Amount) OVER () FROM @T ) SELECT ROW_NUM,AMOUNT,N_AMOUNT, NEEDED_RESULT, CASE WHEN R < 0 THEN 0 WHEN R > Amount THEN Amount ELSE R END FROM x ORDER BY ROW_NUM (不等于运算符)查询Firestore数据库。因此,以下代码行不存在:

  

查询查询= db.collection(“用户”)。其中 EqualTo(“ userID”,userID);

在这种情况下,您需要为此创建自己的逻辑。要解决此问题,您需要在数据库中查询所有用户,但适配器应接收除当前用户之一以外的所有用户。因此,您需要创建一个if语句来检查当前用户是否不同于其他用户。