腾讯公益赛个人冲刺博客18(2024.6.6)

解决网络错误后出现格式错误,但是在网上查了办法不报错但仍然不能运行,加了监听器后重写了消息显示部分的代码

package com.example.helppeople;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.helppeople.adapter.ChatAdapter;
import com.example.helppeople.entity.ChatBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Soul extends AppCompatActivity {

    private ListView listView;
    private ChatAdapter adapter;
    private List<ChatBean> chatBeanList;
    private EditText et_send_msg;
    private Button btn_send;
    private static final String WEB_SITE = "http://openapi.turingapi.com/openapi/api/v2";
    private static final String KEY = "d92360dbde634e89b5f7c4c8e5fa1ee6";
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private String sendMsg;
    private String welcome[];
    private MHandler mHandler;
    public static final int MSG_OK = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_soul);
        chatBeanList = new ArrayList<>();
        mHandler = new MHandler();
        welcome = getResources().getStringArray(R.array.welcome);
        initView();
    }

    private void initView() {
        listView = findViewById(R.id.list);
        et_send_msg = findViewById(R.id.et_send_msg);
        btn_send = findViewById(R.id.btn_send);
        adapter = new ChatAdapter(chatBeanList, this);
        listView.setAdapter(adapter);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendData();
            }
        });
        et_send_msg.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    sendData();
                    return true;
                }
                return false;
            }
        });
        int position = (int) (Math.random() * welcome.length);
        showData(welcome[position]);
    }

    private void sendData() {
        sendMsg = et_send_msg.getText().toString().trim();
        if (TextUtils.isEmpty(sendMsg)) {
            Toast.makeText(this, "您还未输入任何信息哦", Toast.LENGTH_LONG).show();
            return;
        }
        et_send_msg.setText("");
        ChatBean chatBean = new ChatBean();
        chatBean.setMessage(sendMsg);
        chatBean.setState(ChatBean.SEND);
        chatBeanList.add(chatBean);
        adapter.notifyDataSetChanged();
        getDataFromServer(); // 调用获取数据的方法
    }

    private void getDataFromServer() {
        OkHttpClient okHttpClient = new OkHttpClient();
        JSONObject json = new JSONObject();
        try {
            json.put("reqType", 0); // 设置请求类型,0为文本类型
            json.put("perception", new JSONObject().put("inputText", new JSONObject().put("text", sendMsg)));
            json.put("userInfo", new JSONObject().put("apiKey", KEY).put("userId", "123456"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(JSON, json.toString());
        Request request = new Request.Builder().url(WEB_SITE).post(requestBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                showData("网络请求失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Message msg = new Message();
                msg.what = MSG_OK;
                msg.obj = res;
                mHandler.sendMessage(msg);
            }
        });
    }

    class MHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_OK:
                    if (msg.obj != null) {
                        String vlResult = (String) msg.obj;
                        parseData(vlResult);
                    }
                    break;
            }
        }
    }

    private void parseData(String jsonData) {
        try {
            JSONObject obj = new JSONObject(jsonData);
            if (obj.has("results")) {
                // 提取有效的回复内容
                JSONObject resultObject = obj.getJSONArray("results").getJSONObject(0);
                String content = resultObject.getJSONObject("values").getString("text");
                // 显示有效的回复内容
                showData(content);
            } else {
                // 如果没有找到有效的回复内容,显示默认提示
                showData("未找到有效的回复内容");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            showData("主人,你的网络不好哦");
        }
    }

    private void showData(String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ChatBean chatBean = new ChatBean();
                chatBean.setMessage(message);
                chatBean.setState(ChatBean.RECEIVE);
                chatBeanList.add(chatBean);
                adapter.notifyDataSetChanged();
            }
        });
    }
}

 

posted @ 2024-06-12 08:22  记得关月亮  阅读(11)  评论(0)    收藏  举报