Android - progress dialog for an "syncronous" task - android

When my app is used for the first time i am performing some data setup etc that takes a "random" time to complete, whilst this is going on i'm showing a progress dialog to the user telling them whats going on and presenting a spinning wheel, this is all done via an async task as the many docs and guides say is the only way to go about using a progress dialog.
but my problem is i need everything else in my app to "wait" for the data setup to be finished before it goes about its business but still keep the handy dialog telling the user whats going on, im struggling to find how to go about this.
if anyone has any ideas that be great.

You can use Threads for doing data setup , and handlers for implementation after the work in thread is over..
See Below
ProgressDialog pd = ProgressDialog.show(this,"Please Wait..", "Data Setup in Progress..", false, true);
pd.setCanceledOnTouchOutside(false);
Thread tDataSetup = new Thread(
new Runnable()
{
#Override
public void run()
{
//Insert the data setup code here..
if(dataSetupDone)
handlerDataSetup.sendEmptyMessage(OPERATION_COMPLETED);
else
handlerDataSetup.sendEmptyMessage(OPERATION_NOT_COMPLETED);
}
});
tDataSetup.start();
private Handler handlerDataSetup = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(pd.isShowing())
{
pd.dismiss();
}
if(msg.what == OPERATION_COMPLETED)
//Code after the data Setup done , to be implemented here..
else if(msg.what == OPERATION_NOT_COMPLETED)
//Code if data setup fails..
}
};

Something like this should work:
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
// your vairiable time stuff here
// To dismiss the dialog
progress.dismiss();
if you need to update your progress dialog after finishing some work you can do something like
progress.setMessage("I have a new message now");

Related

Why is the ProgressDialog not being dismissed, in this case?

There are a number of questions involving the lack of ability to dismiss a ProgressDialog, but none of them seem to cover my situation.
I have a Thread that runs a Runnable object that, when it completes, sends a message to a Handler object which I'm certain is sitting on the same thread as the ProgressDialog. The handler does this:
if(progressDialog != null){
Log.w(TAG, "Progress dialog is dismissed");
progressDialog.dismiss();
}else{
Log.w(TAG, "Progress dialog is null");
}
I've done this a million times before, and it's worked. The ProgressDialog goes away. But, in one particular instance, it doesn't.
In this particular case, a ProgressDialog (we'll call uploadChangesDialog) is showing, then a particular Handler (uploadChangesHandler) is called. After dismissing the uploadChangesDialog, it does a check that, if true, starts a different ProgressDialog (refreshViewDialog) and a Runnable (refreshViewRunnable) in a Thread. However, when it's Handler is called (refreshViewHandler), it can't close the dialog. But it does log Progress dialog is dismissed.
This is particularly strange, because the refreshViewsRunnable is run when the Activity is started, too, but it can get rid of the dialog then, just fine. The progressDialog variable above is the only one of it's kind, which is supposed to hold whatever ProgressDialog is currently showing.
I've done this with AlertDialogs before, but they know how to close themselves, so if I'm doing something wrong, then I wouldn't have noticed.
In the onCreateDialog() method:
case DIALOG_REFRESH_VIEW:
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading details...");
progressDialog.setCancelable(false);
return progressDialog;
Copied for each instance, with a different message. I did change it to all dialogs pointing to the same code, and setting the message in onPrepareDialog(), but that didn't change any behaviour.
In the UploadChangesRunnable:
public void run(){
int result = 0;
if(uploadChanges()){
result = 1;
}
uploadChangesHandler.sendEmptyMessage(result);
}
And then in uploadChangesHandler:
public void handleMessage(Message msg){
if(progressDialog != null){
progressDialog.dismiss();
}
if(msg.what == 0){
showDialog(DIALOG_UPLOAD_CHANGES_FAILED); //This is an AlertDialog
}else{
//All this does is showDialog(DIALOG_REFRESH_VIEW) then run the thread.
//This method is in the enclosing Activity class.
refreshViewInThread();
}
}
Finally, the refreshViewInThread method:
private void refreshViewInThread(){
showDialog(DIALOG_REFRESH_VIEW);
Thread thread = new Thread(new RefreshViewRunnable(refreshViewHandler));
thread.start();
}
And the RefreshViewRunnable looks remarkably similar to the UploadChangesRunnable.
There must be some special case that makes me lose the link to my progressDialog, and the dialog that I'm dismissing is likely not the dialog that is showing, but I can't think of how that could be. Any ideas?
my guess is that this is a context/handler issue. I had a similar problem, and decided to use interfaces/callbacks instead of Handler, and it fixed my problem.
However, you could try the following, where you see this: >> But it does log Progress dialog is dismissed.<< , add:
MyActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
});

Android Programming: I cannot get data from a background thread AND show a progress dialog

Sorry, the title is a bit hard to understand but I'm not 100% sure as to what to ask. its easier to show you the code and see if you understand from that. I found the way to use the progress dialog from another post on here, so this is basically adding onto that post. ( ProgressDialog not showing until after function finishes )
btw, this is using eclipse environment with the android plugin.
final MyClass mc = new MyClass(text,info, this);
final ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
Thread t = new Thread(new Runnable()
{
public void run()
{
// keep sure that this operations
// are thread-safe!
Looper.prepare(); //I had to include this to prevent force close error
mc.doStuff();//does ALOT of stuff and takes about 30 seconds to complete... which is why i want it in a seperate thread
runOnUiThread(new Runnable()
{
#Override
public void run() {
if(dialog.isShowing())
dialog.dismiss();
}
});
}
});
t.start();
tmp = mc.getStuff();
now the issue is that tmp is always null because mc isnt finished doing stuff. So, if i do this it finishes doing stuff, but doesnt show the progress dialog..
t.start();
while(t.isAlive());//noop
tmp = mc.getStuff();
Any thoughts or ideas would be greatly appreciated!
In your second attempt, you are making the main thread wait for the new thread to complete.
The runnable in the runOnUiThread call is where you want to do tmp = mc.getStuff();
That will then be executed on the main thread after mc has finished doStuff().
But otherwise, check out the link blindstuff commented, it simplifies threading.

progress dialog not showing in android?

when does the progress dialog not show in android? i want to know the circumstances when the above can happen:
in my case the progress dialog was not showing in this case:
func{
progressdialog.show();
....
.....
anotherfunction();
listview.setAdapter();
progressdialog.dismiss();
}
what is the general rule of thumb with dialog boxes?
thank you in advance.
EDIT
when the .show() command is executed the progress dialog should show. But when the otherfucntion() is called, does the previous command of progressdialog show stop?
Seems like you need to use AsyncTask the UI (including the progressDialog) will not update if the UI thread is still busy. There are many examples in SO for that.
And as a rule of thumb - if you need Progress dialog - you need AsyncTask.
It is not that any command stops, it is just that if you execute a sequence of methods on the UI thread, the UI will probably not be updated until the sequence is over, which is after progressDialog.dismiss(), so the progressDialog should not be displayed anymore.
I think You have to do this in your activity.
ProgressDialog _progressDialog = ProgressDialog.show(this,"Saving Data","Please wait......");
settintAdater();
private void settingAdater(){
Thread _thread = new Thread(){
public void run() {
Message _msg = new Message();
_msg.what = 1;
// Do your task where you want to rerieve data to set in adapet
YourCalss.this._handle.sendMessage(_msg);
};
};
_thread.start();
}
Handler _handle = new Handler(){
public void handleMessage(Message msg) {
switch(msg.what){
case 1:
_progressDialog.dismiss();
listview.setAdapter();
}
}
}
To show a ProgressDialog use
ProgressDialog progressDialog = ProgressDialog.show(PrintMain.this, "",
"Uploading Document. Please wait...", true);
And when you have completed your task use
progressDialog.dismiss();
to dismiss the ProgressDialog ..
You can call to show the ProgressDialog in your onPreExecute method of AsyncTask class and when your done dismiss it in the onPostExecute method

Android: ProgressDialog doesn't show

I'm trying to create a ProgressDialog for an Android-App (just a simple one showing the user that stuff is happening, no buttons or anything) but I can't get it right. I've been through forums and tutorials as well as the Sample-Code that comes with the SDK, but to no avail.
This is what I got:
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
(...)
ProgressDialog pd = new ProgressDialog(MyApp.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Working...");
pd.setIndeterminate(true);
pd.setCancelable(false);
// now fetch the results
(...long time calculations here...)
// remove progress dialog
pd.dismiss();
I've also tried adding pd.show(); and messed around with the parameter in new ProgressDialog resulting in nothing at all (except errors that the chosen parameter won't work), meaning: the ProgressDialog won't ever show up. The app just keeps running as if I never added the dialog.
I don't know if I'm creating the dialog at the right place, I moved it around a bit but that, too, didnt't help. Maybe I'm in the wrong context? The above code is inside private ViewGroup _createInputForm() in MyApp.
Any hint is appreciated,
you have to call pd.show before the long calculation starts and then the calculation has to run in a separate thread. A soon as this thread is finished, you have to call pd.dismiss() to close the prgoress dialog.
here you can see an example:
the progressdialog is created and displayed and a thread is called to run a heavy calculation:
#Override
public void onClick(View v) {
pd = ProgressDialog.show(lexs, "Search", "Searching...", true, false);
Search search = new Search( ... );
SearchThread searchThread = new SearchThread(search);
searchThread.start();
}
and here the thread:
private class SearchThread extends Thread {
private Search search;
public SearchThread(Search search) {
this.search = search;
}
#Override
public void run() {
search.search();
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
displaySearchResults(search);
pd.dismiss();
}
};
}
I am giving you a solution for it,
try this...
First define the Progress Dialog in the Activity before onCreate() method
private ProgressDialog progressDialog;
Now in the onCreate method you might have the Any button click on which you will change the Activity on any action. Just set the Progress Bar there.
progressDialog = ProgressDialog.show(FoodDriveModule.this, "", "Loading...");
Now use thread to handle the Progress Bar to Display and hide
new Thread()
{
public void run()
{
try
{
sleep(1500);
// do the background process or any work that takes time to see progress dialog
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
// dismiss the progress dialog
progressDialog.dismiss();
}
}.start();
That is all!
Progress Dialog doesn't show because you have to use a separated thread. The best practices in Android is to use AsyncTask ( highly recommended ).
See also this answer.
This is also possible by using AsyncTask. This class creates a thread for you. You should subclass it and fill in the doInBackground(...) method.

Android - Loading, please wait

Is there a standard "Loading, please wait" dialog I can use in Android development, when I invoke some AsyncTask (downloading some data from remote service for example)?
You mean something like an indeterminate ProgressDialog?
Edit: i.e.
ProgressDialog dialog = ProgressDialog.show(context, "Loading", "Please wait...", true);
then call dialog.dismiss() when done.
If you implement runnable as well as extending Activity then you could handle the code like this...
private ProgressDialog pDialog;
public void downloadData() {
pDialog = ProgressDialog.show(this, "Downloading Data..", "Please wait", true,false);
Thread thread = new Thread(this);
thread.start();
}
public void run() {
// add downloading code here
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pDialog().dismiss();
// handle the result here
}
};
It's worth mentioning that you can set the content view of the progress dialog so you can display a custom message / image:)
pDialog.setContentView(R.layout.X);
Mirko is basically correct, however there are two things to note:
ProgressDialog.show() is a shortcut that automatically creates a dialog. Unlike other dialogs, it should NOT be used in onCreateDialog(), as it will cause errors in Android 1.5.
There are some further issues with AsyncTask + ProgressDialog + screen orientation changes that you should be aware of - check this out.

Categories

Resources