package com.kp.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.JsonObject;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;
public class MainActivity extends AppCompatActivity {
private EditText answerEditText;
private Button submitAnswerButton;
private TextView feedbackTextView;
private TextView questionTextView;
// OpenAI API Key (replace with your key)
private static final String OPENAI_API_KEY = "YOUR_OPENAI_API_KEY";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize UI elements
answerEditText = findViewById(R.id.answerEditText);
submitAnswerButton = findViewById(R.id.submitAnswerButton);
feedbackTextView = findViewById(R.id.feedbackTextView);
questionTextView = findViewById(R.id.questionTextView);
// Set sample question
questionTextView.setText("What is your understanding of Object-Oriented Programming?");
submitAnswerButton.setOnClickListener(v -> {
String answer = answerEditText.getText().toString();
if (!answer.isEmpty()) {
analyzeAnswer(answer); // Send answer to GPT model
}
});
}
private void analyzeAnswer(String answer) {
// Setup Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.openai.com/v1/chat/completions/")
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient.Builder().build())
.build();
// Create API Service
OpenAIApi openAIApi = retrofit.create(OpenAIApi.class);
// Prepare request body
JsonObject jsonBody = new JsonObject();
jsonBody.addProperty("model", "gpt-3.5-turbo-16k");
jsonBody.addProperty("prompt", "Analyze the following answer: " + answer);
jsonBody.addProperty("max_tokens", 100);
// Make API call
Call<JsonObject> call = openAIApi.analyzeAnswer("Bearer " + OPENAI_API_KEY, jsonBody);
call.enqueue(new retrofit2.Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, retrofit2.Response<JsonObject> response) {
if (response.isSuccessful() && response.body() != null) {
String feedback = response.body().get("choices").getAsJsonArray()
.get(0).getAsJsonObject().get("text").getAsString();
runOnUiThread(() -> feedbackTextView.setText(feedback));
} else {
runOnUiThread(() -> feedbackTextView.setText("Error in response!"));
}
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
runOnUiThread(() -> feedbackTextView.setText("Failed to analyze answer!"));
}
});
}
// Retrofit API interface
interface OpenAIApi {
@Headers({
"Content-Type: application/json"
})
@POST("v1/completions")
Call<JsonObject> analyzeAnswer(@retrofit2.http.Header("Authorization") String authHeader,
@Body JsonObject body);
}
}