Intelligent chatbot project developed by Android Studio

Table of contents

I. Introduction       

2. Preparation

3. Detailed design and implementation

1.Start page

2. Log in to the registration page

3.Chat page

4. You also need to create a class: ChatBean

At this point, a simple chatbot is completed. Let’s take a look at the final effect video:

Conclusion


I. Introduction       

       In today's rapidly developing technological era, artificial intelligence has become a hot topic. With the continuous development of artificial intelligence technology, more and more application scenarios are paying attention to developers, and intelligent chatbots are one of them.

      This article will introduce how to use Android Studio to develop an intelligent chatbot project. We will use Android Studio, JAVA language, JDK1.8, database Sqlite.

     The video effects are placed at the end.

     This design contains a total of four pages: startup page, login page, registration page, and chat page. The rendering is as follows:

2. Preparation

1. You need to find a robot’s API interface yourself.

2. Prepare image materials yourself

3. Detailed design and implementation

1.Start page

(1) Use the `handler.postDelayed()` method to delay the execution of a `runnable` for three seconds. The purpose of this `runnable` is to start `LoginActivity` after three seconds.

(2) Use the `CountDownTimer` class to create a timer `timeCount` with a total duration of 4 seconds and execute it once every second. Its function is to remove the `handler` waiting for execution in the `onFinish()` method. runnable` to avoid unnecessary errors.

        It should be noted that all pending operations should be canceled in the `onPause()` method to avoid causing unknown problems when the program is closed or running in the background.

The code looks like this:

// 进入主页面
    private void tomainActive() {
        startActivity(new Intent(this, LoginActivity.class));
        // 跳转完成后注销
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        // 1.延迟三秒执行 runnable
        handler.postDelayed(runnable, 3000);
        // 2.初始化,共执行四秒,一秒执行一次
        timeCount = new TimeCount(4000, 1000);
        timeCount.start();
    }


    // 计时器
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }


        @Override
        public void onFinish() {
            // 结束之后移除runnable(进入主页)
            handler.removeCallbacks(runnable);
        }
    }

2. Log in to the registration page

(1) Created a `DatabaseHelper` object named `mDatabaseHelper`, which is used to manage the local database of the application.

(2) Use the `findViewById` method to find the registered button and set the `OnClickListener` listener to perform the corresponding operation when the user clicks the button. In this listener, obtain the account number and password entered by the user through `mUserNameEditText` and `mPasswordEditText`, and write them into the local database.

(3) Create a control named `loginRegister` and set the `OnClickListener` listener. This listener is used to initiate registration activity if the user has not yet registered an account.

(4) Use the `findViewById` method to find the login button and set the `OnClickListener` listener to perform the corresponding operation when the user clicks the button. In this listener, obtain the username and password entered by the user through the input box, and if the user's account has been registered in the local database, transfer the user to `RobotActivity`. Otherwise, a Toast prompt of "Incorrect account or password" will be displayed.

       It is important to note that the `DatabaseHelper` used in the code is definitely customized for this application, and the specific details may vary.

The code looks like this:

   mDatabaseHelper = new DatabaseHelper(this);

        Button registerButton = findViewById(R.id.register_button);
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = mUserNameEditText.getText().toString().trim();
                String password = mPasswordEditText.getText().toString().trim();

                if (username.isEmpty() || password.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "请输入账号或密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                boolean result = mDatabaseHelper.insertData(username, password);
                if (result) {
                    Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), "注册失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
  loginRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = user.getText().toString().trim();
                String password = pass.getText().toString().trim();

                if (username.isEmpty() || password.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "请输入账号或密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                boolean result = mDatabaseHelper.checkUser(username, password);
                if (result) {
                    Toast.makeText(getApplicationContext(), "登陆成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LoginActivity.this, RobotActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(getApplicationContext(), "账号或密码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

3.Chat page

(1) Create a button named `btn_send` and set the `OnClickListener` listener to perform the corresponding action when the user clicks it. In this listener, the information entered by the user is obtained and added to a `ChatBean` object, then the object is added to the `chatBeanList` collection, and finally the list is updated.

(2) Created an input box named `et_send_msg`, and set the `OnKeyListener` listener for it so that information can be sent when the user presses the Enter key.

(3) Created a `private void getDataFromServer()` method, which uses the OkHttp library to send a GET request to the server in order to obtain the reply information sent by the robot from the server.

(4) In the `getDataFromServer()` method, use the Callback callback function to process the response result of the network request. When the request is successful, the response result is encapsulated into a `Message` object and sends the message to `mHandler` so that it can be displayed in the UI Update the chat content list in the thread.

       It should be noted that in the chatbot application implemented by the above code, the specific details of sending a request to the server and receiving a response from the server may vary between different implementations, such as request address, request parameters, and server return value. Format, etc., developers should modify it themselves according to specific needs.

The code looks like this:

  btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                sendData();//点击发送按钮,发送信息
            }
        });
        et_send_msg.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() ==
                        KeyEvent.ACTION_DOWN) {
                    sendData();//点击Enter键也可以发送信息
                }
                return false;
            }
        });
        int position = (int) (Math.random() * welcome.length - 1); //获取一个随机数
        showData(welcome[position]); //用随机数获取机器人的首次聊天信息
    }
    private void sendData() {
        sendMsg = et_send_msg.getText().toString(); //获取你输入的信息
        if (TextUtils.isEmpty(sendMsg)) {             //判断是否为空
            Toast.makeText(this, "您还未输任何信息哦", Toast.LENGTH_LONG).show();
            return;
        }
        et_send_msg.setText("");
        //替换空格和换行
        sendMsg = sendMsg.replaceAll(" ", "").replaceAll("\n", "").trim();
        ChatBean chatBean = new ChatBean();
        chatBean.setMessage(sendMsg);
        chatBean.setState(chatBean.SEND); //SEND表示自己发送的信息
        chatBeanList.add(chatBean);        //将发送的信息添加到chatBeanList集合中
        adpter.notifyDataSetChanged();    //更新ListView列表
        getDataFromServer();                //从服务器获取机器人发送的信息
    }
    private void getDataFromServer() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(WEB_SITE + "?key=" + KEY + "&appid=0&msg="
                + sendMsg).build();
        Call call = okHttpClient.newCall(request);
        // 开启异步线程访问网络
        call.enqueue(new Callback() {
            @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);
            }
            @Override
            public void onFailure(Call call, IOException e) {
            }
        });
    }

4. You also need to create a class: ChatBean

       This code defines a JavaBean class called `ChatBean` that encapsulates every message sent or received in the chat application.

(1) Two static variables `SEND` and `RECEIVE` are defined, representing the sent and received messages respectively.

(2) A member variable named `state` is defined to identify the message status (that is, whether to send or receive).

(3) A member variable named `message` is defined to save the specific content of the message.

(4) A method named `getState()` is defined to obtain the status of the message.

(5) A method named `setState()` is defined to set the status of the message.

(6) A method named `getMessage()` is defined to obtain the content of the message.

(7) A method named `setMessage()` is defined for setting the content of the message.

       As the data type of each row in `ListView`, this class is responsible for encapsulating and displaying messages sent and received by users. The `state` attribute is used to distinguish whether a message is sent or received, and the `message` attribute is used to save the specific content of the message.

      It should be noted that this class only defines member variables and related methods, and does not perform actual operations on them. The actual operations need to be performed in other parts of the application.

The code looks like this:

class ChatBean {
    public static final int SEND = 1;     //发送消息
    public static final int RECEIVE = 2; //接收到的消息
    private int state;       //消息的状态(是接收还是发送)
    private String message; //消息的内容
    public int getState() {
        return state;
    }
    public void setState(int state) {
        this.state = state;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

At this point, a simple chatbot is completed. Let’s take a look at the final effect video:

chatbot

Conclusion

        This simple chatbot application uses the OkHttp library and the GSON library to send requests to the server and receive responses from the server, allowing users to chat and interact with the robot. In this application,  ChatBean the class that encapsulates message data acts as the deliverer of message data, responsible for encapsulating and displaying messages sent and received by users, while the  DatabaseHelper class is responsible for managing the local database and saving user registration information. In this way, the application fully embodies the idea of ​​object-oriented programming, encapsulating different business logic modules into different classes for processing.

       In addition, the application also implements filtering and replacing spaces and line breaks for user-entered content to ensure the accuracy and cleanliness of chat data. It also implements functions when users do not fill in complete information. The function of prompting at any time improves the user experience.

       In short, through the implementation of this simple chatbot application, we have a deeper understanding of the development life cycle of Android applications, and we have richer practices in using the OkHttp library and GSON library for network requests and data processing. experience. In future development, we will use this application as a basis to further expand and improve it to make it more practical and user-friendly.

Guess you like

Origin blog.csdn.net/qq_29823791/article/details/131351633