Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Joel Jacoby
1,808 PointsFinishing Async Task throwing IO exception
My connection string has been working fine up until now and for some reason it keeps the responseData at -1 and throwing an IO exception
private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject>{
@Override
protected JSONObject doInBackground(Object... arg0) {//set verify and read the connection Async
int responseCode = -1;
JSONObject jsonResponse = null;
try{
URL blogUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_BLOG_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogUrl.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
String responseData = new String(charArray);
reader.read(charArray);
jsonResponse = new JSONObject(responseData);
}else{
Log.i(TAG, "Unsuccessful Code: " + responseCode);
}
}
catch(MalformedURLException e){
Log.e(TAG, "exception caught: ", e);
}
catch(IOException e){
Log.e(TAG, "exception caught: ", e);
}
catch(Exception e){
Log.e(TAG, "exception caught: ", e);
}
return jsonResponse;
}
1 Answer
Joel Jacoby
1,808 PointsI got it. I guess the InputStreamReader.read() method is actually "reading"(saving) to the charArray and I was setting responseData to charArray before it had the input stream. I still dont know why i was getting that error but I moved the responseData line below the reader.read() call and it fixed it.