Alert Dialog Builder wont show ArrayList - java

I have a class that retrieves ArrayList from Database. And I need to show this items in Alert Dialog builder. But im getting an error in this. Please Help!
Here is my error:
Error: The method setSingleChoiceItems(int, int,
DialogInterface.OnClickListener) in the type AlertDialog.Builder is
not applicable for the arguments (Name[], int, new
DialogInterface.OnClickListener(){})
ArrayList<Name> n_names = null;
n_names = db.getAllNames();
AlertDialog.Builder builder = new AlertDialog.Builder(Name.this);
builder.setTitle("Choose Name");
builder.setSingleChoiceItems(n_names.toArray(new Name[n_names.size()]), -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
}});
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}});
AlertDialog alert = builder.create();
alert.show();

I think the error is that you're providing a customized class object to the setSingleChoiceItems method. The first parameter has to be a a CharSequence[], a ListAdapter or a Cursor. If you're not intended to put one of them, you'll have to extend the Dialog class an implement your own setSingleChoiceItems method.
---- EDIT ----
In your case, I'd recommend extending the ArrayAdapter class, as you have some customized structures to show (in your case, a CheckBox). To help you do that, you may see my answer to a similar question and also a little basic explaination on how to extend the ArrayAdapter class, here. Hope this helps you!

Related

How to display AlertDialog in a Fragment?

I want to display an alert dialog in my app. I am using fragments. I tried the below code to do this:
AlertDialog ad = new AlertDialog.Builder(context)
.create();
ad.setCancelable(false);
ad.setTitle(title);
ad.setMessage(message);
ad.setButton(context.getString(R.string.ok_text), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
but it was crashing and the error in logcat was:
04-18 15:23:01.770: E/AndroidRuntime(9424): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
From internet I came to know that the crash is due to context issue. I had given context as
context = this.getActivity().getApplicationContext();
I don't know what is the problem with this. Can anybody help me?
Replace context with getActivity().
The ApplicationContext should not be used for tasks such as creating Dialogs. As you are in a fragment you can instead get the Activity-Context simply by calling the Fragments getActivity() method.
More Information about this question (AlertDialog in a fragment, managed inside an event):
If you call AlertDialog within an event like onClick(View v) or onLongClick(View v) you can use
public boolean onClick(View v) {
...
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(v.getContext());
...
}
Try to use DialogFragment, DialogFragment is better when you use Fragments
I have had similar issues whereby I was trying to create an AlertDialog from a Fragment. A NullPointerException arose from it. Initially I did as follows:
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
The NullPointerException occurred specifically when calling alertDialog.show() later on in the code.
But after searching the documentation for AlertDialog.Builder(), there seemed to be another way to initialize it [AlertDialog.Builder Doc], which is to include a theme/resId as shown below:
AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), R.style.Theme_AppCompat_Dialog_Alert).create();
This resolved the NullPointerException at hand. Hope this helps you as well!
I used it in an adapter inside a listView, therefore I couldn't use getActivity(). In order to make it work I used getActivity() for the context in the instantiation of the adapter in the fragment:
this.adapter = new myAdapter(getActivity(), factory);
Later in the other class (the adapter's class) I was able to use getContext()and it worked.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
AlertDialog alert= null;
AlertDialog.Builder build= new AlertDialog.Builder(getActivity());
build.setTitle("title");
build.setItems(stringarrayname, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//Toast.makeText(getActivity(), "hi", Toast.LENGTH_SHORT).show();
}
});
build.create().show();
You can try this or use DialogFragment
private void showAlert(final int position) {
new AlertDialog.Builder(getActivity().getApplicationContext())
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// deleteSuggestions(position);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
The solution is to replace by getActivity()
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity(),R.style.MaDialog);

AlertDialog - trying to understand this syntax

This is code from the book sample:
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.alert_label))
.setMessage(validationText.toString())
.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
})
.show();
I want to understand this code, please rewrite it in several statements, so that each statement makes exactly one operation. Thanks!
// Create a builder
AlertDialog.Builder adb = new AlertDialog.Builder(this);
// Set a title
adb.setTitle(getResources().getString(R.string.alert_label));
// Set the dialogs message
adb.setMessage(validationText.toString());
// Set label and even handling of the "positive button"
//
// NOTE: If you don't want to do anything here except to close the dlg
// use the next line instead (you don't have to specifiy an event handler)
// adb.setPositiveButton("Continue", null);
adb.setPositiveButton("Continue",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
});
// Show the dialog
adb.show();
Seperate statements, each executed on a normal builder object.
Alternatively you can chain builder methods to save a few chars (like your orginal source), though you can write it more readable. To do so remove the semicolons and the object reference at the beginning of each line. Each builder method returns the original builder object, which you can use to run the next statement on it.
Here's a small, better readable example for that:
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("42 is the answer")
.show();
AlertDialog.Builder has numerous methods that all return the AlertDialog.Builder they operate on.
This allows you to write:
builder.A();
builder.B();
builder.C() ;
as
builder.A().B().C();
I find this extra annoying, but that's just me.
AlerDialog.Builder d = new AlertDialog.Builder(this); // get an Object of AlertDialog.Builder
d.setTitle(getResources().getString(R.string.alert_label)); //Set its title
d.setMessage(validationText.toString()); //set message body
d.setPositiveButton("Continue",new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
}); //this dialog will have single button called Continue
d.show(); // this pops up the dialog..
This technic is known as Method chaining
try putting line breaks before each . Then it'll be more readable.
new AlertDialog.Builder(this)
.setTitle(
getResources().getString(R.string.alert_label))
.setMessage(validationText.toString()).setPositiveButton("Continue",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
})
.show();

Creating a simple yes/no dialog box in a view (Android)

I've got an onCreateDialog method in my activity, which has a case switch to bring up different dialogs that I want to display depending on the request.
I cannot use the showDialog() method from my view because it's not accessible from the context that is passed when the view is created. At least, I can't find a way to access it.
How do I use showDialog from my application's view? Do I need to create a listener? And if so, how? Is there a better method?
Here is my onCreateDialog code that exists in my application's activity:
protected Dialog onCreateDialog(int id) {
AlertDialog alert=null;
switch(id) {
case DIALOG_GAMEOVER_ID:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You died. Play again?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//init();
//oGameState = eGameState.PLAYING;
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
alert = builder.create();
break;
default:
break;
}
return alert;
}
I tried passing a reference to my activity, and I get crashes. Perhaps I am doing it wrong?
In my activity:
// set our MainView as the View
oNebulaMainView = new NebulaMainView(this, this);
setContentView(oNebulaMainView);
In my view:
public NebulaMainView(Context context, Activity oActivity) {
super(context);
// adding the callback (this) to the surface holder to intercept events
getHolder().addCallback(this);
// create the game loop thread
thread = new NebulaMainThread(getHolder(), this);
setFocusable(true);
oActivity.showDialog(DIALOG_GAMEOVER_ID);
}
I may be missing something here, but what is stopping you from just calling:
alert.show()
Just make the alert accessible to the view, and call that form inside your view.
declare alert as an instance variable

AlertDialog not displaying file list

AlertDialog.Builder load_alert = new AlertDialog.Builder(this);
File list = new File("data/data/project/databases/");
if(!list.exists() || !list.isDirectory()){
return;
}
String [] fileList = list.list();
load_alert.setMessage("Please select");
load_alert.setItems(fileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast toast = Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG);
toast.show();
}
});
load_alert.show();
This is supposed to display the content of my database folder into an alertdialog. I've checked the fileList array, and it is being populated. For some reason it just isn't displaying via setItems. Any ideas?
I realize I'm a little late to the ballgame and that you have probably already solved your problem, but I was having the same issue and I figured out what the problem was.
Apparently, when you call .setMessage(), that overrides the setItems() declaration and turns the AlertDialog into a message dialog. Instead, call .setTitle() to set the title of the dialog.
Also, in your example you don't seem to call .create(), so it should be load_alert.create().show(). Presumably that's a transcription error, though, because I think AlertDialog.Builder doesn't have a show() method.
Even I am late in posting
but here is what i tried and was able to display all the folders.
AlertDialog.Builder listAlert = new AlertDialog.Builder(this);
String [] filelist = path.list();
listAlert.setTitle("Select Definition File");
listAlert.setItems(filelist, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Stuffs to do after you have selected folder or file.
}
}).show();
and at some point in my code i have
private File path = new File(Environment.getExternalStorageDirectory()+"");
Thanks

In Android how to set image in DialogBox?

I created a dialogBox in my Android application.i want to show with image in that dialog Box.But i Cannot create image.kindly help me.
Thanks in Advance
here my Coding;
public void createbtnteam_adelaide()
{
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setMessage("What kind of Banner do you Want to Create?");
//my new code
ImageView image = (ImageView) alertDialog.findViewById(R.drawable.team_brisbane);
image.setImageResource(R.drawable.team_brisbane);
alertDialog.setButton("Text Only", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.setButton2("Text+Image", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
}
i have Small icon in team_gwsid(imageid).
The Android Developer site has an excellent article on how to create dialogs in Android, including custom dialogs. I think you solve your problem by having a look at that, it's pretty easy to do.
Here's the link: http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog
By the way (not related to this question): I see you've asked six questions here on StackOverflow, and haven't accepted any of them. This is usually what you do when someone helps you to solve your problems.
There ia a alertDialog.setView(View view) method that enables you to set a custom view.
This does not affect the buttons or the titlebar.
In standard dialog the icon is shown only if you set title too. You have to use setTitle to see result of setIcon. Icon is shown in title of the dialog.
You can use Set icon or SetTitle to Display the Images in DialogBox. Read this Tutorial
public void createbtnteam_adelaide()
{
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.drawable.team_adelaide);
alertDialog.setTitle("What kind of Banner do you Want to Create?");
alertDialog.setButton("Text Only", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.setButton2("Text+Image", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}

Categories