Through the following piece of Android code, I connect to an html page on the internet and extract few lines. The code executes well most of the time, but it hangs sometimes. I have to press the back button on the mobile to get the ‘Force Close’ dialog. It always runs well on the emulator though (Have a fast connection on the PC).
- So, is the code hanging because of a slow EDGE/GPRSconnection on my mobile?
- Should I be inserting Socket timeouts?
- What other reasons could there be for the code to hang?
- How do I prevent the code from hanging? Is there a way to trap the error and return a message to the user before re-trying again?
Please help.
private String readFile(){
List<String> scores = new ArrayList<String>();
String result="";
String score = "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.espncricinfo.com/icc_cricket_worldcup2011/engine/current/match/433567.html");
try{
HttpResponse response = client.execute(request);
//txtResult.setText(HttpHelper.request(response));
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
//result = str.toString().substring(1,500);
Pattern p = Pattern.compile(
"<title>(.*)</title>",
Pattern.DOTALL
);
Matcher matcher = p.matcher(
result
);
if (matcher.find())
{
score = matcher.group(1).toString();
}
TextView tv = (TextView)findViewById(R.id.textview);
tv.setText(score);
return score;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, "IOException e = " + e.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG, "IOException e = " + e.toString());
return "IOException e = " + e.toString();
}catch(Exception ex){
result = "Error";
ex.printStackTrace();
Toast.makeText(this, "Exception ex = " + ex.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG,"Exception ex = " + ex.toString());
return "Exception ex = " + ex.toString();
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
Toast.makeText(this, "SocketTimeoutException e = " + e.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG, "SocketTimeoutException e = " + e.toString());
return "SocketTimeoutException e = " + e.toString();
}catch(Exception ex){
Toast.makeText(this, "Exception ex1 = " + ex.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Exception ex1 = " + ex.toString());
return "Exception ex1 = " + ex.toString();
}
}
Are you running this in the main thread of your application? Longer running processes should execute in a separate thread to avoid slowing down the main thread for the user.
See the Android Developer guide for example.