Progress Dialog Box Won't appear - Android - android

I want to make a Progress Dialog Box in my app to use when sending some information. But the code I wrote won't work. It the method send() executes but the dialog box never appears because it dismisses very quickly
Here is my code :
ProgressDialog myProgressDialog = ProgressDialog.show(Tents.this,
"Please wait...", "Sending...", true);
send();
myProgressDialog.dismiss();
goFour();
How do I make the Dialog Box Last a little longer?

First of all - you should not do send() in the same thread as show() and dismiss() - because you are effectively blocking UI thread during sending. The dialog will actually never show - because in order to show it after show() is called, you need to give the control back to the main looper in UI thread and simply finish handling whatever event you are handling. Otherwise the UI thread will never have a chance to draw your dialog.
The best idea is to start running send() in AsyncTask and call dismiss() in onPostExecute() (see http://developer.android.com/reference/android/os/AsyncTask.html to get idea how to run async task).

You are probably getting a progress dialog, but having it immediately dismiss as it has nothing to wait for.
I'll pretend you want this in OnCreate for my example:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProgressDialog pd = ProgressDialog.show(this, "Please wait...", "Sending...");
new Thread(new Runnable(){
public void run() {
send();
pd.dismiss();
}
}).start();
gofour();
}
EDIT: If it still goes away immediately, make sure send(); does something that actually takes some time. ;)

The UI thread is used to start send() , this will not work and progress dialog will not be shown .
Call send in another thread or AsynTask doBackground and on completion dismiss the dialog.

If your send action is completing so quickly that the dialog is not displaying properly, might I suggest instead using an indeterminate progress bar in the upper right corner of your activity via requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS) and then utilizing setProgressBarIndeterminateVisibility(true/false).

"I guess my real question would then be how do I make it so that it lasts a little longer?" My answer would be WHY???!!!
I think you would be better showing an alert dialog to confirm your send function has completed, it would be annoying for the user having to wait for no reason!

Related

Android show toast before methdod

Because you must include a legal notice when using google maps on android I added the following code to my fragment:
//in oncreate view method
_noticeMaps.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(getActivity().getApplicationContext(), "Loading", Toast.LENGTH_LONG).show();
showLegalNotice();
}
});
public void showLegalNotice(){
_legalNotice = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getActivity());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Legal Notice");
builder.setMessage(_legalNotice);
AlertDialog dialog = builder.create();
dialog.show();
}
Because the legal notice takes a long time to be placed in the setMessage the app shows the dialog after a few seconds (5+). Thats why i added the toast before the showLegalNotice to notice the user that its loading. However the toast shows after the dialog is loaded. Why isnt the toast showing before the dialog is loading? I call showLegalNotice AFTER i create the toast. I know i can fix it with threads but I want to understand why the toast is showing after the dialog is created.
The best solution is to put the legalNotice method codes in an AsyncTask. The Toast is shown after the dialog because you are doing the heavy work on the UI thread which is making it busy and that's why the toast is lagging behind.
If you don't know about AsyncTask, you can learn about it here. You can show the Toast in the preExecute() method of the AsyncTask. It will be guaranteed that the toast will be shown before any other action is taken.
UPDATE
Yes, you are right. The code is run in a sequential manner so the Toast should have been shown before the method runs. But try to think in a different way.
The Toast is an system UI component. You call show() on toast and your code moves to the next heavy or long-running task almost instantly.
There is always a slight delay for the toasts to be drawn or initiated on your screen and it also depends on various flavours of Android. So, before the toast starts to draw on the screen, the UI thread gets busy or jammed on performing a long-running task and looses frames.
Just when the long-running task of your method ends, the UI thread gets free once again and is able to resume drawing the toast. That is why, the toast is displayed, but always after the method completed its execution.

Android - show progress dialog while doing work on UI thread

I need to do some work on the UI thread, specifically setting up some views, etc. - this can't be done in a background thread. The process is invoked on a button click and takes about a second or so to complete - without a progress dialog it looks as if the app is frozen. I use progress dialog with AsynTasks in several places and it works fine - however here I'm struggling.
I started with simple:
showDialog(DIALOG_PLEASE_WAIT);
viewInfo.setFromGuide(true); //this method just sets a variable
viewInfo.setVenue(venue); //this method does a lot of UI manipulation and takes a second or so
showScreen(VIEW_INFO); //this method shows the corresponding view in ViewFlipper
dismissDialog(DIALOG_PLEASE_WAIT);
However the dialog would not show (sort of expected, as this is all on UI thread.
Then I changed the code to this:
Handler hnd = new Handler() {
#Override
handleMessage(Message m) {
viewInfo.setFromGuide(true);
viewInfo.setVenue(venue);
showScreen(VIEW_INFO);
dismissDialog(DIALOG_PLEASE_WAIT);
}
}
showDialog(DIALOG_PLEASE_WAIT);
new Thread() {
public void run() {
hnd.sendEmptyMessage(0);
}
}.start();
This still doesn't show the dialog - naturally, the UI work in handleMessage is still done on the UI thread. So, what can I do to show the progress dialog?
If it takes really takes a second or so to complete than maybe you can just use a simple Toast notification with a message like "Please wait"
as you are using AsyncTask you can override onProgressUpdate which is called when ever you call publishProgress() from inside the doInBackGround so you can publish your results smoothly while working in background because, onProgressUpdate works on the UI thread.

Showing AlertDialog from not UI thread

I'm connecting to bluetooth in background and I want to show alert or toast befor processing socket.
Here is my code
mmSocket.connect();
connectionHandler.post(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(BluetoothSampleActivity.this);
builder.setMessage("conneted");
builder.show();
}
});
manageConnectedSocket(mmSocket);
but as I understand alert will be shown only when this will end his work. How can i show alert BEFORE executing manageConnectedSocket(mmSocket);?
P.S.: I tryed runOnUiThread - it didn't help
I suggest to move your logic from a normal Thread to an AsyncTask. Whenever you have to do heavy work but also to interact with the UI, AsyncTask is the best practice.
On the preExecute() method you show the dialog or update UI, on doInBackground you do whatever you need to do and on onPostExecute you dismiss the dialog or re-update the UI.
Here the AsyncTask doc.
En plus, if you need to show a progress of the work that you are doing in background, it comes super easy thanks to the methods publishProgress/onProgressUpdate.

Progress Dialog in Android with some background logic gives Handler Error?

Anybody has any idea about ProgressDialog of Andorid with Thread? I am successfully able to display the dialog and dismiss it also, but I have some long logic to be done and then only to dismiss the dialog, until that dialog will display loading message. I put my logic code inside the Run method of thread with While condition that until I didn't get particular result it will run the code. But somehow it is giving Handler and Looper.prepare() error. I try to found this and get to know that I have to use the functionality of Handler class.
ProgressDialog comes under UserInterface.Donot dissmis it inside thread and show before starting thread;
like this.
Thread th=new Thread(this);
ProgressDialog pd=new ProgressDialog(this);
pd.setMessage("Loading...");
pd.show();
th.start();
Now take handler class to dismiss it
void run(){
///do your work;
handler.sendEmptyMessage(0);
}
private Handler handler=new Handler(){
//override onhandle message method and dismiss dialog in it
}
For the same, you can implement AsyncTask concept, and which is very much preferable in Android to implement threading task, by implementing this task, system itself handles the threading task like start, run, stop....etc. and that's why its known as as Painless Threading.
If you have gone through AsyncTask link then i am sure you have noticed those 4 methods of AsyncTask.
For your problem, you can implement the AsyncTask as below:
onPreExecute() - Display progress dialog
doInBackground() - implement all the long running task
onPostExecute() - dismiss progress dialog by calling dialog.dismiss();
I am sure you got it now.
All the best.
Update:
you just need to write Dialog.Show() method inside the onPreExecute() method, and dialog.dismiss() inside the onPostExecute() method. And yes i have told 1000 times that you can't write Toast directly inside the doInBackground() method because Android doesn't allows to ride on the main thread, and if you still want to execute it then write the same Toast message inside the runOnUiThead method (this method should be inside the doInBackground().

Android: alert box after 3000 ms

In my program I want this alert dialog to show after 3000ms. how can I do this? I tried a lot but I couldnt. any Idea?
Help is always appreciated...!
AlertDialog.Builder successfullyLogin = new Builder(Register.this);
successfullyLogin.setCancelable(false);
successfullyLogin.setMessage("Successfully Login !");
// successfullyLogin.wait(3000);// this line is nt working
successfullyLogin.setPositiveButton("Ok",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
}
});
I think the wait function you are calling should be specifically used for multithreading...
try this...
new Thread()
{
public void run()
{
sleep(3000);
AlertDialog.Builder successfullyLogin = new Builder(LWM.this);
successfullyLogin.setCancelable(false);
successfullyLogin.setMessage("Successfully Login !").show();
}
};
The wait method is part of java.lang.Object and causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires. It's not used to implement "sleep" like functionality.
You could start an AsyncTask (that will start a background thread). In the doBackGround, you could sleep the thread for 3 seconds (not blocking the UI), and in your doPostExecute you can pop the dialog.
Instead of showing an alert box why dont u put an suucess message as a toast for 3 seconds....
or else if u want to show the alert box for 3 seconds first remove the ok button then use handlers for close the alert box...
You could use AsyncTask or Timer to accomplish that. If you use AsyncTask, sleep in the background and show the dialog in onPostExecute
The accepted answer here should give you a good head start. Just substitute toast for dialog and you're done.
How to display toast inside timer?
i.e. Use a timer to create a new thread to count down your 3 seconds, and use a handler to display your dialog or toast message on the main UI thread.
Create a Handler in your Activity's class (can be assigned local variable). Then set it up to send a sendEmptyMessageDelayed() inOnStart(). Then, in your handler, create the alert dialog. Note that, since an Activity can be terminated at any time by Android, you need to also override OnStop()in your Activity and call removeMessages() on your handler. If you don't do this, the message is left in the queue but your Activitiy will have already been terminated when the event fires. The result is a rather confusing Exception.
This approach also has the benefit of being able to terminate the message from firing in the first place. For instance, if you finish doing whatever needs to be done before then, you can simply remove the message from the queue and it won't fire.

Categories

Resources