Android AlertDialog Box Not Showing - android

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.

Related

Setting AlertDialog Text Freezes UI Thread

I have an about screen in my app that opens in an AlertDialog, in which I include the text from Google's open source API license. However, it takes almost 30 seconds to load the AlertDialog, and doing so often freezes the UI thread.
private void about() {
AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setTitle("About ...");
builder.setNeutralButton("Close",null);
Toast.makeText(this,"Loading...",Toast.LENGTH_LONG).show();
GoogleApiAvailability googleApi=GoogleApiAvailability.getInstance();
String text=googleApi.getOpenSourceSoftwareLicenseInfo(getContext());
String str=getResources().getString(R.string.about_message);
str+=text;
builder.setMessage(str);
builder.show();
}
EDIT: The line that is causing this lag is the one that sets the dialog's text.
Note: I have already tried running the whole thing in an AsyncTask, and doing so did not change anything.
If anyone else is having this problem, one solution that works is to prevent the activity from overlaying another activity (if it uses Theme.Dialog, remove that). While this does not completely speed it up, it prevents the UI thread from being frozen for as long.

solo.clickInlist(int) not working for custom listview in Robotium

I'm new to Robotium, I have two questions.
1) I'm trying to make click on custom listview item but its not working. I tried with clickInList(int) and clickInlist(int, int).
2) Handling random AlertDialog:
How to handle display alert dialog dynamically in Robotium? For example I'm using alert dialog when I get any message during call webservice, like connection failure, no internet, server error, timeout, etc..,
Thanks in advance.
There are two important things to note about the clickInList(int) method that aren't readily apparent: First, the list items are 1-indexed, so to click the first item of the list, use clickInList(1) not clickInList(0). Second, the clicking is relative to the visible items on the screen, so clickInList(1) will click the first visible item on the list, not the first item overall.
As for the dynamic handling of a Dialog, arbitrary pop-ups aren't really what Robotium was meant to handle. It's supposed to test user interaction with the app under known, controlled, repeatable conditions. If something unexpected happens in the middle of the test, such as losing connection, it should be considered a failure; There's a good chance your test wouldn't be able to run to completion anyway. As a hacky work-around, you can check for the existence of the Dialog before each of your events, something like:
if(solo.searchText("Dialog text") {
//handle closing dialog
}
However, I'd advise against this, it'll slow down your test considerably, and again, even if you close the dialog, the fact that the error happened in the first place is probably going to cause a later part of your test to fail.

Display alert dialog while running an Android test case

I am using Robotium to automate testing of an application. Is there a way I can display an alert box while executing a particular test case.
Thanks.
It is possible to do, nearly everything is possible but before I give you the answer do you have a good reason to do this? I cant easily thing of a good reason why a test should open an alert box but you may know best.
Robotium has the method.
solo.getCurrentActivity();
Using this you can get an Activity Context and with such a thing you can do pretty much anything that you could do in an android activity. The page http://developer.android.com/guide/topics/ui/dialogs.html tells us how to make a dialog, you will notice the first line calls a method to get the currentActivity, instead of that I replaced it with the robotium method above.
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(solo.getCurrentActivity());
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
this will create a dialog, then just call the dialogs .show() method to show it on the screen.
Robotium tests do not run on the UI Thread, so any code in a test method will in the best case just not work and in the worst case throw and error and cause your test to fail.
To interact with the UI from inside a test method you need to run your code on the UI Thread. This can be done by writing that code inside a Runnable, and sending that Runnable to the runOnUiThread() method of the current Activity. Robotium's solo class has the getCurrentActivity() method, which will allow this execution. Here's an example of how you'd show a Toast using this technique.
public void testDisplayToastInActivity() throws Exception
{
Runnable runnable = new Runnable
{
#Override
public void run()
{
Toast.makeText(solo.getCurrentActivity(), "Hello World", Toast.LENGTH_LONG).show();
}
}
solo.getCurrentActivity().runOnUiThread(runnable);
}
You can use runOnUiThread() to perform many other actions that interact with your Activity, such as creating Alert Dialogs, if you want something more than a Toast. However, I'd suggest against doing any of this, even though you can. Robotium and other testing frameworks are meant to judge the correctness of your application code's execution, and should not inject any logic or UI modifying behavior beyond interacting with your application the way a user would. Your tests will be cleaner if you take any outpu from your tests and log them to Logcat or a file.

How to show a dialog for an exception while halting the rest of the program flow?

I have thought out an IMHO neat way of handling checked Exceptions, like so:
protected void handleException(Throwable e, int messageResourceId, ExceptionReaction reaction) {...}
which would be part of the app's BaseActivity (thus usable in all Activities).
Within this method I intend to show a dialog with the given message string and an OK button, and afterwards do something to react individually to the Exception (restart the activity, log the user out, reset database,...).
However, the dialog is started on the UI thread non-blockingly, and the Activities having called handleException(...) would just continue execution while the dialog is shown - which sucks, because something most probably has gone very wrong and e.g. an activity-restart might be needed.
Note that the UI thread can't be put to sleep or wait, since then the OK button in the dialog would not work at all.
Has anybody got an idea how to achieve this?
Has anybody got an idea how to achieve this?
Put your "do something to react individually to the Exception" in the dialog close-button handler, such as via a final Runnable.
Have you tried UncaughtExceptionHandler?
Refer this doc Thread.UncaughtExceptionHandler
Implement this interface and do the handling stuff in the callback uncaughtException(Thread thread, Throwable ex)

android detect if a dialog is active?

Is there a generic way to determine if there is dialog currently shown ? Sure, i can keep track of all createDialog and dismissDialog invocations, but that's cumbersome.
thanks
I use this method:
protected void showDialogSafe(int id) {
if (!isFinishing()) {
showDialog(id);
}
}
Which I grabbed from here: http://daniel-codes.blogspot.com/2009/12/activities-and-dialogs.html
When dismissing them I just catch the IllegalArgumentException.
Falmarri, keeping track of the dialogs seems to be easier said than done when you have multiple threads running. I thought my code was perfect, but I get a bunch of crash reports when my app tries to dismiss dialogs that aren't shown or tries to display a dialog when the activity is finished.

Categories

Resources