I’m not sure if I’m asking in the right place, if not don’t mind. I am trying to implement chatgpt in my android application (java).
ChatFragment.java
package com.uwv.apps.nadjinet1.fragments;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.uwv.apps.nadjinet1.R;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class ChatFragment extends Fragment {
private LinearLayout llChatContainer;
private EditText etMessage;
private Button continueButton;
private boolean isResponseReceived = false;
private boolean isResponseInterrupted = false;
private ImageButton sendButton;
private static final String OPENAI_API_KEY = "API-KEY";
private static final String OPENAI_API_URL = "https://api.openai.com/v1/chat/completions";
public static ChatFragment newInstance(int page, String title) {
ChatFragment fragment = new ChatFragment();
Bundle args = new Bundle();
args.putInt("page", page);
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
int page = getArguments().getInt("page");
String title = getArguments().getString("title");
// Ovde možete koristiti prosleđene vrednosti page i title kako želite
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chat, container, false);
llChatContainer = view.findViewById(R.id.llChatContainer);
etMessage = view.findViewById(R.id.etMessage);
sendButton = view.findViewById(R.id.sendButton);
continueButton = view.findViewById(R.id.continueButton);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
etMessage.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
continueButton.setVisibility(View.GONE);
}
}
});
continueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isResponseInterrupted = true;
continueButton.setVisibility(View.GONE);
etMessage.requestFocus();
}
});
return view;
}
private void sendMessage() {
String message = etMessage.getText().toString().trim();
if (!message.isEmpty()) {
addMessageToChatContainer("Vi: " + message, true);
showTypingIndicator();
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String requestBody = "{\"model\": \"gpt-3.5-turbo-0613\", \"messages\": [{\"role\": \"system\", \"content\": \"You are an AI Chat made by United Web Vision and you only speak Serbian.\"}, {\"role\": \"user\", \"content\": \"" + message + "\"}], \"max_tokens\": 3800}";
Request request = new Request.Builder()
.url(OPENAI_API_URL)
.post(RequestBody.create(mediaType, requestBody))
.header("Authorization", "Bearer " + OPENAI_API_KEY)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
addMessageToChatContainer("Greška GPT Preopterećen pokušajte ponovo.", false);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
try {
String responseBody = response.body().string();
JSONObject json = new JSONObject(responseBody);
JSONArray choicesArray = json.getJSONArray("choices");
JSONObject replyObject = choicesArray.getJSONObject(0);
String reply = replyObject.getJSONObject("message").getString("content");
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
replaceTypingIndicatorWithMessage("NadjiGPT: " + reply);
}
});
} catch (JSONException e) {
e.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
addMessageToChatContainer("Failed to parse response", false);
}
});
}
} else {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
addMessageToChatContainer("Greška GPT Preopterećen pokušajte ponovo.", false);
}
});
}
}
});
etMessage.setText("");
// Sakrivanje tastature
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etMessage.getWindowToken(), 0);
}
}
private void addMessageToChatContainer(String message, boolean isUserMessage) {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
int leftMargin = getResources().getDimensionPixelSize(R.dimen.bubble_left_margin);
int rightMargin = getResources().getDimensionPixelSize(R.dimen.bubble_right_margin);
int topMargin = getResources().getDimensionPixelSize(R.dimen.bubble_top_margin);
int bottomMargin = getResources().getDimensionPixelSize(R.dimen.bubble_bottom_margin);
layoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
TextView textView = new TextView(getActivity());
textView.setText(message);
textView.setTextColor(getResources().getColor(R.color.white));
textView.setBackgroundResource(isUserMessage ? R.drawable.bubble_user_background : R.drawable.bubble_ai_background);
textView.setLayoutParams(layoutParams);
textView.setPadding(16, 8, 16, 8);
textView.setGravity(isUserMessage ? Gravity.END : Gravity.START);
if (!isUserMessage) {
textView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Odgovor", textView.getText().toString());
clipboard.setPrimaryClip(clip);
showCopiedMessage();
return true;
}
});
}
llChatContainer.addView(textView);
scrollToBottom();
if (isUserMessage && !isResponseReceived && !isResponseInterrupted) {
continueButton.setVisibility(View.VISIBLE);
} else {
continueButton.setVisibility(View.GONE);
isResponseInterrupted = false;
}
}
private void showTypingIndicator() {
addMessageToChatContainer("Odgovaram...", false);
}
private void replaceTypingIndicatorWithMessage(String message) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
llChatContainer.removeViewAt(llChatContainer.getChildCount() - 1);
addMessageToChatContainer(message, false);
}
}, 500); // Delay for half a second to simulate typing
}
private void scrollToBottom() {
ScrollView scrollView = getActivity().findViewById(R.id.scrollView);
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
}, 100);
}
private void showCopiedMessage() {
Toast.makeText(getActivity(), "Poruka je kopirana", Toast.LENGTH_SHORT).show();
}
}
The problem is that when I ask him a more complex question, he fails to answer.