Show ProgressDialog Android
Declare your progress dialog:
ProgressDialog progress;
When you're ready to start the progress dialog:
progress = ProgressDialog.show(this, "dialog title", "dialog message", true);
and to make it go away when you're done:
progress.dismiss();
Here's a little thread example for you:
// Note: declare ProgressDialog progress as a field in your class.progress = ProgressDialog.show(this, "dialog title", "dialog message", true);new Thread(new Runnable() { @Override public void run() { // do the thing that takes a long time runOnUiThread(new Runnable() { @Override public void run() { progress.dismiss(); } }); }}).start();
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
// ---------------------------- START DownloadFileAsync // -----------------------//class DownloadFileAsync extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); // DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class showDialog(DIALOG_DOWNLOAD_PROGRESS); } @Override protected String doInBackground(String... urls) { try { String xmlUrl = urls[0]; URL u = new URL(xmlUrl); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); int lengthOfFile = c.getContentLength(); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; long total = 0; while ((len1 = in.read(buffer)) > 0) { total += len1; // total = total + len1 publishProgress("" + (int) ((total * 100) / lengthOfFile)); xmlContent += buffer; } } catch (Exception e) { Log.d("Downloader", e.getMessage()); } return null; } protected void onProgressUpdate(String... progress) { Log.d("ANDRO_ASYNC", progress[0]); mProgressDialog.setProgress(Integer.parseInt(progress[0])); } @Override protected void onPostExecute(String unused) { dismissDialog(DIALOG_DOWNLOAD_PROGRESS); }}@Overrideprotected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_DOWNLOAD_PROGRESS: mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("Retrieving latest announcements..."); mProgressDialog.setIndeterminate(false); mProgressDialog.setMax(100); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setCancelable(true); mProgressDialog.show(); return mProgressDialog; default: return null; }}
While creating the object for the progressbar check the following.
This fails:
dialog = new ProgressDialog(getApplicationContext());
While adding the activities context works..
dialog = new ProgressDialog(MainActivity.this);