How to Build a ChatGPT Like App in Android using OpenAI API?
Last Updated :
24 Apr, 2025
Chat GPT is nowadays one of the famous AI tools which are like a chatbot. This chatbot answers all the queries which are sent to it. In this article, we will be building a simple ChatGPT-like android application by integrating the OpenAI API(ChatGPT) where we can ask any question and get an appropriate answer.
We have created a sample application and will take a look at its output of it and then we will proceed further to creating a new project in android studio.
Step-By-Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL.
// below line is used for volley library
implementation ‘com.android.volley:volley:1.2.0’
After adding this dependency sync your project and now move toward 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"/>
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:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/back_color"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/idTILQuery"
android:layout_alignParentTop="true"
android:layout_margin="5dp"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- text view for displaying question-->
<TextView
android:id="@+id/idTVQuestion"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
android:padding="4dp"
android:text="Question"
android:textColor="@color/white"
android:textSize="17sp" />
<!-- text view for displaying response-->
<TextView
android:id="@+id/idTVResponse"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:padding="4dp"
android:text="Response"
android:textColor="@color/white"
android:textSize="15sp" />
</LinearLayout>
</ScrollView>
<!-- text field for asking question-->
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/idTILQuery"
style="@style/TextInputLayoutStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_margin="5dp"
android:hint="Enter your query"
android:padding="5dp"
android:textColorHint="@color/white"
app:hintTextColor="@color/white">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/idEdtQuery"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/edt_back_color"
android:drawableEnd="@drawable/ic_send"
android:drawableTint="@color/white"
android:ems="10"
android:imeOptions="actionSend"
android:importantForAutofill="no"
android:inputType="textEmailAddress"
android:textColor="@color/white"
android:textColorHint="@color/white"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
</RelativeLayout>
Step 5: Generating bearer token for using the API.
Navigate to the below URL and simply sign up with your email and password. On this screen click on Create a new secret key to generate your new key. Once your key is generated that we have to use it as a token for making our API key.
Step 6: Working with MainActivity.kt file.
Navigate to app > java > your app's package name > MainActivity.kt file and add the below code to it. Comments are added in the code to get to know it in detail.
Kotlin
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import android.widget.TextView.OnEditorActionListener
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.RetryPolicy
import com.android.volley.VolleyError
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.textfield.TextInputEditText
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
// creating variables on below line.
lateinit var responseTV: TextView
lateinit var questionTV: TextView
lateinit var queryEdt: TextInputEditText
var url = "https://api.openai.com/v1/completions"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// initializing variables on below line.
responseTV = findViewById(R.id.idTVResponse)
questionTV = findViewById(R.id.idTVQuestion)
queryEdt = findViewById(R.id.idEdtQuery)
// adding editor action listener for edit text on below line.
queryEdt.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEND) {
// setting response tv on below line.
responseTV.text = "Please wait.."
// validating text
if (queryEdt.text.toString().length > 0) {
// calling get response to get the response.
getResponse(queryEdt.text.toString())
} else {
Toast.makeText(this, "Please enter your query..", Toast.LENGTH_SHORT).show()
}
return@OnEditorActionListener true
}
false
})
}
private fun getResponse(query: String) {
// setting text on for question on below line.
questionTV.text = query
queryEdt.setText("")
// creating a queue for request queue.
val queue: RequestQueue = Volley.newRequestQueue(applicationContext)
// creating a json object on below line.
val jsonObject: JSONObject? = JSONObject()
// adding params to json object.
jsonObject?.put("model", "text-davinci-003")
jsonObject?.put("prompt", query)
jsonObject?.put("temperature", 0)
jsonObject?.put("max_tokens", 100)
jsonObject?.put("top_p", 1)
jsonObject?.put("frequency_penalty", 0.0)
jsonObject?.put("presence_penalty", 0.0)
// on below line making json object request.
val postRequest: JsonObjectRequest =
// on below line making json object request.
object : JsonObjectRequest(Method.POST, url, jsonObject,
Response.Listener { response ->
// on below line getting response message and setting it to text view.
val responseMsg: String =
response.getJSONArray("choices").getJSONObject(0).getString("text")
responseTV.text = responseMsg
},
// adding on error listener
Response.ErrorListener { error ->
Log.e("TAGAPI", "Error is : " + error.message + "\n" + error)
}) {
override fun getHeaders(): kotlin.collections.MutableMap<kotlin.String, kotlin.String> {
val params: MutableMap<String, String> = HashMap()
// adding headers on below line.
params["Content-Type"] = "application/json"
params["Authorization"] =
"Bearer Enter your token here"
return params;
}
}
// on below line adding retry policy for our request.
postRequest.setRetryPolicy(object : RetryPolicy {
override fun getCurrentTimeout(): Int {
return 50000
}
override fun getCurrentRetryCount(): Int {
return 50000
}
@Throws(VolleyError::class)
override fun retry(error: VolleyError) {
}
})
// on below line adding our request to queue.
queue.add(postRequest)
}
}
Output:
Similar Reads
How to Make a Joke App in Android Using API Call?
Jokes are the best way to keep the face smiling. With the power of technology, we can create apps that provide instant access to a broad Category(i.e. animal, money, career, dev etc ) of jokes at any time. In this article, we will create a Joke App in Android that uses API calls to fetch jokes from
7 min read
How to Build a Book Library App using Google Books API in Android?
If you are looking for building a book library app and you want to load a huge data of books then for adding this feature, you have to use a simple API which is provided by Google, and of course, it's free. In this article, we will take a look at the implementation of this API in our Android App. Wh
15+ min read
How to Make an Motivational Quotes App in Android using API Call?
In this article, we will see the process of building a Motivational Quotes App for Android that fetches random quotes from an API and displays them to the user. By the end of this article, we will have a Complete Android application that connects to an API, retrieves motivational quotes and author n
5 min read
How to Build a ChatGPT Like Image Generator Application in Android?
Chat GPT is nowadays one of the famous AI tools which are like a chatbot. This chatbot answers all the queries which are sent to it. In this article, we will be building a simple ChatGPT-like android application in which we will be able to ask any question and from that question, we will be able to
5 min read
How to Build Live Train Status App in Android?
Imagine you are traveling via Indian railways which is one of the biggest rail networks in the world. You want to get real-time updates for the train on which you are traveling so that you can plan accordingly. In this article, we will take a look at How to build a live train status checker applicat
8 min read
How to Add Memes Using API Call in Android?
Application Programming Interface calling is the process of making requests to external web-based services to retrieve or manipulate data. APIs provide a standardized way for different software applications to communicate with each other. It involves sending a request from one application to another
4 min read
How to Build a Simple Note Android App using MVVM and Room Database?
Android provides us a feature with which we can store users' data inside their mobile itself with different storage options such as Shared Preferences, SQLite database, and the Room Database. All the data storing techniques are having different use cases. In this article, we will specifically take a
15+ min read
How to Build a Palindrome Checker App in Android Studio?
In this article, we will be building a Palindrome Checker android app in Android Studio using Java/Kotlin and XML. The app will check whether the entered word is Palindrome or not, if the entered word is a Palindrome then a toast will be displayed having the message "Yes, it's a palindrome" otherwis
3 min read
How to Build a Simple Contact List Android App using MVVM and Room Database?
A contact list app is a great tool to store and manage our contacts in one place. With the rise of smartphones and mobile devices, contact list apps have become increasingly popular. In this article, we will explore the development of a contact list app using Kotlin, Room Database, and MVVM architec
7 min read
How to Build a Simple Voice Typer App in Android using Java?
Pre-requisites: Android App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioHow to Create/Start a New Project in Android Studio?Running your first Android appSpinner in AndroidRecognizerIntent in Android In this article, we are going to build a simple Voice Typer app
5 min read