Android show toast before methdod - android

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.

Related

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 Box Won't appear - 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!

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.

Android AlertDialog Box Not Showing

I've searched through Stackoverflow, looked at the examples in Android Developer, and some books and I'm just not getting it.
I'm trying to show an AlertDialog Box that interrupts the program flow. Most of the examples I've seen don't have code after the dialog box and I need my program to stop executing until the AlertDialog button is pressed. Seems as if the AlertDialog is created from another thread and I'm not sure how to retrieve that thread.
Program logic: If the parsing is bad the program will force close. I want to let the user know to restart the program and everything will work. (I'm dropping and recreating tables and they are repopulated when the program starts back up)
Here's some code:
if(database populated)
{
....code.....
if(parseok.contentEquals("Error"))
{
doForceClose();
}
displayDate = "Last: " + parseok; //I don't want the program to continue to here.
//Rest of code in the method. If I continue the program will Force Close
}
else
do something else
Here's the AlertDialog method:
private void doForceClose()
{
String themessage = "Because some of the parameters have changed in the yada yada";
AlertDialog.Builder ad = new AlertDialog.Builder (this);
ad.setTitle("Internal Error");
ad.setMessage(themessage);
ad.setPositiveButton("Sorry", new OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
finish();
return;
}
});
ad.create();
ad.show();
}
except ad doesn't show and the program continues to its force close.
Obviously I'm not getting something. Any ideas?
edit: I am in a Class that extends Activity
I'm trying to show an AlertDialog Box that interrupts the program flow.
That does not exist in Android and various other UI systems.
I need my program to stop executing until the AlertDialog button is pressed.
No, you don't. Event-driven programming has been in use for a couple of decades.
Program logic: If the parsing is bad the program will force close.
That's your code -- rewrite it to behave better.
I don't want the program to continue to here.
Then use an else, or a return, or something.
except ad doesn't show and the program continues to its force close.
Your dialog will not appear until the main application thread gets control again to process your request -- show() is asynchronous. You are crashing before then, most likely.
In short, your strategy for dealing with your parsing problem is fundamentally flawed.
The Commonsware response s correct. Let me try and say the same thing in different words.
An alert dialog does NOT interrupt the flow of control. It is just "left showing" when the program is waiting for input.
thus the sequence
showAlert("this is a message);
showGallery();
return;
this shows only momentarily.
A way out of this is to put the showGallery() function call inside the Positive response from the AlertDialog.
So to put it another way. If you want to interrupt the flow of your app with an AlertDialog (which is wisely pointed out is the wrong thing to want) then put the code you want executed after the dialog into the onClick callback of the AlertDialog.
OK, I had a similar situation. I was expecting a dialog to pop-up but it didn't. Instead, an exception occurred. The place where the exception occurred was positioned a couple of rows behind the place where I was expecting the dialog. I fixed this exception and then my dialog appeared.
It looks strange, and I think the dialog needs time to appear while the program just continues to run and then the program encounter the exception, chronological (but not programatically) before the dialog.
That's why I got dialog after I fixed the exception place.

Categories

Resources