Android异步进度对话框延迟

时间:2011-04-05 02:44:51

标签: android progress android-progressbar

我有一个进度对话框类,它是我的主要活动的子类。这本身就很好。

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

    ProgressDialog loading;
    @Override
    protected void onPreExecute() { 
        loading = ProgressDialog.show(NewsFeedActivity.this,"Please wait...", "Retrieving data ...", true);
    }

    @Override
    protected void onProgressUpdate(Void... progress) {

    }


    @Override
    protected void onPostExecute(Void result) {

        loading.dismiss();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        return null;
    }

}

我有一个名为getNews的方法,它发送一个http post请求并解析结果,这需要几秒钟。在这个方法中,我调用UpdateFeedTask以异步方式显示进度对话框,但它似乎不会同时执行。只有在http请求完成后才会打开进度对话框,因此不会显示进度对话框并发送请求,而是首先完成方法getNews,然后在一瞬间简要显示进度对话框。在获取数据之前如何显示对话框?以下是我如何调用进度对话框

public void getNews(){

            //show the progress dialog
    new UpdateFeedTask().execute();


    //go fetch some data
    WheruClient newsFeedLocation = new WheruClient();

    try {

        newsFeedArray = newsFeedLocation.getLocationActivity(sessionKey,page,filter,when);


    }catch (ClientProtocolException e) {
        Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show();
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show();
    }catch (JSONException e) {
        Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

**编辑新的异步类在后台发送http请求并获取json数组,但是我得到一个致命的错误,读取

04-07 15:33:02.967:ERROR / AndroidRuntime(11004):引起:java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序

我读了你的例子,我觉得我错过了在后台做工作的事情,有什么想法吗?

public class UpdateFeedTask extends AsyncTask<Void, Void, JSONArray> {


    @Override
    protected void onPreExecute() { 
        //loading = ProgressDialog.show(NewsFeedActivity.this,"Please wait...", "Retrieving data ...", true);
    }

    @Override
    protected void onProgressUpdate(Void... progress) {

    }


    @Override
    protected void onPostExecute(JSONArray result) {

        //loading.dismiss();
        updateFeed(result);
    }

    @Override
    protected JSONArray doInBackground(Void... params) {

        WheruClient newsFeedLocation = new WheruClient();

        try {
            newsFeedArray = newsFeedLocation.getLocationActivity(sessionKey,page,filter,when);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return newsFeedArray;
    }

}

1 个答案:

答案 0 :(得分:1)

需要在doInBackground中调用时间密集型任务。我在doInBackground方法中什么都没看到。请注意,请勿触摸doInBackground中的UI。我有一些示例代码here.

相关问题