1

我正在使用 arraylist 和 Watson Conversation API 做一个聊天机器人,以在用户输入消息后获取机器人响应。用户将输入一些消息,机器人 API 将根据用户输入显示响应。当用户输入已在 Watson API 中设置的内容时,不会出现错误。但是,当用户键入机器人无法理解的消息时,就会出现此错误。

我不确定如何重组代码来解决这个问题。我希望有人可以帮助并告诉我该怎么做。提前谢谢你!:(

public class BotActivity extends AppCompatActivity {

    private static final String TAG = "BotActivity";
    private String userText;

    private EditText userInput;
    private LinearLayout welcomeText;

    private ArrayList<String> imageList = new ArrayList<>();
    private ArrayList<String> nameList = new ArrayList<>();

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

        userInput = (EditText) findViewById(R.id.input);
        welcomeText = (LinearLayout) findViewById(R.id.centerLayout);

        addItems();
    }

    private void addItems() {

        userInput.setImeOptions(userInput.getImeOptions() | EditorInfo.IME_ACTION_DONE);
        userInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_DONE) {

                    welcomeText.setVisibility(View.GONE);
                    titleView.setVisibility(View.GONE);
                    userText = userInput.getText().toString().trim();
                    nameList.add(userText);
                    imageList.add("https://i.pinimg.com/originals/99/7c/90/997c901be018004a07d66ae4920fd3a6.png");
                    userInput.setText("");

                    setRecyclerView();

                    final ConversationService myConversationService = new ConversationService(
                            "2017-05-26",
                            getString(R.string.username),
                            getString(R.string.password)
                    );

                    MessageRequest request = new MessageRequest.Builder().inputText(userText).build();

                    myConversationService.message(getString(R.string.workspace), request)
                            .enqueue(new ServiceCallback<MessageResponse>() {
                                @Override
                                public void onResponse(MessageResponse response) {

                                    final String outputText = response.getText().get(0);

                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            nameList.add(outputText);
                                            imageList.add("http://4.bp.blogspot.com/-fGmmzMLA4zw/VLSHyleQbXI/AAAAAAAAODw/YevIrHiSJ7o/s1600/blushicon.png");
                                            setRecyclerView();
                                        }
                                    });

                                    if (response.getIntents().get(0).getIntent().endsWith("RequestQuote")) {

                                        String quotesURL = "https://api.forismatic.com/api/1.0/" + "?method=getQuote&format=text&lang=en";

                                        Fuel.INSTANCE.get(quotesURL, null).responseString(new Handler<String>() {
                                            @Override
                                            public void success(String quote) {

                                                nameList.add(quote);
                                                imageList.add("http://4.bp.blogspot.com/-fGmmzMLA4zw/VLSHyleQbXI/AAAAAAAAODw/YevIrHiSJ7o/s1600/blushicon.png");
                                                setRecyclerView();
                                            }

                                            @Override
                                            public void failure(@NotNull FuelError fuelError) {
                                                Toast.makeText(BotActivity.this, fuelError.toString(), Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    }
                                }

                                @Override
                                public void onFailure(Exception e) {
                                    Log.e(TAG, e.toString());
                                }
                            });
                }
                return false;
            }
        });
    }

    private void setRecyclerView() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);
        BotAdapter adapter = new BotAdapter(this, nameList, imageList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
}

这是机器人适配器的编码:

public class BotAdapter extends RecyclerView.Adapter<BotAdapter.ViewHolder> {

    private static final String TAG = "BotAdapter";
    private ArrayList<String> messageList = new ArrayList<>();
    private ArrayList<String> profileImageList = new ArrayList<>();
    private Context context;
    private JumpingBeans jumpingBeans;

    public BotAdapter(Context context, ArrayList<String> nameList, ArrayList<String> imageList) {
        this.messageList = nameList;
        this.profileImageList = imageList;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.single_bot_layout, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {

        Glide.with(context)
                .asBitmap()
                .load(profileImageList.get(i))
                .into(viewHolder.showProfileImage);

        viewHolder.showMessage.setText(messageList.get(i));
        viewHolder.showMessage.setTextIsSelectable(true);

        viewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // click on recycler items action
                // Toast.makeText(context, messageList.get(i), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private TextView showMessage;
        private CircleImageView showProfileImage;
        private RelativeLayout parentLayout;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            showMessage = itemView.findViewById(R.id.showMessage);
            showProfileImage = itemView.findViewById(R.id.showImage);
            parentLayout = itemView.findViewById(R.id.list_single_layout);

        }
    }
}


错误:

05-05 11:47:24.826 9840-9994/com.amethyst.secretgarden D/OkHttp: --> POST https://gateway.watsonplatform.net/conversation/api/v1/workspaces/7e18adc0-c6db-4897-a83c-17c788db377e/message?version=2017-05-26 http/1.1 (27-byte body)
05-05 11:47:25.076 9840-9994/com.amethyst.secretgarden D/OkHttp: <-- 200 OK https://gateway.watsonplatform.net/conversation/api/v1/workspaces/7e18adc0-c6db-4897-a83c-17c788db377e/message?version=2017-05-26 (245ms, unknown-length body)
05-05 11:47:25.076 9840-9994/com.amethyst.secretgarden E/BotActivity: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
05-05 11:47:25.656 9840-9840/com.amethyst.secretgarden D/OppoEditor: OppoEditor, classname = android.support.v7.widget.AppCompatTextView,packageName = com.amethyst.secretgarden
05-05 11:47:25.716 9840-9840/com.amethyst.secretgarden D/OppoEditor: OppoEditor, classname = android.support.v7.widget.AppCompatTextView,packageName = com.amethyst.secretgarden
05-05 11:47:25.736 9840-9840/com.amethyst.secretgarden D/OppoEditor: OppoEditor, classname = android.support.v7.widget.AppCompatTextView,packageName = com.amethyst.secretgarden
05-05 11:47:25.736 9840-9840/com.amethyst.secretgarden D/OppoEditor: OppoEditor, classname = android.support.v7.widget.AppCompatTextView,packageName = com.amethyst.secretgarden
05-05 11:47:25.736 9840-9840/com.amethyst.secretgarden D/OppoEditor: OppoEditor, classname = android.support.v7.widget.AppCompatTextView,packageName = com.amethyst.secretgarden
05-05 11:47:30.526 9840-9855/com.amethyst.secretgarden I/art: Background sticky concurrent mark sweep GC freed 92796(5MB) AllocSpace objects, 0(0B) LOS objects, 23% free, 18MB/24MB, paused 1.611ms total 273.636ms
05-05 11:47:38.986 9840-10155/com.amethyst.secretgarden V/FA: Recording user engagement, ms: 85341
05-05 11:47:38.996 9840-10155/com.amethyst.secretgarden V/FA: Connecting to remote service
05-05 11:47:39.076 9840-10155/com.amethyst.secretgarden V/FA: Activity paused, time: 14744243
05-05 11:47:39.116 9840-10155/com.amethyst.secretgarden D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=85341, firebase_screen_class(_sc)=BotActivity, firebase_screen_id(_si)=6871416413478563474}]
05-05 11:47:39.276 9840-10155/com.amethyst.secretgarden V/FA: Connection attempt already in progress
05-05 11:47:39.276 9840-10155/com.amethyst.secretgarden D/FA: Connected to remote service
05-05 11:47:39.276 9840-10155/com.amethyst.secretgarden V/FA: Processing queued up service tasks: 2
05-05 11:47:39.286 9840-9840/com.amethyst.secretgarden W/InputMethodManager: startInputInner : InputBindResult == null need restart
05-05 11:47:39.306 9840-9840/com.amethyst.secretgarden W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
4

0 回答 0