Android dialog setNegativeButton without listener - android

Curiosity question here.
I use a lot of dialogs builders and most of the time my negative cancel button do nothing except dismiss the dialog. The code I found everywhere on the web is this :
builder.setNegativeButton(
"cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
I happened to find out that this code do exactly the same :
builder.setNegativeButton("cancel", null);
So my question is then : is that a bad habit not to manually dismiss the dialog, and if yes why ?

It is somewhat documented behaviour, see:
http://developer.android.com/guide/topics/ui/dialogs.html#DismissingADialog
When the user touches any of the action buttons created with an AlertDialog.Builder, the system dismisses the dialog for you.
So with null listener you exercise this implicit documented behaviour of Dialog.
What can go possibly wrong? (yeah, I think there's at least 50% chance that some custom ROM out there is not behaving properly... then again, who cares about custom ROMs failing to follow documented behavior, I don't any more, too much of that BS).

I learned this myself in an Android course in school. Basically, you only need to implement the button listener if you need additional functionality.
So it is not "habit" to include the click listener, it is just clear intent.

Related

Build dialog one after one in a loop

I have this function where I need to return a list depending of what user pressed in Alert Dialog (cancel or save).
But I have an issue, let's imagine we have a list with a size of 10. Then on the iteration of that list it will build 10 alert dialogs at the same time plus a dark black shadow at the background caused by these.
So I'd like to "pause" until user pressed or find a way to don't pop up all these alert dialog at the same time and just appear one by one once pressed a button.
A quick reminder: I need to return a list after all dialogs have been pressed.
Question: How could I do that?
It would be better if you provided some code with this. Anyway, even though this is not something I would do and create 10 dialogs in the for loop, this can be done.
Just create a Boolean inside your for loop which will be used to check if the dialog is dismissed.
for(int i = 0; i < list.size(); ++i) {
Boolean isDismissed = false;
AlertDialog d = new AlertDialog(getBaseContext());
d.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
isDismissed = true;
}
});
//start your dialog
while(!isDismissed) {
//do nothing
}
}
As I said, I wouldn't do this.
Because I evaluate first a list of items, then I set on a new list of items that will require user to confirm about what to do with that, so I loop that with alert dialogs waiting for user to tell me what to do with those items
There is a much better way to do this. Why not starting one CustomDialog which will ask the user what to do with those items. He could choose options for each item with a spinner or if options are KEEP or DELETE just use checkbox or something.
So as people said, creating Alert Dialogs in a loop is a bad practice so my solution into this is just setting a view on Fragment that acts like a Dialog but I just turn it visible and gone whenever I need. This seems a proper solution for my case.
When user accept or cancel the view (clicking on button) just send it to the viewmodel and the viewmodel will evaluate if there are still items on the list. If there are items then show again this "view" on Fragment asking to user what to do :)
I don't have code to show because I haven't done it yet but I have thought for a while and this is the best I can think about. Hope it helps for someone who is in the same situation!

Understanding the AlertDialog creation on android

I'm new to Android, only three days mostly studying the basics. I ended up with this code while studying the creation of an android alert dialog:
OnClickListener oclBtnOk = new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Add your code for the button here.
}
});
alertDialog.show();
}
};
But I still have somethings to get known:
1- First time I made the code I was using AlertDialog alertDialog = new AlertDialog.Builder(this).create(); instead AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();. The first code wans't compiling, so, what exactly is the difference? That means the dialog builder is son or has some dependency with the MaiActivity? That means the listener from this dialog is inside the main activity?
2- Is this really the correct way to create a simple alert dialog? 'cause in my console I saw one red line saying "ActivityManager: Warning: Activity not started, its current task has been brought to the front" and also studying through http://developer.android.com/guide/topics/ui/dialogs.html what they recommend is to use AlertDialogFragment as container of my dialog..
And my last question is a little bit more complicated but a simple answer as "Yes" to lead me I a deeper research would help- android has some sort of EDT (Event Dispatch Thread) since is based on java? I mean, to process graphics (like progress bars) should I separate them into another thread?
AlertDialog.Builder requires a Context. The code is in an OnClickListener anonymous subclass and it is not a Context. this refers to the subclass instance. To refer to the this of the parent activity class, it's scoped as MainActivity.this, and activities are Contexts.
It's all right at this point of your learning curve. The "Warning: Activity not started, its current task has been brought to the front" is nothing to worry about - the app was already running and was just brought to front, not re-launched.
Android does not run AWT and there's no EDT by that name. However, the main thread (also called the UI thread) does something similar.
To answer your first question:
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
The code is running in an anonymous class, so this does not reference an object derived from Context. Adding the MainActivity. makes the argument reference an Activity which is derived from Context
Your second question: Is this really the correct way....?
It is certainly one acceptable way. There are others.
The message you are seeing about bringing the activity to the front is not related to dialogs. You may eliminate it by exiting from your application before starting a new debug session.

Best Practice for Dialog for Selecting a Bookmark

I haven't written any code for this yet, but I've been researching how to implement bookmarks in my custom web browser. From what I've read, I believe the way to go is to show the user a dialog (I saw this article on how to return the value from the dialog) containing, I think, a ListView for the bookmarks... I'm honestly stuck at something pretty simple - how to present the bookmarks to the user and select one.
So, where my questions:
what's "best practice" for displaying a list to the user and having
him select one?
is doing this in a Dialog "best practice"?
Thanks.
The classic way to do this (pre 3.0) is to use simple Dialogs, that you manage with your current Activity. The easiest way to go is to use the AlertDialogBuilder to build the dialog, see here, around the middle, the "Adding a list" section. This way you get a Dialog with a list, and the user can select exactly one entry from that list.
Nowadays however, you should be using DialogFragments, with the (not so) new Fragment framework. You can use the official compatibility lib to make fragments work on older Android builds. In a DialogFragment, you can either show any UI layout you want if you override the onCreateView(...) callback, or you can define the looks and behavior by using the "onCreateDialog(...)" callback (you can use AlertDialogBuilder here, too). See the link for examples.
The DialogFragment based solution is more self-contained and you can easily call/show it from any place in your Application.
And yes, I do think that a single-select list-based dialog can be considered the "best practice" in this kind of situation. However, the other advantage of the DialogFragment based solution is, that you're not forced to show it in Dialog-style, you can also embed it into an Activity's layout as a standard fragment if that's what you want.
Best is the to show a dialog with a list and upon user selection navigate to either browser or webview.
you can use the below code to present a dialog to user::
String[] yourarraylist = new String[]{"A","B","C","D","E","F","G"};
AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this);
builder.setTitle("title");
builder.setSingleChoiceItems(yourarraylist, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), yourarraylist[item], Toast.LENGTH_SHORT).show();
//launch web browser or webview
alert.dismiss();
}
});
alert = builder.create();
alert.show();
you can launch web browser as below::
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
Also for opening the url in webview you can refer my blog at this LINK
I would personally use another activity to display the bookmarks rather than using a dialog. The user could have a large number of bookmarks saved and a dialog I don't think would be the best way.
I would make another activty which extends ListView and display the bookmarks on a list or even better a gridview with the thumbnail of the bookmark. Then by clicking a bookmark will return to the main activity refreshing the browser with the selected bookmark.
No need for dialogs, unless you like to create a longpressclick or context menu to show a dialog for deleting/editing/.. bookmarks.
The alertdialog.builder is the quickest and easiest way to build dialog. As another tip to build dialogs with alertdialog.builder. The builder has a setview to give it any view you want to the dialog, this view can basically be a linearLayout with lost more view already in it creating a complex dialog view.
final AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setTitle(getResources().getString(R.string.dialog_title));
ad.setView(dialogLayout);

Android AlertDialog won't display

I have an app that shows a welcome screen via an alert dialog. I use the following code in the onCreate method of the Activity:
wsBuilder = new AlertDialog.Builder(this);
wsBuilder.setIcon(android.R.drawable.ic_dialog_alert);
wsBuilder.setTitle(R.string.instructions_title);
wsBuilder.setMessage(R.string.welcome_1);
wsBuilder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
wsBuilder.show();
When I start the app, most of the time the screen darkens like it does when the dialog is going to
display, but the dialog never shows up. The screen just stays darkened and none of the touch events get through. I can click the back button on the phone to dismiss the dialog and then the app works like normal, but I can't figure out why the dialog doesn't fully display. Once in a while the dialog actually displays, but most of the time it doesn't.
Any help in running down this issue would be greatly appreciated.
OnCreate may not be the best place for it as the application is loading try using it onStart
public void onStart()
{
//Your code here
}
Activity would be better for wellcome screen.

Dialog Problem (result without onclicklistener?)

Ist there a possibility to do something like that:
int selected_value = Dialog("This dialog show a combobox, i want to know which item is selected")
Or
String typed_chars = Dialog("This Dialog show a TextBox, i want to know the typed chars")
It is strongly recommended, that the code will stop while the dialog is shown and resume after dismissing the dialog, like the "showdialogforresult" method in c# or vb.net, I have to show lots of Dialogs and every dialog depends on former choices, I will become crazy if i have to code this with listener or callbacks...
While I don't think this is exactly possible like you do it, you do not need to code an anonymous class per Button callback.
Instead you can designate one class that implements DialogInterface.OnClickListener() and which you specify for all of the buttons. Its onClick() callback gets the information about which Dialog was invoked and which button was clicked. So you can operate within this onClick() method with some switch/case or if/else cascades.
Not perfect, but won't make you crazy :)

Categories

Resources