Reputation: 367
Here's the Asynctask
method:
public class Read extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
sUrl = sUrl.trim();
json = lastTweet(sUrl);
return json.getString(params[0]);
} catch (ClientProtocolException 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 null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
}
}
And related lastTweet method:
public JSONObject lastTweet(String username)
throws ClientProtocolException, IOException, JSONException {
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}
}
All of this code is working fine. No issues as of now. However, there's minor tinkering I want to do. As and when the connectivity is lost during HTTP transmission, a RemoteException
is thrown and app crashes.
I tried to handle exception within Async
method but not able to do so.
Any way to handle such an exception?
Upvotes: 1
Views: 355
Reputation: 14199
you can check network connectivity before executing your Read
AsyncTask
1. check Connection
if(ifConnectionIsAvailable)
new Read().execute();
2. set Connection Time Out
HttpGet get = new HttpGet(url.toString());
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;// in milliseconds
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse r = httpClient.execute(get);
Upvotes: 1