Shubham Shubham - 5 months ago 20
JSON Question

want to make UI thread wait while Asynctask is working in background

I am making an app in which I use

Asynctack
to fetch login details for me

User enters username and password and I the following function from a different class

static int success;
public static boolean authenticate(final String emailId , final String password , final ProgressDialog progressDialog) {
data = new Data();
new AsyncTask<Void , Void, Void>(){
@Override
protected void onPreExecute() {
super.onPreExecute();

progressDialog.setMessage("Authenticating...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}

@Override
protected Void doInBackground(Void... param) {

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username" , emailId));
params.add(new BasicNameValuePair("password" , password));

JSONObject json = jsonParser.makeHttpRequest(url_login, "POST", params);

try {
success = json.getInt("success");
if (success ==1){
JSONArray student = json.getJSONArray("student");
JSONObject jobject = student.getJSONObject(0);

...loading details...
}



} catch (JSONException e) {
Log.e("Authentication error" , e.toString());
}
return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();

}
}.execute();
if (success==1){
return true;}
else return false;

}


here I call it

ProgressDialog progressDialog = new ProgressDialog(this);
if(Login.authenticate(username,password,progressDialog)) {
Toast.makeText(this, "Authenticated\nWelcome " + Login.data.Fullname, Toast.LENGTH_SHORT).show();
..calling next activity...
...bla bla bla...
}
else Toast.makeText(this, "Authentication Failed" , Toast.LENGTH_SHORT).show();


In this IF condition the
ProgressDialog
appears and with that 2nd toast appears i.e. Authentication Failed and nothing happens

I think I know whats the problem here but cant figure it out

I think UI thread must wait till the
Asynctask
completes its task and then return anything

Answer

I think UI thread must wait till the AsyncTask completes its task and then return anything

When calling AsyncTask.execute UI Thread not wait for complete and return from AsyncTask.

But onPostExecute is a method which is called on UI Thread when doInBackground so do all work which want to execute according to AsyncTask result inside onPostExecute method like want to show Toast message or start a new Activity,...

  @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        progressDialog.dismiss();
         if (success==1){
           // start new Activity here
         }
         else {
           // show fail message 
         }
    }
Comments