聊天未在屏幕上正确呈现

时间:2018-09-27 14:48:48

标签: android firebase firebase-realtime-database dialogflow firebaseui

我使用Dialogflow创建了一个聊天机器人,并将其连接到Android和Firebase。现在,当我键入来自用户的消息时,机器人会收到正确的响应并将其保存在数据库中。但是我无法在创建的布局上同时显示问候语和答案。

下面是Chatbot主要活动的代码。

RecyclerView chatbotMainRecyclerView;
EditText chatbotMainEditxt;
RelativeLayout chatbotMainbtnAdd;

DatabaseReference chatbotDatabaseRef;
FirebaseRecyclerAdapter<ChatMessage, ChatViewHolder> adapter;
Boolean flagFab = true;


private AIService aiService;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chatbot_main);

    chatbotMainRecyclerView = (RecyclerView)findViewById(R.id.chatbot_main_recyclerView);
    chatbotMainEditxt = (EditText)findViewById(R.id.chatbot_main_editTxt);
    chatbotMainbtnAdd = (RelativeLayout)findViewById(R.id.chatbot_main_btnAdd);

    final AIConfiguration aiConfiguration = new AIConfiguration("afb8ad5048a74e7f84639c8421ea9de2",
                                                AIConfiguration.SupportedLanguages.English,
                                                AIConfiguration.RecognitionEngine.System);

    aiService = AIService.getService(this, aiConfiguration);
    aiService.setListener(this);

    final AIDataService aiDataService = new AIDataService(aiConfiguration);

    final AIRequest aiRequest = new AIRequest();


    chatbotMainRecyclerView.setHasFixedSize(true);

    final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setStackFromEnd(true);
    chatbotMainRecyclerView.setLayoutManager(linearLayoutManager);

    chatbotDatabaseRef = FirebaseDatabase.getInstance().getReference();
    chatbotDatabaseRef.keepSynced(true);

    chatbotMainbtnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String message = chatbotMainEditxt.getText().toString().trim();

            if(!message.equals(""))
            {
                ChatMessage chatMessage = new ChatMessage(message, "user");
                chatbotDatabaseRef.child("Chatbot").push().setValue(chatMessage);

                aiRequest.setQuery(message);
                new AsyncTask<AIRequest, Void, AIResponse>(){

                    @Override
                    protected AIResponse doInBackground(AIRequest... aiRequests) {
                        final AIRequest request = aiRequests[0];
                        try{
                            final AIResponse response = aiDataService.request(aiRequest);
                            return response;
                        } catch (AIServiceException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(AIResponse aiResponse) {

                        if(aiResponse!=null)
                        {
                            Result result = aiResponse.getResult();
                            String reply = result.getFulfillment().getSpeech();
                            ChatMessage aiChatMsg = new ChatMessage(reply, "scrapwrapbot");

                            chatbotDatabaseRef.child("Chatbot").push().setValue(aiChatMsg);
                        }

                        //super.onPostExecute(aiResponse);
                    }
                }.execute(aiRequest);
            }
            else {
                aiService.startListening();
            }

            chatbotMainEditxt.setText("");
        }
    });


    FirebaseRecyclerOptions<ChatMessage> chatOptions = new FirebaseRecyclerOptions.Builder<ChatMessage>().setQuery(chatbotDatabaseRef.child("Chatbot"), ChatMessage.class).build();

    adapter = new FirebaseRecyclerAdapter<ChatMessage, ChatViewHolder>(chatOptions) {
        @Override
        protected void onBindViewHolder(@NonNull ChatViewHolder holder, int position, @NonNull ChatMessage model) {
            if(model.getMsgUser().equals("user"))
            {
                holder.txtRight.setText(model.getMsgText());
                holder.txtRight.setVisibility(View.VISIBLE);
                holder.txtLeft.setVisibility(View.GONE);
            }
            else
            {
                holder.txtLeft.setText(model.getMsgText());
                holder.txtRight.setVisibility(View.GONE);
                holder.txtLeft.setVisibility(View.VISIBLE);
            }
        }

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

    adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            super.onItemRangeChanged(positionStart, itemCount);

            int messageCnt = adapter.getItemCount();
            int lastVisiblePosition = linearLayoutManager.findLastCompletelyVisibleItemPosition();

            if(lastVisiblePosition == -1 || (positionStart>= (messageCnt -1) && lastVisiblePosition == (positionStart -1)))
            {
                chatbotMainRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    chatbotMainRecyclerView.setAdapter(adapter);
}

@Override
public void onResult(AIResponse response) {
    Result result = response.getResult();

    String message = result.getResolvedQuery();
    ChatMessage chat = new ChatMessage(message, "user");
    chatbotDatabaseRef.child("Chatbot").push().setValue(chat);

    String reply = result.getFulfillment().getSpeech();
    ChatMessage chatMsg = new ChatMessage(reply, "scrapwrapbot");
    chatbotDatabaseRef.child("Chatbot").push().setValue(chatMsg);
}

下面是我创建的用于呈现请求和响应的布局。

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/chatbot_msgList_txtLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_alignParentStart="true"
        android:text="Hello this is me!!"
        android:padding="8dp"
        android:textColor="#212121"
        android:background="@color/cardview_shadow_start_color"
        android:elevation="2dp"
        />
    <TextView
        android:id="@+id/chatbot_msgList_txtRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_alignParentEnd="true"
        android:text="Hi!! How are you!!"
        android:background="@color/colorPrimaryDark"
        android:textColor="#fff"
        android:padding="8dp"
        android:elevation="2dp"/>
</RelativeLayout>

0 个答案:

没有答案