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);
Related
public void exit(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher_round);
builder.setTitle("Likee Likes");
builder.setMessage("Do you really wanna Exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create();
builder.show();
}
**I am using this code to confirm my user either exit or not. when my user click the "yes" button the app doesn't close and get back to the previous activity. Is there any mistake with this code? **
i am trying to close my app by user confirmation.
I assumes you use AlertDialog in the another activity rather than your first activity, so when you use finish, you are close the activity that isn't the first activity.
If you you want to close you app, you can try use startActivityForResult to process some job accordingto the requestCode.
But now startActivityForResult is deprected, you can try to use new way to do this: OnActivityResult method is deprecated, what is the alternative?.
You can reference to this too How to quit android application programmatically
I have a custom alert dialog. I am currently trying to alter the onclicklisteners for my two buttons. Previously I have used the following code.
builder.setNegativeButton("Nope", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
\\code here which is not relevant to question
}
});
However, now since the dialog has a custom view and custom buttons, I use the following approach.
Button confirm = (Button) windowView.findViewById(R.id.confirmbutton);
Button cancel = (Button) windowView.findViewById(R.id.negatebutton);
cancel.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
}
});
My question is how do I dismiss the dialog within the cancel button listener if I can't access the dialog variable. I want to use the AlertDialog I am already using and do not want a solution with a different type of dialog.
What you need to do, is just keep a reference of the Dialog, then you can call the dismiss method. In my example, i keep the reference as a property.
private Dialog dialog;
#Override
public void onResume() {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LinearLayout llView = new LinearLayout(this);
Button btnDismiss = new Button(this);
btnDismiss.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
llView.addView(btnDismiss);
adb.setView(llView);
dialog = adb.create();
dialog.show();
super.onResume();
}
It's important keep the reference as a property, cause the reference must be final to be accessible inside the onClick method, and since the dialog it's not created yet, you cant keep the final reference in a method variable, then keep it in a property.
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!
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.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