有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法在屏幕上正确显示用户和接收者发送的聊天信息

我正在使用Fire Base和DialogFlow开发一个聊天机器人安卓应用程序

它基本上是在录制音频时在按钮上显示麦克风图像,在发送文本时显示箭头图像,例如Whatsapp

我无法显示聊天室布局,如中所示:

https://安卓.jlelse.eu/building-chatbot-with-firebase-and-api-ai-5b787fe693a9GUI(没有图像,因为没有10次重复)

我将聊天记录存储在我的FireBase帐户中,我不仅能够在我的前端屏幕上显示它

应用程序。渐变相关性:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.安卓.support:appcompat-v7:28.0.0-rc02'
    implementation 'com.安卓.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-database:18.0.0'
    // FirebaseUI for Firebase Realtime Database
    implementation 'com.firebaseui:firebase-ui-database:5.0.0'
    implementation 'com.google.firebase:firebase-messaging:19.0.1'
    //implementation 'com.firebaseui:firebase-ui-database:2.3.0'
    implementation 'ai.api:sdk:2.0.7@aar'
    //implementation

    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'commons-io:commons-io:2.4'
    implementation "ai.api:libai:1.6.12"
    implementation 'com.google.firebase:firebase-core:17.0.0'
    testImplementation 'junit:junit:4.12'
    安卓TestImplementation 'com.安卓.support.test:runner:1.0.2'
    安卓TestImplementation 'com.安卓.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.安卓.support:recyclerview-v7:28.0.0'
}
apply plugin: 'com.google.gms.google-services'

主要活动。xml:(屏幕的基本布局,其中包含用于键入消息和发送按钮的文本字段)

<RelativeLayout
    xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    tools:context="com.example.internchatbot.MainActivity"
     >
    <安卓x.recyclerview.widget.RecyclerView
        安卓:id="@+id/recyclerView"
        安卓:layout_width="match_parent"
        安卓:layout_height="match_parent"
        安卓:paddingTop="10dp"
        安卓:paddingBottom="50dp"
        安卓:clipToPadding="false"
        安卓:background="#f4f6f7"
        />


    <RelativeLayout
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content"
        安卓:layout_alignParentBottom="true">


        <RelativeLayout
            安卓:layout_width="match_parent"
            安卓:layout_height="wrap_content"
            安卓:layout_marginStart="10dp"
            安卓:layout_marginLeft="10dp"
            安卓:layout_marginEnd="5dp"
            安卓:layout_marginRight="5dp"
            安卓:layout_marginBottom="10dp"
            安卓:elevation="2dp"
            安卓:background="@drawable/back_addtask"
            安卓:layout_toStartOf="@+id/addBtn"
            安卓:layout_toLeftOf="@id/addBtn"
            安卓:layout_centerVertical="true"
            >
            <EditText
                安卓:id="@+id/editText"
                安卓:layout_width="match_parent"
                安卓:layout_height="wrap_content"
                安卓:minHeight="50dp"
                安卓:layout_marginStart="20dp"
                安卓:layout_marginEnd="20dp"
                安卓:background="#ffffff"
                安卓:hint="Type a Message"
                安卓:textSize="18sp"/>
        </RelativeLayout>

        <RelativeLayout
            安卓:id="@+id/addBtn"
            安卓:layout_width="50dp"
            安卓:layout_height="50dp"
            安卓:layout_alignParentEnd="true"
            安卓:layout_alignParentRight="true"
            安卓:background="@drawable/back_fab"
            安卓:layout_marginBottom="10dp"
            安卓:layout_marginEnd="5dp"
            安卓:layout_marginRight="5dp"
            安卓:elevation="4dp"
            安卓:layout_centerInParent="true"
            >
            <安卓x.appcompat.widget.AppCompatImageView
                安卓:id="@+id/fab_img"
                安卓:layout_width="25dp"
                安卓:layout_height="25dp"
                安卓:layout_centerInParent="true"
                安卓:src="@drawable/ic_mic_white_24dp"
                安卓:tint="#ffffff"/>
        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>

味精清单。xml:它包含一个布局,该布局具有圆形边缘框,其中显示发送的消息和接收的消息

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    安卓:orientation="vertical"
    安卓:layout_width="match_parent"
    安卓:layout_height="wrap_content"
    xmlns:安卓="http://schemas.安卓.com/apk/res/安卓">

    <安卓x.appcompat.widget.AppCompatTextView
        安卓:id="@+id/leftText"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:layout_margin="10dp"
        安卓:layout_alignParentStart="true"
        安卓:layout_alignParentLeft="true"
        安卓:text="KG Precision Moulders"
        安卓:padding="8dp"
        安卓:textColor="#212121"
        安卓:background="@drawable/left_background"
        安卓:elevation="2dp"
        />


    <安卓x.appcompat.widget.AppCompatTextView
        安卓:id="@+id/rightText"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:layout_margin="10dp"
        安卓:layout_alignParentEnd="true"
        安卓:layout_alignParentRight="true"
        安卓:text="Query Center"
        安卓:background="@drawable/right_background"
        安卓:textColor="#ffffff"
        安卓:padding="8dp"
        安卓:elevation="2dp"/>


</RelativeLayout>

现在我的活动终于开始了。java(假设导入了所有头文件)

import 安卓.*;
import 安卓.content.Context;
import 安卓.graphics.Bitmap;
import 安卓.graphics.BitmapFactory;
import 安卓.os.AsyncTask;
import 安卓.os.Bundle;

import 安卓.text.Editable;
import 安卓.text.TextWatcher;
import 安卓.util.Log;
import 安卓.view.LayoutInflater;

import 安卓.view.View;
import 安卓.view.ViewGroup;
import 安卓.view.animation.Animation;
import 安卓.view.animation.AnimationUtils;
import 安卓.widget.EditText;
import 安卓.widget.ImageView;
import 安卓.widget.RelativeLayout;

import 安卓x.annotation.NonNull;
import 安卓x.appcompat.app.AppCompatActivity;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import ai.api.AIDataService;
import ai.api.AIListener;
import ai.api.AIServiceException;
import ai.api.安卓.AIConfiguration;
import ai.api.安卓.AIService;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import ai.api.model.Result;

import 安卓x.core.app.ActivityCompat;
import 安卓x.recyclerview.widget.LinearLayoutManager;
import 安卓x.recyclerview.widget.RecyclerView;

//import com.google.firebase.database.core.Context;
import com.google.firebase.database.Query;

现在是主要课程:


public class MainActivity extends AppCompatActivity implements AIListener{  //because I am recording audio too



    RecyclerView recyclerView;
    EditText editText;
    RelativeLayout addBtn;

    private DatabaseReference ref;
    Boolean flagFab = true;


    final   AIConfiguration config = new AIConfiguration("47f72f4d39b548edbbd11f123d3a40cb ",
            AIConfiguration.SupportedLanguages.English,
            AIConfiguration.RecognitionEngine.System);

    private AIService aiService;
    final AIDataService aiDataService = new AIDataService(config);

    final AIRequest aiRequest = new AIRequest();

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

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO},1);


        recyclerView = findViewById(R.id.recyclerView);
        editText = findViewById(R.id.editText);
        addBtn = findViewById(R.id.addBtn);

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

        ref=FirebaseDatabase.getInstance().getReference();

        final Query query=ref.child("chat").limitToLast(50);
        query.keepSynced(true);

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

        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String message = editText.getText().toString().trim();

                if (!message.equals("")) {

                    ChatMessage chatMessage = new ChatMessage(message, "user");

                    ref.child("chat").push().setValue(chatMessage);


                     aiRequest.setQuery(message);

                    MyAsyncTask myasynctask = new MyAsyncTask();
                    myasynctask.execute();

                }
                else {
                    aiService.startListening();
                }

                editText.setText("");

            }
        });

        editText.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) {
                ImageView fab_img = findViewById(R.id.fab_img);
                Bitmap img = BitmapFactory.decodeResource(getResources(),R.drawable.ic_send_white_24dp);
                Bitmap img1 = BitmapFactory.decodeResource(getResources(),R.drawable.ic_mic_white_24dp);


                if (s.toString().trim().length()!=0 && flagFab){
                    ImageViewAnimatedChange(MainActivity.this,fab_img,img);

                    flagFab=false;

                }
                else if (s.toString().trim().length()==0){
                    ImageViewAnimatedChange(MainActivity.this,fab_img,img1);
                    flagFab=true;

                }


            }

            @Override
            public void afterTextChanged(Editable s) {

            }


        });

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

        final FirebaseRecyclerAdapter<ChatMessage, chat_rec> adapter = new FirebaseRecyclerAdapter<ChatMessage, chat_rec>(options) {


            @NonNull
            @Override
            public chat_rec onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

                View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.msglist,parent,false);

                return new chat_rec(view);

            }


            @Override
            protected void onBindViewHolder(@NonNull chat_rec holder, int position, ChatMessage model) {

                if (model.getMsgUser().equals("user")) {

                    holder.rightText.setText(model.getMsgText());

                    holder.rightText.setVisibility(View.VISIBLE);
                    holder.leftText.setVisibility(View.GONE);
                }
                else {
                    holder.leftText.setText(model.getMsgText());

                    holder.rightText.setVisibility(View.GONE);
                    holder.leftText.setVisibility(View.VISIBLE);
                }

            }

        };

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

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

                if (lastVisiblePosition == -1 ||
                        (positionStart >= (msgCount - 1) &&
                                lastVisiblePosition == (positionStart - 1))) {
                    recyclerView.scrollToPosition(positionStart);

                }

            }
        });

        recyclerView.setAdapter(adapter);

    }//onCreate ends here


    public class MyAsyncTask extends AsyncTask<AIRequest,Void,AIResponse>{
        @Override
        protected AIResponse doInBackground(AIRequest... aiRequests) {
            try {
                final AIResponse response = aiDataService.request(aiRequest);
                return response;
            } catch (AIServiceException e) {
                System.out.print("Error in Aync Task. Please check!"+e);
            }
            return null;
        }
        @Override
        protected void onPostExecute(AIResponse response) {

            if (response != null) {

                Result result = response.getResult();
                String reply = result.getFulfillment().getSpeech();
                ChatMessage chatMessage = new ChatMessage(reply, "bot");
                ref.child("chat").push().setValue(chatMessage);
            }
        }
    }

    public void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) {
        final Animation anim_out = AnimationUtils.loadAnimation(c, R.anim.zoom_out);
        final Animation anim_in  = AnimationUtils.loadAnimation(c, R.anim.zoom_in);
        anim_out.setAnimationListener(new Animation.AnimationListener()
        {
            @Override public void onAnimationStart(Animation animation) {}
            @Override public void onAnimationRepeat(Animation animation) {}
            @Override public void onAnimationEnd(Animation animation)
            {
                v.setImageBitmap(new_image);
                anim_in.setAnimationListener(new Animation.AnimationListener() {
                    @Override public void onAnimationStart(Animation animation) {}
                    @Override public void onAnimationRepeat(Animation animation) {}
                    @Override public void onAnimationEnd(Animation animation) {}
                });
                v.startAnimation(anim_in);
            }
        });
        v.startAnimation(anim_out);
    }

    @Override
    public void onResult(ai.api.model.AIResponse response) {


        Result result = response.getResult();

        String message = result.getResolvedQuery();
        ChatMessage chatMessage0 = new ChatMessage(message, "user");
        Log.d("REQUEST",chatMessage0.toString());
        ref.child("chat").push().setValue("Request"+chatMessage0);


        String reply = result.getFulfillment().getSpeech();
        ChatMessage chatMessage = new ChatMessage(reply, "bot");

        Log.d("Reply",chatMessage.toString());
        ref.child("chat").push().setValue(chatMessage);


    }

    @Override
    public void onError(ai.api.model.AIError error) {

    }

    @Override
    public void onAudioLevel(float level) {

    }

    @Override
    public void onListeningStarted() {

    }

    @Override
    public void onListeningCanceled() {

    }

    @Override
    public void onListeningFinished() {

    }
}

基本上,我没有得到一个在我的前端聊天布局,其余所有代码都正常工作。为什么我得不到帮助


共 (1) 个答案

  1. # 1 楼答案

    请检查数据库的规则,以保存数据库中的值

    enter image description here

    因为这些值是动态添加的 为了测试应用程序的目的,您可以设置

    {
      "rules": {
        ".read": true,
        ".write": true
      }
    }
    

    不过,不建议这样做,因为任何人都可以读取或写入您的数据库。 欲了解更多信息,请访问 https://firebase.google.com/docs/database/android/read-and-write

    希望有帮助