ProgressDialog in AsyncTask

后端 未结 7 2257
一个人的身影
一个人的身影 2020-11-22 07:54

I\'m trying to display a custom progressdialog while loading RSS feed from an HTTP server, I made a hard search, but nothing helped me to do this, the only thing I know is t

相关标签:
7条回答
  • 2020-11-22 08:36

    Fixed by moving the view modifiers to onPostExecute so the fixed code is :

    public class Soirees extends ListActivity {
        private List<Message> messages;
        private TextView tvSorties;
    
        //private MyProgressDialog dialog;
        @Override
        public void onCreate(Bundle icicle) {
    
            super.onCreate(icicle);
    
            setContentView(R.layout.sorties);
    
            tvSorties=(TextView)findViewById(R.id.TVTitle);
            tvSorties.setText("Programme des soirées");
    
            new ProgressTask(Soirees.this).execute();
    
    
       }
    
    
        private class ProgressTask extends AsyncTask<String, Void, Boolean> {
            private ProgressDialog dialog;
            List<Message> titles;
            private ListActivity activity;
            //private List<Message> messages;
            public ProgressTask(ListActivity activity) {
                this.activity = activity;
                context = activity;
                dialog = new ProgressDialog(context);
            }
    
    
    
            /** progress dialog to show user that the backup is processing. */
    
            /** application context. */
            private Context context;
    
            protected void onPreExecute() {
                this.dialog.setMessage("Progress start");
                this.dialog.show();
            }
    
                @Override
            protected void onPostExecute(final Boolean success) {
                    List<Message> titles = new ArrayList<Message>(messages.size());
                    for (Message msg : messages){
                        titles.add(msg);
                    }
                    MessageListAdapter adapter = new MessageListAdapter(activity, titles);
                    activity.setListAdapter(adapter);
                    adapter.notifyDataSetChanged();
    
                    if (dialog.isShowing()) {
                    dialog.dismiss();
                }
    
                if (success) {
                    Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
                }
            }
    
            protected Boolean doInBackground(final String... args) {
                try{    
                    BaseFeedParser parser = new BaseFeedParser();
                    messages = parser.parse();
    
    
                    return true;
                 } catch (Exception e){
                    Log.e("tag", "error", e);
                    return false;
                 }
              }
    
    
        }
    
    }
    

    @Vladimir, thx your code was very helpful.

    0 讨论(0)
  • 2020-11-22 08:40

    AsyncTask is very helpful!

    class QueryBibleDetail extends AsyncTask<Integer, Integer, String>{
            private Activity activity;
            private ProgressDialog dialog;
            private Context context;
    
            public QueryBibleDetail(Activity activity){
                this.activity = activity;
                this.context = activity;
                this.dialog = new ProgressDialog(activity);
                this.dialog.setTitle("查询经文");
                this.dialog.setMessage("正在查询:"+tome+chapterID+":"+sectionFromID+"-"+sectionToID);
                if(!this.dialog.isShowing()){
                    this.dialog.show();
                }
            }
    
            @Override
            protected String doInBackground(Integer... params) {
                Log.d(TAG,"经文doInBackground");
                publishProgress(params[0]);
    
                if(sectionFromID > sectionToID){
                    return "";
                }
    
                String queryBible = "action=query_bible&article="+chapterID+"&id="+tomeID+"&verse_start="+sectionFromID+"&verse_stop="+sectionToID+"";
                try{
                    String bible = (Json.getRequest(HOST+queryBible)).trim();
                    bible = android.text.Html.fromHtml(bible).toString();
                    return bible;
                }catch(Exception e){
                    e.printStackTrace();
                }
                return null;
            }
    
            @Override
            protected void onPostExecute(String bible){
                Log.d(TAG,"经文onPostExecute");
                TextView bibleBox = (TextView) findViewById(R.id.bibleBox);
                bibleBox.setText(bible);
                this.dialog.dismiss();
            }
        }
    
    0 讨论(0)
  • 2020-11-22 08:42

    This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.

    0 讨论(0)
  • 2020-11-22 08:48

    Don't know what parameter should I use?

    A lot of Developers including have hard time at the beginning writing an AsyncTask because of the ambiguity of the parameters. The big reason is we try to memorize the parameters used in the AsyncTask. The key is Don't memorize. If you can visualize what your task really needs to do then writing the AsyncTask with the correct signature would be a piece of cake.

    What is an AsyncTask?

    AsyncTask are background task which run in the background thread. It takes an Input, performs Progress and gives Output.

    ie AsyncTask<Input,Progress,Output>

    Just figure out what your Input, Progress and Output are and you will be good to go.

    For example

    How does doInbackground() changes with AsyncTask parameters?

    How doInBackground() and onPostExecute(),onProgressUpdate() are related?

    How can You write this in a code?

     DownloadTask extends AsyncTask<String,Integer,String>{
    
        @Override
        public void onPreExecute(){
        }
    
        @Override
        public String doInbackGround(String... params)
        {
             // Download code
             int downloadPerc = // calculate that
             publish(downloadPerc);
    
             return "Download Success";
        }
    
        @Override
        public void onPostExecute(String result)
        {
             super.onPostExecute(result);
        }
    
        @Override
        public void onProgressUpdate(Integer... params)
        {
             // show in spinner, access UI elements
        }
    
    }
    

    How will you run this Task in Your Activity?

    new DownLoadTask().execute("Paradise.mp3");
    
    0 讨论(0)
  • 2020-11-22 08:50
    /**
     * this class performs all the work, shows dialog before the work and dismiss it after
     */
    public class ProgressTask extends AsyncTask<String, Void, Boolean> {
    
        public ProgressTask(ListActivity activity) {
            this.activity = activity;
            dialog = new ProgressDialog(activity);
        }
    
        /** progress dialog to show user that the backup is processing. */
        private ProgressDialog dialog;
        /** application context. */
        private ListActivity activity;
    
        protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }
    
            @Override
        protected void onPostExecute(final Boolean success) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
    
    
            MessageListAdapter adapter = new MessageListAdapter(activity, titles);
            setListAdapter(adapter);
            adapter.notifyDataSetChanged();
    
    
            if (success) {
                Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
            }
        }
    
        protected Boolean doInBackground(final String... args) {
           try{    
              BaseFeedParser parser = new BaseFeedParser();
              messages = parser.parse();
              List<Message> titles = new ArrayList<Message>(messages.size());
              for (Message msg : messages){
                  titles.add(msg);
              }
              activity.setMessages(titles);
              return true;
           } catch (Exception e)
              Log.e("tag", "error", e);
              return false;
           }
        }
    }
    
    public class Soirees extends ListActivity {
        private List<Message> messages;
        private TextView tvSorties;
        private MyProgressDialog dialog;
        @Override
        public void onCreate(Bundle icicle) {
    
            super.onCreate(icicle);
    
            setContentView(R.layout.sorties);
    
            tvSorties=(TextView)findViewById(R.id.TVTitle);
            tvSorties.setText("Programme des soirées");
    
            // just call here the task
            AsyncTask task = new ProgressTask(this).execute();
       }
    
       public void setMessages(List<Message> msgs) {
          messages = msgs;
       }
    
    }
    
    0 讨论(0)
  • 2020-11-22 08:55

    It's been a few years since this question was asked (and since someone has posted a response). Since then, ProgressDialog was deprecated in API level O, according to Android's official documentation. As such, you might consider using an inline progress bar instead of a ProgressDialog as the documentation authors suggest.

    0 讨论(0)
提交回复
热议问题