Issue
I'm trying to make a GET request in Android Studio and I don't understand why this method works in Eclipse as a Java program but not in Android Studio, so I supposed it was something related to threats, so I made a call to an Async Task.
My code looks like this:
Called method:
private static class GetFarmaciasTask extends AsyncTask<String,String,String[][]>{
protected String[][] doInBackground(String... urls) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("https://mikelmoli.000webhostapp.com/PHP/json.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
JSONObject jsonO = new JSONObject(result.toString());
//JSONObject myResponse = jsonO.getJSONObject("data");
JSONArray tsmResponse = (JSONArray) jsonO.get("data");
String[] indices = {"Nombre", "Provincia", "Poblacion", "Calle", "Numero", "Telefono"};
String[][] datos = new String[tsmResponse.length()][indices.length];
for (int i = 0; i < tsmResponse.length(); i++) {
for (int j = 0; j < indices.length; j++) {
datos[i][j] = tsmResponse.getJSONObject(i).getString(indices[j]);
}
}
return datos;
} catch (IOException e1) {
e1.printStackTrace();
} catch (JSONException ej) {
ej.printStackTrace();
}
return null;
}
}
The error is in this line of the code:
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
As I said before, this method works in Eclipse as an independent method.
Some of the errors which made me think about thread errors:
android.os.NetworkOnMainThreadException
Caused by: android.os.NetworkOnMainThreadException
Solution
This is mostly likely because if the way you are using the AsyncTask. If you are seeing that exception, you are probably calling doInBackground() directly. This article explains how AsyncTask works and should help: http://hiqes.com/androids-asynctask-explained/
Also, they are one time execute objects, so I would recommend not making it static. There are also other subtle pitfalls with making it an inner class of something like an Activity, which can cause memory leaks, so be careful.
Answered By - Larry Schiefer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.