I am trying to setup an Android List that gets information from an JSON array on the internet, the JSON is this:
[
{
"id":1,
"category":"Category1",
"title":"Title1",
"description":"description1",
"studio":"studio1",
"videoUrl":"https://example.com",
"cardImageUrl":"http://example.com",
"bgImageUrl":"http://example.com"},
{
"id":2,
"category":"category2",
"title":"title2",
"description":"description2",
"studio":"studio2",
"videoUrl":"http://example.com",
"cardImageUrl":"http://example.com",
"bgImageUrl":"http://example.com"
}
]
This is my code used to retrieve the data from the server:
public static List<Movie> setupMovie()
{
List<Movie> list = new ArrayList<>();
try {
URL data = new URL("http://example.com/data.php");
URLConnection tc = data.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line = null;
JSONArray array = new JSONArray(line);
while ((line = in.readLine()) != null) {
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
list.add(buildAppInfo(object.getString("category"), object.getString("title"), object.getString("description"),
object.getString("studio"), object.getString("videoUrl"), object.getString("cardImageUrl"),
object.getString("bgImageUrl")));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
When I run the APK in android Studio it crashes with the following error:
Process: com.example.myapp, PID: 8034
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.MainActivity}: android.os.NetworkOnMainThreadException
Application terminated.
I know the answer is to do an Async Task, I tried reading other answers on similar questions, but I am still don't understand how to correctly setup an Async Task on my case. I also tried the StrictMode but it does not work.
My main problem is that I don't understand how to setup async task work on my project. Any help will be very much appreciated, thank you.