在类扩展Application中调用AsyncTack中的ProgressDialog

时间:2012-11-10 18:23:20

标签: java android android-asynctask

我使用自己的数据类扩展到Application类。它用于在我的应用程序中存储全局对象,并使所有Acitivites都可以访问它们。我希望这个类在应用程序运行时初始化,通过AsyncTask从Internet下载数据。如何在AsyncTask中显示/隐藏ProgressDialog,这需要我将正确的Context / Activity传递给它?

public class DataSource extends Application{
    private int userid;
    private Object[] orders;
    //initialize

    @Override
    public void onCreate() {
        // Pull data from the internet and store it in orders
        super.onCreate();
    }

    public void beginDataLoad(Activity callingActivity) {
        // HOW DO I PASS THE CORRECT ACTIVITY TO MY NEW downloadData OBJECT?
        downloadData task = new downloadData(callingActivity);
        task.execute(new String[] { "http://www.myurl.com" });
    }

    private class downloadData extends AsyncTask<String, Void, String>{
        private ProgressDialog progressDialog;
        private MainActivity activity;

        public downloadData(MainActivity activity) {
            this.activity = activity;
            this.progressDialog = new ProgressDialog(activity);
        }

        protected void onPreExecute() {
            progressDialog.setMessage("Downloading events...");
            progressDialog.show();
        }
        protected String doInBackgroun(String... params) {
            // Do AsyncTask download functions in background...
        }
        protected void onPostExecute() {
            progressDialog.dismiss();
            //Callback function in MainActivity to indicate data is loaded
            activity.dataIsLoaded();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我最终以这种方式从我的MainActivity调用数据源负载。

public class MainActivity extends Activity {

    //onclick function...
    myDataSource = (DataSource)getApplicationContext();
    myDataSource.beginDataLoad(MainActivity.this);

    //Callback for AsyncTask to call when its completed
    public void dataIsLoaded() {
        //Do stuff once data has been loaded
    }
}