I'm currently developing a application that connects to a website to get some information (very few information), and I'm using a Asynctask with a HttpClient inside of it to get this information. In the main (UI) thread, I use a runnable plus a Handler to check if the Asynctask is already finished and, if it is, process the incoming information.
Problem is: sometimes the Asynctask doesn't seem to complete the task, making the Handler plus Runnable check it forever without any answer. It's not a problem with the website, as I tested it in a local website using Xampp. It seems to me that I'm not doing something the way it's meant to be.
I "solve" the problem by forcing the app to close via my Android's app manager (the app then takes less than 1 iteration to get the information), but I wouldn't like to say to people who's gonna use it: "Hey, in case of problem, force the app to close via your app manager", I would like the app to run without problems, so I'm asking you for help. :)
Here's some code:
public class Postman extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... s) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://website.com/" + s[0]);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for(int i = 1; i < s.length; i++){
pairs.add(new BasicNameValuePair(Integer.toString(i),s[i]));
}
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse r = client.execute(post);
String res = EntityUtils.toString(r.getEntity());
return res;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
This class I use to communicate with the website. I create a Postman object then I use postman.execute("phpPageToCommunicate.php", + params);, then I use the following code to check if it's already finished or not:
final Handler h = new Handler();
Runnable r = new Runnable(){
@Override
public void run() {
if(postman.getStatus() == AsyncTask.Status.FINISHED()){
// some code
}else{
h.postDelayed(this,1000);
}
}
};
h.postDelayed(r,1500);
I'm sure I'm doing something wrong, but I don't know what, so I'm sincerely asking you for help
Cheers!