I try to read json file from the URL in my Android Project. But strange situation happens. StringBuilder successfully gets first few characters but then I get java.net.SocketException: recvfrom failed: EBADF (Bad file descriptor)
Why I get this exception?
What is wrong with my code?)
JSON: http://inlyfortesting.ucoz.net/artists.json
My JSONParser:
public JSONArray getJSONFromUrl(String urlAsString) {
// try to create JSONObject from string
try {
URL url = new URL(urlAsString);
new DownloadFileTask().execute(url).get();
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return jObj;
}
private class DownloadFileTask extends AsyncTask<URL, Integer, Long> {
StringBuilder sb;
protected Long doInBackground(URL... urls) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) urls[0].openConnection();
is = new BufferedInputStream(connection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
connection.disconnect();
}
//file reading
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
sb = new StringBuilder();
int symbol;
int counter = 0;
while ((symbol = reader.read()) != -1) { //PROBLEM HERE
sb.append((char)symbol); //OR HERE
}
json = sb.toString();
is.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); //java.net.SocketException: recvfrom failed: EBADF (Bad file descriptor)
}
return null;
}
}
connection.disconnect();. Remove that. If you are disconnected you cannot read any more as you are trying to do now.new DownloadFileTask().execute(url).get();. Very bad programming to call the .get() method there. Remove the get() and place the following statement in onPostExecute.