Alvaro Alvaro - 1 year ago 45
Android Question

AsyncTask return a boolean while retrieving information from a Json

I want to check if a user is registered or not in a database, and if it is get the information of the user.

Normally, when I retrieve the information from the server, I put in the

Json
a variable saying if the user exists or not. Then in
onPostExecute(Void result)
i treat the
Json
, so i don't need the
AsyncTask
to return any value.

Before I was calling the AsyncTask as follows:

task=new isCollectorRegistered();
task.execute();


But now i'm trying a different approach. I want my asynktask to just return a boolean where i called the
AsyncTask
.

the
AsyncTask
looks as follows:

public class isCollectorRegistered extends AsyncTask<Void, Void, Void> {

private static final String TAG_SUCCESS = "success";
int TAG_SUCCESS1;
private static final String TAG_COLLECTOR = "collector";
public String collector;
JSONArray USER = null;
JSONObject jObj = null;

@Override
protected void onPreExecute() {
super.onPreExecute();

}

@Override
protected Void doInBackground(Void... params) {
// Checks on the server if collector is registered
try {
jObj = ServerUtilities.UserRegistered(context, collector);
return null;
} finally {
return null;
}
}

@Override
protected void onPostExecute(Void result) {
try {

String success = jObj.getString(TAG_SUCCESS);
Log.d(TAG_COLLECTOR, "Final Info: " + success);

//This if sees if user correct
if (Objects.equals(success, "1")){
//GOOD! THE COLLECTOR EXISTS!!
}

} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG_COLLECTOR, "JSON parsing didn't work");
}
}
}


I have checked several posts, but I still havent found out the way to retrieve the boolean where I call the Asynktask, something like this :

task=new isCollectorRegistered();
task.execute();
boolean UserRegistered = task.result();


What would be the right approach? Any help would be appreciated

Answer Source

To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .

An AsyncTask is started via the execute() method.

The execute() method calls the doInBackground() and the onPostExecute() method.

TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.

In your case you are passing Void to your AsyncTask : isCollectorRegistered extends AsyncTask<Void, Void, Void> so you can't get your result from the thread. please read this tutorial to a deep understand of the AsyncTask in Android

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download