0

I have a method in an Android app that should execute a URL. But I always get a NetworkOnMainThreadException, because I am not allowed to run it on the mainthread. On the net I found many different ways to solve this problem. Unfortunately, I'm still quite new to Java and don't know much about it.

The app has a button which executes a URL when pressed.

Java

package com.softpi.raspbicontroll;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class MainActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle saveInstanceState){
        super.onCreate(saveInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void doYellow(View view) {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("http://raspberrypi/yellow.php");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            readStream(in);
        } 
        catch (Exception e) {
            System.out.println("Shit!");
            e.printStackTrace();
        } finally {
            assert urlConnection != null;
            urlConnection.disconnect();
        }

    }

    private static void readStream(InputStream in) {}

}

XML

<Button
    ...
    android:onClick="doYellow"
    ...
    app:layout_constraintTop_toTopOf="parent" />

Can someone please help me to find a beginner friendly solution?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
JJandke
  • 9
  • 3

1 Answers1

0

Instead of running the network call inside the main thread, simply use an AsyncTask instead. Also a much better solution would be use Retrofit, but it is not that straightforward for a beginner

private class AsyncTaskRunner extends AsyncTask<String, String, String> {

    private String resp;
    ProgressDialog progressDialog;

    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection urlConnection = null;
    try {
        URL url = new URL("http://raspberrypi/yellow.php");
        urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        readStream(in);
    } 
    catch (Exception e) {
        System.out.println("Shit!");
        e.printStackTrace();
    } finally {
        assert urlConnection != null;
        urlConnection.disconnect();
    }
    return null;
    }


    @Override
    protected void onPostExecute(String result) {
        // execution of result of Long time consuming operation
        progressDialog.dismiss();
        finalResult.setText(result);
    }


    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(MainActivity.this,
                "ProgressDialog",
                "Wait for "+time.getText().toString()+ " seconds");
    }


    @Override
    protected void onProgressUpdate(String... text) {
        finalResult.setText(text[0]);

    }
}

and the doYellow function would be like:

public void doYellow(View view) {
        new AsyncTaskRunner().execute("http://stackoverflow.com");

}

N.B. : I didn't run the code, so, it might/might not need few modifications

touhid udoy
  • 4,005
  • 2
  • 18
  • 31