I’m getting the following errors in the code below: The return type is incompatible with AsyncTask.onPostExecute(Integer). I’m trying to return the result from the http request done in the doInBackground task. I get the error: Type mismatch: cannot convert from AsyncTask to int in the return statement for isAvailable. I feel like there’s something simple I’m not doing but I can’t quite figure it out.
public int isAvailable(int position) {
GetIsAvailable isAvail = new GetIsAvailable();
Integer nisAvail = isAvail.execute(position); // error is still here
return nisAvail;
}
private class GetIsAvailable extends AsyncTask<Integer,Void,Integer > {
@Override
protected Integer doInBackground(Integer...position) {
Bundle resBundle = new Bundle();
String url = "http://www.testurl.com"
+ position[0]+"&uname="+AppStatus.mUserName;
URL iuri;
try {
iuri = new URL(url);
URLConnection connection = iuri.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
BufferedReader br = new BufferedReader(new InputStreamReader(
(InputStream) connection.getContent()));
resBundle.putInt("isAvail", Integer.parseInt(br.readLine().trim()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new Integer(0);
}
@Override
protected Integer onPostExecute(Integer isAvail) { // Main Error here
return isAvail;
}
Oh, I think I see the problem. I don’t think you can handle this the way you’re doing it currently. You should be handling the effects of the value of
isAvailwithin theonPostExecute()method.isAvailable()is running on the main thread, whileisAvailis running on a separate thread. You’re trying to return the result of the AsyncTask before it has finished completion.I’m 99% sure that’s the problem.