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?