I have a method in my activity to download a set of files. This downloading is taking place when I start a new activity. I have used threads, because it downloads completely whereas AsyncTask may sometimes fail to download all files, it may get stuck in between.
Now, a black screen is shown when the downloading takes place. I want to show it within a ProgressDialog so that user may feel that something is getting downloaded.
I have added a ProgressDialog, but its not showing. Can anyone tell where did I go wrong?
Below is my code:
Inside onCreate() I have written:
downloadFiles();
private boolean downloadFiles() {
showProgressDialog();
for(int i = 0; i < filesList.size();i++) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
//downloading code
});
thread.start();
thread.run();
}
dismissProgressDialog();
return true;
}
//ProgressDialog progressDialog; I have declared earlier.
private void showProgressDialog() {
progressDialog = new ProgressDialog(N12ReadScreenActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Downloading files...");
progressDialog.show();
}
private void dismissProgressDialog() {
if(progressDialog != null)
progressDialog.dismiss();
}
Try this .. it's simple
ProgressDialog progress = new ProgressDialog(this);
progress.Indeterminate = true;
progress.SetProgressStyle(ProgressDialogStyle.Spinner);
progress.SetMessage("Downloading Files...");
progress.SetCancelable(false);
RunOnUiThread(() =>
{
progress.Show();
});
Task.Run(()=>
//downloading code here...
).ContinueWith(Result=>RunOnUiThread(()=>progress.Hide()));
Please try Below Code .
private Handler responseHandler=null;
downloadFiles();
private boolean downloadFiles() {
showProgressDialog();
for(int i = 0; i < filesList.size();i++) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
//downloading code
responseHandler.sendEmptyMessage(0);
});
thread.start();
}
responseHandler = new Handler()
{
public void handleMessage(Message msg)
{
super.handleMessage(msg);
try
{
dismissProgressDialog()
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
}
Here in this code when ever your dowload will completed it called response handler and your progress dialog will dismiss.
In downloadFiles() you show the dialog, then start a number of threads and after they've been started the dialog got dismissed. I don't think this is what you want as the dialog gets closed right after the last thread is started and not after the last thread has finished.
The dismissProgressDialog() method must be called after the last thread has finished its work. So at the end of the code run in the thread you have to check whether other threads are still running or whether you can dismiss the dialog as no other threads are running.
Try the following code and let me know how it goes:
private Handler mHandler = new Handler(){
public void handleMessage(Message msg)
{
dismissProgressDialog()
}
};
private boolean downloadFiles() {
showProgressDialog();
for(int i = 0; i < filesList.size();i++) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
//downloading code
});
thread.start();
thread.run();
}
mHandler.sendEmptyMessage(0);
return true;
}
//ProgressDialog progressDialog; I have declared earlier.
private void showProgressDialog() {
progressDialog = new ProgressDialog(N12ReadScreenActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Downloading files...");
progressDialog.show();
}
private void dismissProgressDialog() {
if(progressDialog != null)
progressDialog.dismiss();
}
Related
my app does heavy task so I want to show a progress bar to user and run the task in background, so user can understand that its loading.
when the background task completes hide the progress bar.
But progress bar should not take same time to reach its max, it should be dependent on users input or processing.
Use AsyncTask. AsyncTask is one of the easiest ways to implement parallelism in Android without having to deal with more complex methods like Threads. Though it offers a basic level of parallelism with the UI thread, it should not be used for longer operations (of, say, not more than 2 seconds).
AsyncTask has four methods do the task:
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
Check link for more details.
You can create something like this, the process ends in 30 seconds. I hope it will be useful to you
private ProgressDialog progressDialog;
public void init() {
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setMessage("please wait");
progressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
while (time < 30) {
try {
Thread.sleep(1000);
Message message = new Message();
message.what = UPDATE_PROGRESS;
handler.sendMessage(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Message message = new Message();
message.what = END_PROGRESS;
handler.sendMessage(message);
}
}).start();
}
private static final int UPDATE_PROGRESS = 1;
private static final int END_PROGRESS = 2;
private int time;
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_PROGRESS:
progressDialog.setMessage("Time: " + time++);
break;
case END_PROGRESS:
progressDialog.dismiss();
break;
default:
break;
}
return true;
}
});
UPDATE
This is the thread and handler example. But you can also create an asynctask
I'm calling several AsyncTasks to do a job. In order to know when they are done. I have an object (synchronized) with a numerator that holds the number of current running AsyncTasks.
After deploying all of them I do the following:
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage(getString(R.string.please_wait));
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setProgress(0);
pd.setMax(Utils.getAsyncs());
pd.show();
new Thread(new Runnable() {
#Override
public void run() {
while (Utils.getAsyncs() > 0)
pd.setProgress(pd.getMax() - Utils.getAsyncs());
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
}
});
}
}).start();
When the dialog shows, it starts progressing but at some point it gets stuck til the end of everything and then dismisses (as expected).
I tried to put
pd.setProgress(pd.getMax() - Utils.getAsyncs());
also inside a runOnUiThread but that made things worse and I'm sure I'm missing something else. hence my question. Thanks
edited by request:
public static int getAsyncs() {
return asyncs;
}
edit 2: I did the following based on a comment
while (Utils.getAsyncs() > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
runOnUiThread(new Runnable() {
public void run() {
pd.setProgress(pd.getMax() - Utils.getAsyncs());
}
});
}
and it seems to be better
In your class fields
private Handler progressHandler = new Handler();
private Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progressDialog.setProgress(progressValue);
progressHandler.postDelayed(this, 1000);
}
};
When the time consuming thread is started
// Here start time consuming thread
// Here show the ProgressDialog
progressHandler.postDelayed(progressRunnable, 1000);
When the time consuming thread ends
progressHandler.removeCallbacks(progressRunnable);
/// Here dismiss the ProgressDialog.
ADDED:
Instead new Thread(new Runnable) that you probably use for your time consuming code I propose to do this:
To initialize the task :
MyTask task = new MyTask();
task.execute();
// Here show the PorgressDialog
progressHandler.postDelayed(progressRunnable, 1000);
Add this private class inside your main class:
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
//Here do your time consuming work
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
// This will be called on the UI thread after doInBackground returns
progressHandler.removeCallbacks(progressRunnable);
progressDialog.dismiss();
}
}
do something lik this
new Thread(new Runnable() {
public void run() {
while (prStatus < 100) {
prStatus += 1;
handler.post(new Runnable() {
public void run() {
pb_2.setProgress(prStatus);
}
});
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(prStatus == 100)
prStatus = 0;
}
}
}).start();
im try to show ProgressDialog in side the thread.but when the app run Progressdialog will crach and it give this Exception
android.view.WindowLeaked:
Activity com.testApp.CaptureSignature has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView{528dd504
V.E..... R.....I. 0,0-949,480} that was originally added here
error getting when line executing
pDialog.show();
public void syncing(final int sel){
if(sel==1){
ProgressDialo pDialog = new ProgressDialog(CaptureSignature.this);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.setProgress(0);
pDialog.setOnDismissListener(new MyCustomDialog.OnDismissListener() {
#Override
public void onDismiss(final DialogInterface dialog) {
doaftersync(pDialog.getProgress(),sel);
}
});
pDialog.setMessage("Syncing Deliveries.Please wait..");
pDialog.show();
Thread background = new Thread (new Runnable() {
public void run() {
progressHandler.sendMessage(progressHandler.obtainMessage());
int stat = deliveryup();
if(stat==1){
try {
locationManager.removeUpdates(locationListner);
} catch (Exception e2) {
}
}else{
pDialog.dismiss();
return;
}
progressHandler.sendMessage(progressHandler.obtainMessage());
int isustat=issueup();
if(isustat==0){
pDialog.dismiss();
return;
}
progressHandler.sendMessage(progressHandler.obtainMessage());
int locstat=locationup();
if(locstat==0){
pDialog.dismiss();
return;
}
cleanup();
progressHandler.sendMessage(progressHandler.obtainMessage());
pDialog.dismiss();
return;
}
});
background.start();
}
}
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
pDialog.incrementProgressBy(25);
}
};
Any Help .. !!
Dismiss Your ProgressDialog in Main Thread Using Handler or Using runOnUiThread() Method
Maybe You get exception because Progress dialog is running while Your Activity is destroyed. you should dismiss dialog when Activity is destroyed
Do all your UI actions in a UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
pDialog.dismiss();
}
});
I think the safe way :
if(dialog.isShowing()){
dialog.dismiss();
}
I want to write a download manager app, in the activity I add a progress bar which show the current progress to the user, now if user touch the back button and re-open the activity again this ProgressBar won't be updated.
To avoid from this problem I create a single thread with unique name for each download that keep progress runnable and check if that thread is running in onResume function, if it is then clone it to the current thread and re-run the new thread again but it won't update my UI either, Any ideas !?
#Override
public void onResume()
{
super.onResume();
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
for (int i = 0; i < threadArray.length; i++)
if (threadArray[i].getName().equals(APPLICATION_ID))
{
mBackground = new Thread(threadArray[i]);
mBackground.start();
downloadProgressBar.setVisibility(View.VISIBLE);
Toast.makeText(showcaseActivity.this
, "Find that thread - okay", Toast.LENGTH_LONG).show();
}
}
private void updateProgressBar()
{
Runnable runnable = new updateProgress();
mBackground = new Thread(runnable);
mBackground.setName(APPLICATION_ID);
mBackground.start();
}
private class updateProgress implements Runnable
{
public void run()
{
while (Thread.currentThread() == mBackground)
try
{
Thread.sleep(1000);
Message setMessage = new Message();
setMessage.what = mDownloadReceiver.getProgressPercentage();
mHandler.sendMessage(setMessage);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch (Exception e)
{/* Do Nothing */}
}
}
private Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message getMessage)
{
downloadProgressBar.setIndeterminate(false);
downloadProgressBar.setProgress(getMessage.what);
if (getMessage.what == 100)
downloadProgressBar.setVisibility(View.GONE);
}
};
Download button code:
downloadBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
downloadProgressBar.setVisibility(View.VISIBLE);
downloadProgressBar.setIndeterminate(true);
downloadProgressBar.setMax(100);
Intent intent = new Intent(showcaseActivity.this, downloadManagers.class);
intent.putExtra("url", "http://test.com/t.zip");
intent.putExtra("receiver", mDownloadReceiver);
startService(intent);
updateProgressBar();
}
});
I'd strongly recommend reading the Android Developer blog post on Painless Threading. As it states, the easiest way to update your UI from another thread is using Activity.runOnUiThread.
I want to open a ProgressDialog when I click on the List Item that opens the data of the clicked Item form the Web Service.
The ProgressDialog needs to be appeared till the WebContent of the clicked Item gets opened.
I know the code of using the Progress Dialog but I don't know how to dismiss it particularly.
I have heard that Handler is to be used for dismissing the Progress Dialog but I didn't found any worth example for using the Handler ultimately.
Can anybody please tell me how can I use the Handler to dismiss the Progress Dialog?
Thanks,
david
Hi this is what you want
public void onClick(View v)
{
mDialog = new ProgressDialog(Home.this);
mDialog.setMessage("Please wait...");
mDialog.setCancelable(false);
mDialog.show();
new Thread(new Runnable()
{
#Override
public void run()
{
statusInquiry();
}
}).start();
}
here is the web webservice that is called
void statusInquiry()
{
try
{
//calling webservice
// after then of whole web part you will send handler a msg
mHandler.sendEmptyMessage(10);
}
catch (Exception e)
{
mHandler.sendEmptyMessage(1);
}
}
and here goes handler code
Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case 10:
mDialog.dismiss();
break;
}
}
}
};
A solutiion could be this:
ProgressDialog progressDialog = null;
// ...
progressDialog = ProgressDialog.show(this, "Please wait...", true);
new Thread() {
public void run() {
try{
// Grab your data
} catch (Exception e) { }
// When grabbing data is finish: Dismiss your Dialog
progressDialog.dismiss();
}
}.start();