Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display progress dialog before starting an activity in Android?

How do you display a progress dialog before starting an activity (i.e., while the activity is loading some data) in Android?

like image 514
Neha Avatar asked Mar 05 '11 06:03

Neha


People also ask

How do you show progress dialog for 5 seconds?

ProgressDialog dialog = ProgressDialog. show(this, "", "Detecting...", true); dialog. show(); dialog. dismiss();


2 Answers

You should load data in an AsyncTask and update your interface when the data finishes loading.

You could even start a new activity in your AsyncTask's onPostExecute() method.

More specifically, you will need a new class that extends AsyncTask:

public class MyTask extends AsyncTask<Void, Void, Void> {   public MyTask(ProgressDialog progress) {     this.progress = progress;   }    public void onPreExecute() {     progress.show();   }    public void doInBackground(Void... unused) {     ... do your loading here ...   }    public void onPostExecute(Void unused) {     progress.dismiss();   } } 

Then in your activity you would do:

ProgressDialog progress = new ProgressDialog(this); progress.setMessage("Loading..."); new MyTask(progress).execute(); 
like image 88
Matthew Willis Avatar answered Sep 25 '22 22:09

Matthew Willis


When you start a long-running process on Android, its always advisable to do it on another thread. You can then use the UI thread to display a progress dialog. You cannot display a progress dialog in the same (UI) thread in which the process is running.

Do the following to start your process

pd = ProgressDialog.show(this, "Synchronizing data", "Please wait..."); Thread t = new Thread(this); t.start(); 

For this your activity should implement Runnable as follows

public class SyncDataActivity extends Activity implements Runnable 

And finally a method to perform the long-running process

@Override public void run() {       //your code here } 
like image 37
Arun Avatar answered Sep 22 '22 22:09

Arun