API CLIENT
package com.example.chatgpttest;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
private static final String BASE_URL = "https://api.openai.com/v1/";
public static OpenAIApi getApiService() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // Log request and response bodies
// Create OkHttp client with interceptor
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor) // Add the logging interceptor
.addInterceptor(chain -> {
Request request = chain.request().newBuilder()
.addHeader("Authorization", "Bearer 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") // Replace with your actual API key
.build();
return chain.proceed(request);
})
.build();
// Build Retrofit instance
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
// Return the API service
return retrofit.create(OpenAIApi.class);
}
}
Chat Request:
package com.example.chatgpttest;
import java.util.List;
// Request model
public class ChatRequest {
private String model;
private List<Message> messages;
public ChatRequest(String model, List<Message> messages) {
this.model = model;
this.messages = messages;
}
public String getModel() {
return model;
}
public List<Message> getMessages() {
return messages;
}
// Getters and Setters
}
Chat Response
package com.example.chatgpttest;
import java.util.List;
import com.example.chatgpttest.Choice;
// Response model
public class ChatResponse {
private List<Choice> choices;
public List<Choice> getChoices() {
return choices;
}
public void setChoices(List<Choice> choices) {
this.choices = choices;
}
}
Choice
package com.example.chatgpttest;
public class Choice {
private Message message;
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
}
Fragment Chat xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/inputText"
android:layout_width="match_parent"
android:layout_height="50dp"
android:autofillHints="emailAddress"
android:inputType="text"
android:hint="@string/hint_enter_message"/>
<Button
android:id="@+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send_button_text" />
<TextView
android:id="@+id/responseText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/response_placeholder"
android:paddingTop="16dp" />
</LinearLayout>
Chat Fragment.java
package com.example.chatgpttest;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import retrofit2.Call;
import retrofit2.Response;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class ChatFragment extends Fragment {
private EditText inputText;
private TextView responseText;
private Button sendButton;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chat, container, false);
// Initialize UI elements
inputText = view.findViewById(R.id.inputText);
responseText = view.findViewById(R.id.responseText);
sendButton = view.findViewById(R.id.sendButton);
// Ensure UI components are not null
if (inputText == null || responseText == null || sendButton == null) {
Log.e("ChatFragment", "UI elements not properly initialized");
return view;
}
// Set up click listener for the send button
sendButton.setOnClickListener(v -> {
String userMessage = inputText.getText().toString();
if (!userMessage.isEmpty()) {
sendMessageToApi(userMessage); // Call API when button is clicked
} else {
Log.e("ChatFragment", "User input is empty");
responseText.setText("Please enter a message.");
}
});
return view;
}
// Method to send message to ChatGPT API
public void sendMessageToApi(String userMessage) {
Log.d("ChatFragment", "Sending message to API: " + userMessage);
// Create a message list with the user input
List<Message> messages = new ArrayList<>();
messages.add(new Message("user", userMessage));
// Create ChatRequest object
ChatRequest chatRequest = new ChatRequest("gpt-3.5-turbo", messages);
// Get the API service
OpenAIApi apiService = ApiClient.getApiService();
Log.d("ChatFragment", "Making API call with request: " + chatRequest.getMessages().get(0).getContent());
try {
Call<ChatResponse> call = apiService.getChatResponse(chatRequest);
Response<ChatResponse> response = call.execute(); // Synchronous call
// Log entire response object
Log.d("ChatFragment", "Response received: " + response.toString());
if (response.isSuccessful() && response.body() != null) {
ChatResponse chatResponse = response.body();
// Log entire body to see if something is wrong
Log.d("ChatFragment", "Response body: " + chatResponse.toString());
if (chatResponse.getChoices() != null && !chatResponse.getChoices().isEmpty()) {
Message message = chatResponse.getChoices().get(0).getMessage();
if (message != null && message.getContent() != null) {
String gptResponse = message.getContent();
Log.d("ChatFragment", "API Success: " + gptResponse);
responseText.setText(gptResponse); // Update UI with response
} else {
Log.e("ChatFragment", "API Success but message content is null");
responseText.setText("Received a response, but the content is null.");
}
} else {
Log.e("ChatFragment", "API Success but choices are null or empty");
responseText.setText("Received a response, but choices are null or empty.");
}
} else {
// Handle error response
Log.e("ChatFragment", "API Error: " + response.code() + " - " + response.message());
if (response.errorBody() != null) {
Log.e("ChatFragment", "Error body: " + response.errorBody().string());
}
responseText.setText("Failed to get a response. Error code: " + response.code());
}
} catch (Exception e) {
Log.e("ChatFragment", "API Failure: " + e.getMessage());
responseText.setText("Network error: " + e.getMessage());
}
Activity main xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="414dp"
android:layout_height="685dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/openChatButton" />
<Button
android:id="@+id/openChatButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="1dp"
android:text="Open Chat"
app:layout_constraintBottom_toTopOf="@+id/fragment_container"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Main activity java
package com.example.chatgpttest;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Load the ChatFragment when the activity is created
loadFragment(new ChatFragment());
}
// Method to load fragments into the activity
private void loadFragment(Fragment fragment) {
// Use FragmentManager to begin a fragment transaction
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Replace the content in the activity_main layout with the ChatFragment
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit(); // Commit the transaction
}
}
Message java
package com.example.chatgpttest;
public class Message {
private String role;
private String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
// Getter for content
public String getContent() {
return content;
}
public void setRole(String role) {
this.role = role;
}
public String getRole() {
return role;
}
public void setContent(String content) {
this.content = content;
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ChatGptTest"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>