我在查询中遇到错误

时间:2018-07-15 19:29:09

标签: java android firebase-realtime-database

在我的ChatActivity中,出现此异常:

java.lang.IllegalArgumentException: You must use startAt(String value), endAt(String value) or equalTo(String value) in combination with orderByKey(). Other type of values or using the version with 2 parameters is not supported
        at com.google.firebase.database.Query.zza(Unknown Source)
        at com.google.firebase.database.Query.zzb(Unknown Source)
        at com.google.firebase.database.Query.endAt(Unknown Source)
        at com.google.firebase.database.Query.endAt(Unknown Source)
        at com.jimmytrivedi.lapitchat.ChatActivity.loadMoreMessages(ChatActivity.java:318)

这是我的代码:

private void loadMoreMessages() {
        MessageReference = RootReference.child("Messages").child(currentUID).child(chatUser);
        Query query = MessageReference.orderByKey().endAt(LastKey).limitToLast(10);
        query.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Messages messages = dataSnapshot.getValue(Messages.class);
                String messageKey = dataSnapshot.getKey();

                if (PrevKey.equals(messageKey)) {
                    MsgList.add(itemPosition++, messages);
                } else {
                    PrevKey = LastKey;
                }

                if (itemPosition == 1) {
                    LastKey = messageKey;
                }

                messageAdapter.notifyDataSetChanged();
                refreshLayout.setRefreshing(false);
                linearLayoutManager.scrollToPositionWithOffset(10, 0);
            }

我不知道应该添加什么,因为在创建ChatFragment之前它运行良好,但是由于我做了一些更改并且我的片段为空白,所以我编写了wholw类,现在当我打开ChatFreagment并在ChatFragment中时,我重定向到ChatActivty,并且此异常即将到来。

ChatFragment.java

package com.priyanka.lapitchat;


import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
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.ImageView;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;


public class ChatFragment extends Fragment {

    private RecyclerView ConversationList;
    private DatabaseReference ConversationRef, MessageRef, UserRef;
    private FirebaseAuth mAuth;
    private String currentUID;
    private View MainView;

    public ChatFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        MainView = inflater.inflate(R.layout.fragment_chat, container, false);
        ConversationList = MainView.findViewById(R.id.ConversationList);
        mAuth = FirebaseAuth.getInstance();
        currentUID = mAuth.getCurrentUser().getUid();

        ConversationRef = FirebaseDatabase.getInstance().getReference().child("Chat").child(currentUID);
        ConversationRef.keepSynced(true);

        UserRef = FirebaseDatabase.getInstance().getReference().child("Users");
        UserRef.keepSynced(true);

        MessageRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUID);

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

        ConversationList.setHasFixedSize(true);
        ConversationList.setLayoutManager(layoutManager);

        return MainView;
    }

    @Override
    public void onStart() {
        super.onStart();
        Query conversationQuery = ConversationRef.orderByChild("timestamp");

        Query query = FirebaseDatabase.getInstance()
                .getReference()
                .child("Chat")
                .limitToLast(50);

        FirebaseRecyclerOptions<Conversation> options = new FirebaseRecyclerOptions.Builder<Conversation>()
                .setQuery(query, Conversation.class)
                .build();

        FirebaseRecyclerAdapter<Conversation, ConversationViewHolder> ConversationRecyclerViewAdapter = new
                FirebaseRecyclerAdapter<Conversation, ConversationViewHolder>(options) {
                    @Override
                    protected void onBindViewHolder(@NonNull final ConversationViewHolder holder, int position, @NonNull final Conversation model) {
                        final String listUID = getRef(position).getKey();

                        Query lastMessageQuery = MessageRef.child(listUID).limitToLast(1);

                        lastMessageQuery.addChildEventListener(new ChildEventListener() {
                            @Override
                            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                                String data = dataSnapshot.child("message").getValue().toString();
                                holder.setMassage(data, model.isSeen());
                            }

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

                            }

                            @Override
                            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

                            }

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

                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }
                        });

                        UserRef.child(listUID).addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                final String userName = dataSnapshot.child("Name").getValue().toString();
                                String userThumb = dataSnapshot.child("thumbImage").getValue().toString();

                                if (dataSnapshot.hasChild("Online")) {
                                    String userOnline = dataSnapshot.child("Online").getValue().toString();
                                    holder.setUserOnline(userOnline);
                                }

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

                                holder.mView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(getContext(), ChatActivity.class);
                                        intent.putExtra("userID", listUID);
                                        intent.putExtra("userName", userName);
                                        startActivity(intent);
                                    }
                                });
                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }
                        });

                    }

                    @NonNull
                    @Override
                    public ConversationViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
                        return new ConversationViewHolder(view);
                    }
                };

        ConversationList.setAdapter(ConversationRecyclerViewAdapter);
        ConversationRecyclerViewAdapter.startListening();
    }


    public static class ConversationViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public ConversationViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setMassage(String message, boolean isSeen) {
            TextView userStatusView = mView.findViewById(R.id.userStatus);
            userStatusView.setText(message);

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


        public void setUserOnline(String online) {
            ImageView userOnlineView = mView.findViewById(R.id.online);

            if (online.equals("true")) {
                userOnlineView.setVisibility(View.VISIBLE);
            } else {
                userOnlineView.setVisibility(View.INVISIBLE);
            }
        }

        public void setName(String userName) {
            TextView userNameView = mView.findViewById(R.id.userName);
            userNameView.setText(userName);
        }

        public void setUserImage(String userThumb, Context context) {
            CircleImageView userImageView = mView.findViewById(R.id.userImage);
            Picasso.get().load(userThumb).placeholder(R.drawable.defaultimage).into(userImageView);
        }
    }
}

LastKey是一个字符串,在下面的代码中的3个地方使用:

private void loadMoreMessages() {
        MessageReference = RootReference.child("Messages").child(currentUID).child(chatUser);
        Query query = MessageReference.orderByKey().endAt("LastKey").limitToLast(10);
        query.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Messages messages = dataSnapshot.getValue(Messages.class);
                String messageKey = dataSnapshot.getKey();

                if (PrevKey.equals(messageKey)) {
                    MsgList.add(itemPosition++, messages);
                } else {
                    PrevKey = LastKey;
                }

                if (itemPosition == 1) {
                    LastKey = messageKey;
                }

                messageAdapter.notifyDataSetChanged();
                refreshLayout.setRefreshing(false);
                linearLayoutManager.scrollToPositionWithOffset(10, 0);
            }

0 个答案:

没有答案