如何使用Async Task Class设置微调器的适配器

时间:2012-09-19 11:54:24

标签: android

在我的代码中,我使用Async Task加载了一个微调器适配器     在我的情况下,ProgressDialog并没有消失     这是我的代码。     我想在适配器加载后显示该项目,并且将解除progressDialog     请帮助我,谢谢

private class LoadMoreVehicals extends AsyncTask<Object, Integer, Object> {

        @Override
        protected void onPreExecute() {

            progressBar = ProgressDialog.show(RegistrationScreen.this, "",
                    "Loading...");
            progressBar.setIndeterminate(true);
            progressBar.setIndeterminateDrawable(getResources().getDrawable(
                    R.anim.progressbar_handler));
            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object... params) {
            String countryUrl = ConstantURL.COUNTRY_URL;
            getCounty(countryUrl);

            countrySpinner
            .setAdapter(new MyCustomSpinnerAdapter(
                    RegistrationScreen.this,
                    R.layout.spinner_dropdown,
                    countyList));

                                return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            progressBar.getProgress();

        }

        @Override
        protected void onPostExecute(Object result) {

            progressBar.dismiss();

             Log.e("Im in onPostExecute", "");
            super.onPostExecute(result);
        }
    } 

3 个答案:

答案 0 :(得分:2)

在Android中编程时,您应该记住,在主线程上执行任何在屏幕上绘制内容的任务。当你设置适配器然后android调用适配器的getView()方法并在屏幕上绘制视图。因此,您应该在postExecute()方法中设置适配器,而不是在doInBackground()方法中。
这是一个清楚我的观点的小样本:

class MyTask extends AsyncTask<Void, Void, Void> {
    ProgressDialog pd = new ProgressDialog(MainActivity.this);

    @Override
    protected void onPreExecute ( )
    {
        //starting the progress dialogue
        pd.show();
    }

    @Override
    protected Void doInBackground (Void... params)
    {
        //fetch data here
        ...
        ... 
        return null;
    }

            @Override
    protected void onPostExecute (Void result)
    {
        //set adapter here
        ...
        ...
        //dismissing the progress dialogue
        pd.dismiss();
    }

}

答案 1 :(得分:0)

首先,您无法在doInBackground中设置适配器 遵循这个设计:

private class LoadMoreVehicals extends AsyncTask<Object, Integer, Object> 
{
    private ArrayList<Country> countries;
    @Override
    protected void onPreExecute() {
         progressBar = ProgressDialog.show(RegistrationScreen.this, "","Loading...");
         progressBar.setIndeterminate(true);
         progressBar.setIndeterminateDrawable(getResources().getDrawable(R.anim.progressbar_handler));              
         super.onPreExecute();
    }

    @Override
    protected Object doInBackground(Object... params) {
        String countryUrl = ConstantURL.COUNTRY_URL;
        countries = getCounty(countryUrl);
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        progressBar.getProgress();

    }

    @Override
    protected void onPostExecute(Object result) {
        countrySpinner.setAdapter(new MyCustomSpinnerAdapter(RegistrationScreen.this,R.layout.spinner_dropdown,countries));
        progressBar.dismiss();
        Log.e("Im in onPostExecute", "");
        super.onPostExecute(result);
    }
} 

答案 2 :(得分:0)

根据我的经验,我在异步运行和UI方面遇到了很多问题,所以现在总是将试图在每个地方放置“责任”的东西分开。所以我做这样的事情:

  1. 使用我想要执行的流程创建我的Async类,并且不改变其中的UI
  2. 在UI线程中创建一个函数,在异步任务完成时修改UI,如OnAsyncTaskComplete(对象响应)
  3. 保持沟通线程

    public class MyActivity extends Activity {
    
    private static MyAsyncClass backgroundTask;
    private static ProgressDialog pleaseWaitDialog; 
    
    //......activity stuff.......
    
    @Override
    public void onPause()
    {
        super.onPause();
        //Get rid of progress dialog in the event of a screen rotation or other state change. Prevents a crash.
        if (pleaseWaitDialog != null)
            pleaseWaitDialog.dismiss();
    }
    //Function to avoid lose the async thread if the app interrupts (phone rotation, incoming call, etc) RECOMENDED TO HANDLE THIS!!
    //Sets the current state after app resume
    @Override
    public void onResume()
    {
    
        super.onResume();
        //If there is a background task set it to the new activity
        if ((backgroundTask != null) && (backgroundTask.getStatus() == Status.RUNNING))
        {
           if (pleaseWaitDialog != null)
             pleaseWaitDialog.show();
    
           backgroundTask.setActivity(this);
        }
        }
    }
    
        //Logic business after the web service complete here
    //Do the thing that modify the UI in a function like this
    private void onTaskCompleted(Object _response) 
    { 
        //For example _response can be a new adapter
    MyList.setAdapter((BaseAdapter)_response);
    //or can be a list to create the new adapter
    MyList.setAdapter(new MyAdapter(this, (ArrayList<String>)_response));
    //or can be anything you want, just try to make here the things that you need to change the UI
    }
    
    /**
     * Class that handle the async task
     */
    public class MyAsyncClass extends AsyncTask<Void, Void, Object>
    {
        //Maintain attached activity for states change propose 
         private MyActivity activity;
         //Keep the response of the async task
         private Object _response;
         //Flag that keep async task completed status
         private boolean completed; 
    
         //Constructor
         private MyAsyncClass(MyActivity activity) { 
                 this.activity = activity;
         } 
    
         //Pre execution actions
         @Override 
         protected void onPreExecute() {
                 //Start the splash screen dialog
                 if (pleaseWaitDialog == null)
                     pleaseWaitDialog= ProgressDialog.show(activity.this, 
                                                            "PLEASE WAIT", 
                                                            "Getting results...", 
                                                            false);
    
         } 
    
         //Execution of the async task
        protected Object doInBackground(Object...params)
        {
            //return the thing you want or do want you want
            return new ArrayList();
        }
    
        //Post execution actions
        @Override 
        protected void onPostExecute(Object response) 
        {
            //Set task completed and notify the activity
                completed = true;
                _response = response;
                notifyActivityTaskCompleted();
            //Close the splash screen
            if (pleaseWaitDialog != null)
            {
                pleaseWaitDialog.dismiss();
                pleaseWaitDialog = null;
            }
        } 
    
        //Notify activity of async task completion
        private void notifyActivityTaskCompleted() 
        { 
            if ( null != activity ) { 
                activity.onTaskCompleted(_response); 
            } 
        } 
    
    //for maintain attached the async task to the activity in phone states changes
        //Sets the current activity to the async task
        public void setActivity(MyActivity activity) 
        { 
            this.activity = activity; 
            if ( completed ) { 
                notifyActivityTaskCompleted(); 
            } 
        } 
    
    }
    }
    
  4. 希望对你有所帮助