如何将进度对话与异步任务一起使用

时间:2013-07-23 07:21:30

标签: android android-layout android-intent android-asynctask

我想使用带有asynctask的进度对话框我怎么能用它。我试过但是它在获得响应后显示了对话框。这是我的调用函数...到asycnk任务 正如我所期待的那样,我面临的问题是因为 AppResponse = reqClient.execute()。get(); 因为我必须从此异步任务中获取返回值。所以请查看两个文件以获取参考

 void postHttpRequest(String userId,String pass,TextView error){
            RequestClient reqClient = new RequestClient(IweenTravelLoginPage.this);
            String AppResponse = null;
            try {
                url = "";
                Log.d("Http Post URL is ", url);
                AppResponse = reqClient.execute().get();

                String status = ValidateLoginStatus.checkLoginStatus(AppResponse);
                Log.d("Status recived", status);

                if(status.equals("200")){
                    saveInformation(userId,pass);
                    startingActivity();
                }else{
                    error.setText("Incorrect UserName or Password");
                }
            } catch (Exception e) {
                Log.e("Exception Occured", "Exception is "+e.getMessage());
            }

此功能用于发送请求

public class RequestClient extends AsyncTask<String, Void, String>{
    Context context;

    public RequestClient(Context c) {
        context = c;
    }

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

    @Override
    protected String doInBackground(String... aurl){
    String responseString="";
    HttpClient client = null;
    try {
         client = new DefaultHttpClient();  
         HttpGet get = new HttpGet(IweenTravelLoginPage.url);
         HttpResponse responseGet = client.execute(get);  
         HttpEntity resEntityGet = responseGet.getEntity();  
         if (resEntityGet != null) {  
             responseString = EntityUtils.toString(resEntityGet);
             Log.i("GET RESPONSE", responseString.trim());
         }
    } catch (Exception e) {
        Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
    }
        Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
        client.getConnectionManager().shutdown();
     return responseString.trim();

    }


    @Override
    protected void onPostExecute(String response) {
         super.onPostExecute(response); 
        }
}

所以请建议我要显示进程对话框。我尝试了stackoverflow上的所有示例。但是这些都不适合我。请帮助

5 个答案:

答案 0 :(得分:1)

使用这种方式对我来说非常适合

您可以创建界面,将其传递给AsyncTask(在构造函数中),然后在onPostExecute中调用方法

例如:

您的界面:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

您的活动:

public YourActivity implements OnTaskCompleted{
    //your Activity
}

你的AsyncTask:

public YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    //required methods

    protected void onPostExecute(Object o){
        //your stuff
        listener.onTaskCompleted();
    }
}

确保永远不会调用AppResponse = reqClient.execute().get();这会阻止您的uithread

答案 1 :(得分:1)

你可以尝试这个

extends AsyncTask<String, Void, String>{
Context context;

public RequestClient(Context c) {
    context = c;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage("Loading. Please Wait");
    progressDialog.setIndeterminate(false);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progressDialog.setCancelable(true);
    progressDialog.show();
}

@Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client = null;
try {
     client = new DefaultHttpClient();  
     HttpGet get = new HttpGet(IweenTravelLoginPage.url);
     HttpResponse responseGet = client.execute(get);  
     HttpEntity resEntityGet = responseGet.getEntity();  
     if (resEntityGet != null) {  
         responseString = EntityUtils.toString(resEntityGet);
         Log.i("GET RESPONSE", responseString.trim());
     }
} catch (Exception e) {
    Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
    Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
    client.getConnectionManager().shutdown();
 return responseString.trim();

}


@Override
protected void onPostExecute(String response) {
     super.onPostExecute(response); 
     progressDialog.dismiss();
        }
}

答案 2 :(得分:1)

只需基于之前的答案,您可以通过修改侦听器函数来获取从异步任务返回的数据,以获取返回数据的参数

public interface OnTaskCompleted{
    void onTaskCompleted(String response);
}

然后在Async任务的postExecute函数中让它用返回数据调用监听器

    @Override
    protected void onPostExecute(String response){
        //your stuff
        listener.onTaskCompleted(response);
    }

然后,在您调用Async任务的地方,您只需要实现侦听器。你可以有一个类实现监听器或使用匿名类

OnTaskCompleted listener = new OnTaskCompleted() {
    void onTaskCompleted(String response){
        // We got return data from the Async Task, do stuff!
    }
};
RequestClient reqClient = new RequestClient(listener);
reqClient.execute();

为了显示进度对话框,您应该在调用异步任务之前将其设置为显示,然后一旦从Aysnc任务接收到回叫,您就可以将其解除。

//make progressDialog a member of your class
progressDialog = new ProgressDialog(IweenTravelLoginPage.this);
progressDialog.setMessage("Loading");
progressDialog.show();

OnTaskCompleted listener = new OnTaskCompleted() {
    void onTaskCompleted(String response){
        // get rid of the progress dialog
        progressDialog.dismiss;
        // We got return data from the Async Task, do stuff!
    }
};
RequestClient reqClient = new RequestClient(listener);
reqClient.execute();

答案 3 :(得分:0)

为此,您可以在asyncTask中使用onProgressUpdate()。您可以从doInBackground()

中调用everyTime showProgressUpdate()

答案 4 :(得分:0)

可以查看此代码。这可以是简单的示例

public class LoginSync extends
            AsyncTask<ArrayList<NameValuePair>, Void, UserVO> {

        @Override
        protected UserVO doInBackground(ArrayList<NameValuePair>... params) {
            // TODO Auto-generated method stub
            return WebServiceClient.SendHttpPost("/us/si",
                    params[0], Use.class);
        }

        @Override
        protected void onPostExecute(UserVO result) {
            // TODO Auto-generated method stub
            if (result == null) {
                progressLayout.setVisibility(View.GONE);
                Toast.makeText(getApplicationContext(),
                        "Bağlantı Sorunu Tekrar Deneyiniz. ", 500).show();
                return;
            }
            UserVO userVO = new UserVO();
            userVO.setUserName(result.getUserName());
            userName = result.getUserIdentificationVO().getFirstName();
            userSName = result.getUserIdentificationVO().getLastName();



            progressLayout.setVisibility(View.GONE);

        }

    }