gpt4 book ai didi

java - 无法使用来自用户和 DialogFlow(api.ai) 的对话填充我的 RecyclerView

转载 作者:行者123 更新时间:2023-11-29 23:22:48 25 4
gpt4 key购买 nike

我正在尝试使用 FirebaseDatabase 和 DialogFlow(api.ai) 构建一个 android 聊天机器人应用程序,并且我正在使用 RecyclerView 将消息加载到应用程序中。但是我无法将消息加载到应用程序中,每次运行该应用程序时它都会显示黑屏。

我已经尝试了 StackOverflow 上的所有建议答案,但我仍然无法将消息加载到应用程序中。

主 Activity

import ai.api.AIConfiguration;
import ai.api.AIListener;
import ai.api.AIServiceException;
import ai.api.android.AIDataService;
import ai.api.android.AIService;
import ai.api.model.AIError;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import ai.api.model.Result;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
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 java.util.List;
import java.util.Objects;


public class MainActivity extends AppCompatActivity implements AIListener{

RecyclerView recyclerView;
EditText editText;
RelativeLayout addBtn;
DatabaseReference ref;


private AIService aiService;
private Context context;


FirebaseRecyclerAdapter<ChatMessage, chat_rec>adapter;




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



recyclerView = findViewById(R.id.RecyclerView);
editText = findViewById(R.id.TEXT);
addBtn = findViewById(R.id.addBtn);
context = getApplicationContext();
recyclerView.setHasFixedSize(true);
final ai.api.android.AIConfiguration configuration = new ai.api.android.AIConfiguration("8c9665a53fba45d9a3015e0ba7330417", AIConfiguration.SupportedLanguages.English,

ai.api.android.AIConfiguration.RecognitionEngine.System);

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

final AIRequest aiRequest = new AIRequest();
final AIDataService aiDataService = new AIDataService(context, configuration);



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




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

addBtn.setOnClickListener(new View.OnClickListener() {
@SuppressLint("StaticFieldLeak")
@Override
public void onClick(View v) {

recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);





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

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

ref = FirebaseDatabase.getInstance().getReference().child("chat").push();

ChatMessage chatMessage = new ChatMessage(message, "user");
ref.child("chat").push().setValue(chatMessage);
ChatMessage model1 = new ChatMessage();
model1.setMessageUser(chatMessage.toString());
new AsyncTask<AIRequest, Void, AIResponse>() {


@Override
protected AIResponse doInBackground(AIRequest... aiRequests) {

final AIRequest request = aiRequests[0];
try {
final AIResponse response = aiDataService.request(aiRequest);
} catch (AIServiceException e) {
e.printStackTrace();
}

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);
}
}
}.execute(aiRequest);

} 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) {

}

@Override
public void afterTextChanged(Editable s) {

}
});




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



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

@Override
protected void onBindViewHolder(@NonNull final chat_rec holder, int i, @NonNull final ChatMessage model) {
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

if(Objects.requireNonNull(dataSnapshot.child("chat").getValue()).equals( model.getMessageUser())) {
holder.rightText.setText(model.getMessageText());
holder.rightText.setVisibility(View.VISIBLE);


}
else {
holder.leftText.setText(model.getMessageText());

holder.leftText.setVisibility(View.VISIBLE);

}

}

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

}






});



}


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

};



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);

}
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
}

@Override
public void onResult(AIResponse result) {
Result result1 = result.getResult();
String message = result1.getResolvedQuery();
ChatMessage chatMessage = new ChatMessage(message, "user");
ref.child("chat").push().setValue(chatMessage);

String reply = result1.getFulfillment().getSpeech();
ChatMessage chatMessage1 = new ChatMessage(reply,"bot");
ref.child("chat").push().setValue(chatMessage1);

}

@Override
public void onError(AIError error) {

}

@Override
public void onAudioLevel(float level) {

}

@Override
public void onListeningStarted() {

}

@Override
public void onListeningCanceled() {

}

@Override
public void onListeningFinished() {

}


}

有人可以让我知道我应该做哪些更改,以便我可以使它正常工作。

最佳答案

我找到了这个问题的替代解决方案。而不是填充 RecyclerView。可以创建两种不同的 xml 布局 - 机器人布局和用户布局。

机器人消息布局

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:paddingBottom="0dp">

<LinearLayout
android:id="@+id/botMsgLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|center_vertical"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="8dp"
android:background="@drawable/bot_bg_bubble"
android:gravity="start|center_vertical"
android:orientation="vertical">

<TextView
android:id="@+id/chatMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:fontFamily="@font/adamina"
android:lineSpacingExtra="1sp"
android:padding="12dp"
android:text="Hello There!"
android:textAlignment="viewStart"
android:textAllCaps="false"
android:textSize="18sp"
android:typeface="normal" />

<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp">

</FrameLayout>

</LinearLayout>
</FrameLayout>

用户消息布局

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp">

<LinearLayout
android:id="@+id/userMsgLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|center_vertical"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="8dp"
android:background="@drawable/user_bg_bubble"
android:gravity="end|center_vertical"
android:orientation="vertical">

<TextView
android:id="@+id/chatMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:padding="12dp"
android:text="Hello!"
android:textSize="18sp" />

<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp">

</FrameLayout>

</LinearLayout>
</FrameLayout>

现在,在 MainActivity 中根据需要使用 switch case 来扩充上述布局。

关于java - 无法使用来自用户和 DialogFlow(api.ai) 的对话填充我的 RecyclerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53980050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com