What is causing "Error NetworkOnMainThreadException"?

Hi All

I am creating a simple Android Java program that calls Chat GPT using the API, and am just getting started. This error occurs at the getOutputStream() step.

Please find screenshots attached. I have searched the forums but did not find this issue discussed, and I asked Chat GPT but did not get any new suggestions. Please find screenshots attached.

Any help would be appreciated!

Thanks.

Please also find the entire MainActivity.java script here:

package com.example.chatgptapp01;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import kotlin.contracts.Returns;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String conversation;
    try {
        conversation = chatGPT("Hello, how are you?");
    } catch (IOException | JSONException e) {
        throw new RuntimeException(e);
    }

}

private String chatGPT(String s) throws IOException, JSONException {
    String url = "https://api.openai.com/v1/completions";
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();

    String API_KEY = "s*...deleted...*A";

    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Authorization", "Bearer " + API_KEY);

    JSONObject data = new JSONObject();
    data.put("model", "gpt-3.5-turbo-0301");
    data.put("prompt", s);
    data.put("max_tokens", 2000);
    data.put("temperature", 1.0);

    con.setDoOutput(true);
    Log.d("msg","up to here1");
    con.getOutputStream().write(data.toString().getBytes()); // failing here
    Log.d("msg","up to here2");

    String output = new BufferedReader(new InputStreamReader(con.getInputStream())).lines().reduce((a, b) -> a + b).get();

    System.out.println(new JSONObject(output).getJSONArray("choices").getJSONObject(0).getString("text"));
    return null;
}

}

1 Like