Open In App

How to Create a Chatbot in Android with BrainShop API?

Improve
Improve
Like Article
Like
Save
Share
Report

We have seen many apps and websites in which we will get to see a chatbot where we can chat along with the chatbot and can easily get solutions for our questions answered from the chatbot. In this article, we will take a look at building a chatbot in Android

https://www.youtube.com/watch?v=7_Cc36c7EW0

What we are going to build in this article? 

We will be building a simple application in which we will be building a simple chatbot where we can ask a question to our bot and the bot will answer our questions. Below is the video in which we will get to see what we are going to build in this article. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.  

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add the below dependency in your build.gradle file

Navigate to the app > Gradle Scripts > build.gradle file and add the below dependency to it in the dependencies section.  

implementation ‘com.android.volley:volley:1.1.1’

After adding this dependency sync your project and now move towards the AndroidManifest.xml part.  

Step 3: Adding permissions to the internet in the AndroidManifest.xml file

Navigate to the app > AndroidManifest.xml and add the below code to it. 

XML




<!--permissions for internet-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Step 4: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--recycler view to display our chats-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVChats"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/idLLMessage" />
 
    <LinearLayout
        android:id="@+id/idLLMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:weightSum="5">
 
        <!--edit text to enter message-->
        <EditText
            android:id="@+id/idEdtMessage"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:hint="Enter Message" />
 
        <!--button to send message-->
        <ImageButton
            android:id="@+id/idIBSend"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:background="@color/purple_200"
            android:src="@android:drawable/ic_menu_send"
            android:tint="@color/white" />
 
    </LinearLayout>
     
</RelativeLayout>


Step 5: Creating a Modal class for storing our messages

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as MessageModal and add the below code to it. Comments are added inside the code to understand the code in more detail.

Java




public class MessageModal {
 
    // string to store our message and sender
    private String message;
    private String sender;
 
    // constructor.
    public MessageModal(String message, String sender) {
        this.message = message;
        this.sender = sender;
    }
 
    // getter and setter methods.
    public String getMessage() {
        return message;
    }
 
    public void setMessage(String message) {
        this.message = message;
    }
 
    public String getSender() {
        return sender;
    }
 
    public void setSender(String sender) {
        this.sender = sender;
    }
}


Step 6: Creating a layout file for user messages

Icons used in this file are present in the drawable folder. Navigate to the app > res > layout > Right-click on it > New > layout resource file and name the file as user_msg and add the below code to it. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end"
    android:layout_margin="5dp"
    android:elevation="8dp"
    app:cardCornerRadius="8dp">
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <!--text view for displaying user message-->
        <TextView
            android:id="@+id/idTVUser"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_margin="5dp"
            android:padding="3dp"
            android:text="User message"
            android:textColor="@color/black" />
 
        <!--we are displaying user icon-->
        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_margin="10dp"
            android:src="@drawable/ic_user" />
         
    </LinearLayout>
 
</androidx.cardview.widget.CardView>


Step 7: Create a layout file for bot messages 

Icons used in this file are present in the drawable folder. Navigate to the app > res > layout > Right-click on it > New > layout resource file and name the file as bot_msg and add the below code to it. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="start"
    android:layout_margin="5dp"
    android:elevation="8dp"
    app:cardCornerRadius="8dp">
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <!--below widget is for image of bot-->
        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_margin="10dp"
            android:src="@drawable/ic_bot" />
 
        <!--below widget is for
            displaying message of bot-->
        <TextView
            android:id="@+id/idTVBot"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_margin="5dp"
            android:padding="3dp"
            android:text="Bot message"
            android:textColor="@color/black" />
         
    </LinearLayout>
 
</androidx.cardview.widget.CardView>


Step 8: Working with the Adapter class

For setting data to our items of Chat RecyclerView we have to create an Adapter class. Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as MessageRVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail. 

Java




import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
 
import java.util.ArrayList;
 
public class MessageRVAdapter extends RecyclerView.Adapter {
     
    // variable for our array list and context.
    private ArrayList<MessageModal> messageModalArrayList;
    private Context context;
 
    // constructor class.
    public MessageRVAdapter(ArrayList<MessageModal> messageModalArrayList, Context context) {
        this.messageModalArrayList = messageModalArrayList;
        this.context = context;
    }
 
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        // below code is to switch our
        // layout type along with view holder.
        switch (viewType) {
            case 0:
                // below line we are inflating user message layout.
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg, parent, false);
                return new UserViewHolder(view);
            case 1:
                // below line we are inflating bot message layout.
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg, parent, false);
                return new BotViewHolder(view);
        }
        return null;
    }
 
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        // this method is use to set data to our layout file.
        MessageModal modal = messageModalArrayList.get(position);
        switch (modal.getSender()) {
            case "user":
                // below line is to set the text to our text view of user layout
                ((UserViewHolder) holder).userTV.setText(modal.getMessage());
                break;
            case "bot":
                // below line is to set the text to our text view of bot layout
                ((BotViewHolder) holder).botTV.setText(modal.getMessage());
                break;
        }
    }
 
    @Override
    public int getItemCount() {
        // return the size of array list
        return messageModalArrayList.size();
    }
 
    @Override
    public int getItemViewType(int position) {
        // below line of code is to set position.
        switch (messageModalArrayList.get(position).getSender()) {
            case "user":
                return 0;
            case "bot":
                return 1;
            default:
                return -1;
        }
    }
 
    public static class UserViewHolder extends RecyclerView.ViewHolder {
         
        // creating a variable
        // for our text view.
        TextView userTV;
 
        public UserViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing with id.
            userTV = itemView.findViewById(R.id.idTVUser);
        }
    }
 
    public static class BotViewHolder extends RecyclerView.ViewHolder {
         
        // creating a variable
        // for our text view.
        TextView botTV;
 
        public BotViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing with id.
            botTV = itemView.findViewById(R.id.idTVBot);
        }
    }
}


Step 9: Generating API key for using the chatbot service

Go to Brainshop.ai generate your simple account with your username and password. Simply create your account on this website. After creating a new account you will get to see the below screen. After creating your account you have to request a new password from the request password option and enter your email address. After adding your email address you have to add the password to your account. Now we are good to go to generate our API key. 

Follow the above steps to Generate a new brain for your chatbot. After generating your bot now we will get the API URL for this brain. Navigate to the settings tab inside your created brain you will get to see your bot details as shown below.

Note: Now we will be using this API URL only inside the MainActivity.java file. 

Step 10: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
 
import org.json.JSONException;
import org.json.JSONObject;
 
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
 
    // creating variables for our
    // widgets in xml file.
    private RecyclerView chatsRV;
    private ImageButton sendMsgIB;
    private EditText userMsgEdt;
    private final String USER_KEY = "user";
    private final String BOT_KEY = "bot";
 
    // creating a variable for
    // our volley request queue.
    private RequestQueue mRequestQueue;
 
    // creating a variable for array list and adapter class.
    private ArrayList<MessageModal> messageModalArrayList;
    private MessageRVAdapter messageRVAdapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // on below line we are initializing all our views.
        chatsRV = findViewById(R.id.idRVChats);
        sendMsgIB = findViewById(R.id.idIBSend);
        userMsgEdt = findViewById(R.id.idEdtMessage);
 
        // below line is to initialize our request queue.
        mRequestQueue = Volley.newRequestQueue(MainActivity.this);
        mRequestQueue.getCache().clear();
 
        // creating a new array list
        messageModalArrayList = new ArrayList<>();
 
        // adding on click listener for send message button.
        sendMsgIB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking if the message entered
                // by user is empty or not.
                if (userMsgEdt.getText().toString().isEmpty()) {
                    // if the edit text is empty display a toast message.
                    Toast.makeText(MainActivity.this, "Please enter your message..", Toast.LENGTH_SHORT).show();
                    return;
                }
 
                // calling a method to send message
                // to our bot to get response.
                sendMessage(userMsgEdt.getText().toString());
 
                // below line we are setting text in our edit text as empty
                userMsgEdt.setText("");
            }
        });
 
        // on below line we are initializing our adapter class and passing our array list to it.
        messageRVAdapter = new MessageRVAdapter(messageModalArrayList, this);
 
        // below line we are creating a variable for our linear layout manager.
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);
 
        // below line is to set layout
        // manager to our recycler view.
        chatsRV.setLayoutManager(linearLayoutManager);
 
        // below line we are setting
        // adapter to our recycler view.
        chatsRV.setAdapter(messageRVAdapter);
    }
 
    private void sendMessage(String userMsg) {
        // below line is to pass message to our
        // array list which is entered by the user.
        messageModalArrayList.add(new MessageModal(userMsg, USER_KEY));
        messageRVAdapter.notifyDataSetChanged();
 
        // url for our brain
        // make sure to add mshape for uid.
        // make sure to add your url.
        String url = "Enter you API URL here" + userMsg;
 
        // creating a variable for our request queue.
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
 
        // on below line we are making a json object request for a get request and passing our url .
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    // in on response method we are extracting data
                    // from json response and adding this response to our array list.
                    String botResponse = response.getString("cnt");
                    messageModalArrayList.add(new MessageModal(botResponse, BOT_KEY));
                    
                    // notifying our adapter as data changed.
                    messageRVAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                     
                    // handling error response from bot.
                    messageModalArrayList.add(new MessageModal("No response", BOT_KEY));
                    messageRVAdapter.notifyDataSetChanged();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error handling.
                messageModalArrayList.add(new MessageModal("Sorry no response found", BOT_KEY));
                Toast.makeText(MainActivity.this, "No response from the bot..", Toast.LENGTH_SHORT).show();
            }
        });
         
        // at last adding json object
        // request to our queue.
        queue.add(jsonObjectRequest);
    }
}


Now run your app and see the output of the app. 

Output: 

Check out the project on the below link: https://github.com/ChinmayMunje/GFG-Bot



Last Updated : 21 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads