简体   繁体   中英

android asynctask & progress dialog

I'm currently working on a android app in which I use asynctasks to carry out json rest request. I've got this working fine. I have also got a progress dialog being made visible on the preexecute then dismissing it on the postexecute all working fine. see code below.

@Override
protected void onPreExecute(){

    Variables var = Variables.getInstance();
    Variables.getInstance().showPd(ProgressDialog.show(Variables.getInstance().getContext(), var.getValue("loggingin_text"), var.getValue("pleasewait"), true, false));
}    

protected void onPostExecute( JSONObject[] loginresponse ){

    Variables.getInstance().dismisspd();
    try {

        JSONObject responseheader = loginresponse[0].getJSONObject("commonInputParameters");

        if (responseheader.getString("status").equals("SUCCESS")) {

            Variables.getInstance().setUsername( loginresponse[1].getString("username") );
            Variables.getInstance().setSessiontoken(responseheader.getString("userSessionToken"));

            delegate.onRequestCompletion( true );

        } else {

            delegate.onRequestCompletion(false);
        }

    }catch (JSONException je ) {

        this.cancel( true );
    }
}

final Button _loginBTN = ( Button ) findViewById(R.id.loginBTN );
    _loginBTN.setText( vars.getValue( "loginbtn_text" ) );
    _loginBTN.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final Functions functions = Functions.getInstance();
            if( functions.isNetworkAvailable(getApplicationContext())) {
                if (functions.fullypopulated(new Object[]{_username, _password})) {
                    LoginRequest login = new LoginRequest(new responseInterface() {
                        @Override
                        public void onRequestCompletion(boolean successfulRequest) {

                            Variables.getInstance().dismisspd();
                            if ( !successfulRequest ) {

                                functions.showDialog(Variables.getInstance().getValue("login_err"), findViewById(R.id.input_username));
                                functions.clearEditText(new EditText[]{_username, _password});
                                functions.setError(new EditText[]{_username, _password});
                            } else {

                                Intent intent = new Intent(getApplicationContext(), NavigationHandler.class);
                                startActivity(intent);
                                finish();
                            }
                        }

                        @Override
                        public void onRequestCompletion(String requestResponse) {}
                        @Override
                        public void onRequestCompletion(int requestResponse) {}
                        @Override
                        public void onRequestCompletion(float requestResponse) {}
                    });
                    Map<String, String> loginDetails = new HashMap<String, String>();
                    loginDetails.put("username", _username.getText().toString());
                    loginDetails.put("password", _password.getText().toString());
                    login.execute(loginDetails);
                } else {

                    functions.showDialog(Variables.getInstance().getValue("no_details"), findViewById(R.id.input_username));
                    functions.clearEditText(new EditText[]{_username, _password});
                    functions.setError(new EditText[]{_username, _password});
                }
            }
            else {

                functions.showDialog(Variables.getInstance().getValue("no_network"), findViewById(R.id.input_username));
            }
        }
    });

The problem is that when I try to work in a time out into the async task the progress dialog shows but not until after it has completed and at which point I can't remove it.

This is how I'm trying to run it with a time out.

try{
       login.execute(loginDetails).get( 5000, TimeUnit.MILLISECONDS );
   }catch (InterruptedException ie ){
   }catch (ExecutionException ee){
   }catch (TimeoutException te ){
       login.cancel(true);
   }

Yes I know the catches are empty right now.

UPDATE:

Never mind looking at the get function again, it actually blocks the UI thread that is why the Progress Dialog isn't showing until the ASyncTask has completed. Is there anyway to implement a timeout feature?

Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

From http://developer.android.com/reference/android/os/AsyncTask.html

Mind the bold pieces ... as to my understanding, you should dismiss the Dialog in onCancelled() in case of Timeout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM