My main question is: Is there anyway I can get trigger an AlertDialog from inside onOptionsItemSelected() without it crashing my emulator when I press a button on the dialog?
I have looked all over the internet for this but everyone I find keeps saying the same thing but even when I copy and paste their code I get the same error. So I'll try explain my situation as well as I can.
Here is an example of a pretty simple AlertDialog:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this)
.setTitle("Your Title")
.setMessage("Click yes to exit!")
.setCancelable(false)
.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Now this WORKS. As long as I run it OUTSIDE of the onOptionsItemSelected() function. For example, if I add this piece of code inside the onClickListener for a regular Button. Then the alert dialog will appear when I click the button and everything will work. However when I include this piece of code inside my onOptionsItemSelected(). Then the alert dialog will appear, but pressing a button on the dialog will crash my entire emulator. Here is my onOptionsItemSelected():
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_trash:
Log.i("trash", "button clicked");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this)
.setTitle("Your Title")
.setMessage("Click yes to exit!")
.setCancelable(false)
.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return true;
case R.id.action_help:
Log.i("help", "button clicked");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Now when I click on the item in my toolbar linked with the action_trash id. I get an alert dialog, but when I click the OK button, my entire android emulator just crashes. And the only warning I can still see is this:
Hax is enabled
Hax ram_size 0x40000000
HAX is working and emulator runs in fast virt mode.
emulator: Listening for console connections on port: 5554
emulator: Serial number of this emulator (for ADB): emulator-5554
EmuGL:WARNING: bad generic pointer 0x7fc16d378600
Which I am pretty sure is an unrelated message. I sometimes see people asking for LogCats, but there are none that I can find since the entire emulator has crashed.
And as a side question: why doesn't this even work at all? Is it because the onClickListener() made inside setNeutralButton() has somehow been destroyed? I am fairly new to android, so if this is some big nooby mistake that can be avoided in the future any advice would be appreciated.
P.S. I have also tried replacing '.Builder(this)' with '.Builder(MainActivity.this)' and all the variations I have encountered so far and none of them solve the issue.
Thanks in advance :)
I've ran into this same thing. Two separate things worked for me.
Changing the AVD settings to have "Software - GLES 2.0" instead of hardware or auto for the "Emulated Performance" option.
Turn on "Show Layout Bounds" in the developer options of the AVD.
Either of those should fix the issue, you don't need to do both.
Related
I've built an android AlertDialog (named dialog) that fires other Android AlertDialog (named dialog2) if some conditions happen.
I've checked that what if only one of them is displayed on screen it is dismissed without any problem.
Problem comes when both of them are showing, that happens when I press the OK button for the second dialog, it just closes the second dialog, despite the first dialog is even showing on screen.
This is the code related to dialog2 for that operation:
dialog2.setOnShowListener(new DialogInterface.OnShowListener()
{
#Override
public void onShow(final DialogInterface dialog)
{
Button button = ((AlertDialog)
dialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
[some more operations]
dialog2.dismiss();
dialog.dismiss();
}
});
}
});
The strangest thing is that if I supress the line dialog2.dismiss(); by leaving only dialog.dismiss(); what get dismissed is the second dialog, not the first one, looks like android somehow confuses one with the other, and I don't think that should be happening because they are created separately like this:
dialog=[code to create that dialog]
dialog2=[code to create that dialog]
Doing that the only way I see that app would close dialog2 when asked to close dialog would be doing dialog=dialog2, which I am not. I think They should be different objects loaded in memory each one with their characteristics.
I don't see any reason of why this is happening, seems like a clueless error from my point of view. Hope you can give ideas about what is happening.
A couple things to take note of here:
First, it isn't necessary to create an "onShowListener", unless you actually need to perform a task when the dialog is shown, this code should help you correctly create an AlertDialog:
new AlertDialog.Builder(getContext())
.setTitle(R.id.dialog_title)
.setMessage(R.id.dialog_message)
.setPositiveButton(R.id.positive_text, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//do onClick stuff here
}
})
.show();
This example does all your setup at once. If you need a reference to this dialog or don't want to show it right away, just use AlertDialog.Builder dialog1 = new ..., and then use dialog1.show() to create the dialog.
Second, the reason that only the second dialog is closing when you suppress dialog2.dismiss() is because there is a local variable named 'dialog' inside of your onShow() method (look at the method parameters) that is taking precedence over your broader scoped 'dialog' variable.
Third, to answer your actual question, can you dismiss the first dialog just before you show the second? I don't see any real reason to have 2 dialogs open at the same time.
I have a simple if statement check to determine if the GPS is turned on on my app.
This works perfectly on the emulator, but when installed on an actual device instead of the 'Location & security' menu being loaded as called from the intent, it is loading the AGPS option. This menu does not allow me to turn the GPS on and I have to manually naviagte to the 'Location & security' menu.
This is my alertDialog builder code. As shown using an intent to call 'ACTION_LOCATION_SOURCE_SETTINGS'.
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
To highlight the issue further ill use the following screenshots:
This is the screen I want to load through my intent:
The menu that is currently being loaded:
How do I enable my intent to load the first menu instead of the second?
I am trying to implement a dialog box that pops up when a button is pressed by the user. This currently works, however the buttons I have included in the pop up are unresponsive. I have tried the following code to try and resolve the problem.
public void showDialog()
{
final Dialog dialog= new Dialog(context);
dialog.setContentView(R.layout.dialog_info);
infoView=(EditText) dialog.findViewById(R.id.infoView);
infoView.setFocusable(false);
infoView.setText("");
dialog.setTitle(aList.get(count).toTitle());
infoView.append(aList.get(count).toDescription());
Button back=(Button)findViewById(R.id.back);
Button reminder=(Button)findViewById(R.id.reminder);
Log.e(TAG,"Testing click 1.5");
back.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.e(TAG,"Testing click 2");
dialog.dismiss();
}
});
dialog.show();
}
showDialog() gets called after a button (back) in the first view is pressed
public void onClick(View v) {
for (count =0;count<aList.size();count++)
{
if (v==buttons.get(count))
{
Log.e(TAG,"Testing click -1.1");
showDialog();
}
}
}
Correct me if I understood wrong,
your button back and reminder are a part of the dialog, so you should be getting a null pointer exception. Try finding your buttons like this
Button back=(Button)dialog.findViewById(R.id.back);
Button reminder=(Button)dialog.findViewById(R.id.reminder);
EDIT: By doing this you'll find the button inside the dialog. If you don't do this android will try to find the button in Activity itself and not the dialog .
For the Override problem please recheck that you've done the right import. (there are two kinds of import for View.onClickListner I don't remember their name right now.) You can delete your import associated with View.Onclick and try to re-import the correct package.
If this is not the case then I might have misinterpreted your question. You can check your Java Compliance level and see if its on 1.6 or not. You can check this by going to your project properties under Java Compliance Level
What version of Java are you using?
Right-click your project
Go to Properties
Go to Java Compiler
Enable project specific settings
Select 1.6 for Java compliance level
This will fix the #Override errors. If you want to use another version, you can just remove all #Override annotations.
Test device: GSM galaxy nexus 4.2 (tested with both built in keyboard and swiftkey 3)
In my app I create a dialog to prompt the user for input. The dialog displays an EditText which the user is supposed to fill in a word in. Upon creation, as well as whenever the user erases everything from the EditText I get the following error message in logcat:
SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
Googling as well as searching here on stackOverflow tells me that the error can be avoided by using something like
inputBox.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
where inputBox is the EditText in question. I however, would like to keep auto complete functionality as the user is supposed to fill in words that will most likely be autocompletable. Here is the code used to create the dialog:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText inputBox = new EditText(this);
inputBox.setHint("New keyword");
builder.setTitle(R.string.add_keyword_dialogue_header)
.setView(inputBox)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id {
mListAdapter.addItem(inputBox.getText()
.toString());
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
inputBox.requestFocus();
My question is, how can I prevent the error from occuring while retaining auto complete functionality?
Just add this property to your edittext and your problem will definitely be resolved
android:inputType="textNoSuggestions"
Add the above property to each of your edit text used in the application, or simply where you get the error in that edit text only.
I've never seen that particular error before, but my guess is that its this line that causes it:
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
That should open the soft keyboard even when the edit box isn't focused. So the input connection isn't correctly set up, leaving the keyboard with limited functionality. Setting the focus first might help it. So might using LayoutParams.SOFT_INPUT_STATE_VISIBLE without the always- it would prevent the keyboard from having a bad input connection due to not being tied to an editor.
I have been looking around and I couldn't find anything, so I don't know if its possible, but is there a way to do something on close for alertdialogs?
In my situation, I have the background UI paused while the dialog is up as its a pause screen. If you click the buttons in the dialog it will run the onClick stuff, so I have it unpausing there, but if they click off of the dialog it closes the dialog but doesn't run onClick. Is there anyway to get something to run when they click off to the side? Thanks!
You can set an onDismissListener() to listen whenever the dialog goes away. Docs.
You can use onDismissListener() but it was introduced in higher APIs so will not be compatible with older ones. You can use onCancel() instead.
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("My Titile");
alertDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//your logic
}
});
The only way to do this is to not use a AlertDialog.Builder and instead create a PopupWindow sub class.
A good example may be found here on line 37 :
https://github.com/lorensiuswlt/NewQuickAction/blob/master/src/net/londatiga/android/PopupWindows.java
You can use setCanceledOnTouchOutside(false) to force the user to click on the cancel button.
You could also (if you're using a DialogFragment) override the onDetach() method.
And finally you could set a dismiss listener.