Detect Back Button Event when Dialog is Open - java

I'm building an app that has 2 dialogues that open up and I want something to occur if the user presses the back button while certain dialogues are open. However, for some reason, the back button event is not registering when the dialogues are open. I tested it by putting a log in onBackPressed() and whenever the dialogues are NOT open and I'm simply on the main activity, the logs appear on logcat. However, if the dialogues are open, I simply get this:
W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
Below I have placed the code for the dialogues:
public void pair() {
final Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
AlertDialog.Builder pairedList = new AlertDialog.Builder(this);
pairedList.setTitle("Paired Devices");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_singlechoice);
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
arrayAdapter.add(device.getName());
}
}
pairedList.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.disable();
// pair_dialog = false;
}
});
pairedList.setPositiveButton("Pair New", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS), 0);
}
});
pairedList.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// connect_dialog = true;
String strName = arrayAdapter.getItem(which);
AlertDialog.Builder builderInner = new AlertDialog.Builder(MainActivity.this);
builderInner.setMessage(strName);
builderInner.setTitle("Connect To:");
builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (BluetoothDevice device : pairedDevices) {
if(device.getName().equals(strName)){
paired = device;
dialog.dismiss();
}
}
}
});
builderInner.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// connect_dialog = false;
pairedList.show();
}
});
builderInner.show();
}
});
pairedList.show();
// pair_dialog = true;
}
Below is my onBackPressed() method which is right after the above method. Nothing out of the ordinary, I don't think.
#Override
public void onBackPressed() {
Log.e(TAG, "Back Button Pressed");
super.onBackPressed();
}
Like I said, if the dialogues are not open, the log shows up just fine in logcat but if the dialogues are open, it's like the back button doesn't register.

this worked for me...
yuordialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//your stuff....
}
return true;
}
});

If you have added,
dialog.setCancelable(false);
change it to,
dialog.setCancelable(true);
Actually, setCancelable(false) cancel the event of touch outside the dialog and back press also.

You can also use
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//your dismiss code here
}
});
This listens to both backpress events and dismiss by touch.

Related

How can I stop same alert dialog showing every time from handler?

I have an AlertDialog on a method and the method is used inside a Handler. When the Handler running every time the AlertDialog also loading again and again, I want to show the dialog one time if the dialog is still showing I don't want to load it again. For this I have the below code but not working.
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 1000);
checkCountry();
}
};
handler.postDelayed(runnable, 1000);
public void checkCountry() {
alertDialogueBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogueBuilder.setTitle("VPN Detected!");
alertDialogueBuilder.setMessage("Please Turn Of VPN To Continue!");
alertDialogueBuilder.setIcon(R.drawable.errorstop);
alertDialogueBuilder.setCancelable(false);
alertDialogueBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = alertDialogueBuilder.create();
if(alertDialog.isShowing()){
//Do Something
}else{
alertDialog.show();
}
}
Create your Dialog only once and not every time:
private AlertDialog alertDialog;
// ...
initDialog();
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 1000);
checkCountry();
}
};
handler.postDelayed(runnable, 1000);
//...
public void initDialog() {
alertDialogueBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogueBuilder.setTitle("VPN Detected!");
alertDialogueBuilder.setMessage("Please Turn Of VPN To Continue!");
alertDialogueBuilder.setIcon(R.drawable.errorstop);
alertDialogueBuilder.setCancelable(false);
alertDialogueBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog = alertDialogueBuilder.create();
}
public void checkCountry() {
if(alertDialog.isShowing()){
//Do Something
}else{
alertDialog.show();
}
}
To show only 1-time dialog call only this checkCountry() method from which you want to show this dialog. And, please remove the Handler code. No need to use Handler here. Use only checkCountry() method to show the dialog.
The oldest trick in the book is to just make a boolean field "isAlertDialogShown" with false initialization, upon creation to true and in the onClick set it to false again (if you want it to be shown again when the handler fires).
private boolean isShown = false;
public void checkCountry() {
if (isShown){
//do something
return;
}
isShown = true;
alertDialogueBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogueBuilder.setTitle("VPN Detected!");
alertDialogueBuilder.setMessage("Please Turn Of VPN To Continue!");
alertDialogueBuilder.setIcon(R.drawable.errorstop);
alertDialogueBuilder.setCancelable(false);
alertDialogueBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
isShown = false;
finish();
}
});
AlertDialog alertDialog = alertDialogueBuilder.create();
alertDialog.show();
}
if you want to try and use the alertDialog isShowing you need to use the one you created and not the new one, so again save it as a field,
but you will still might have an edge case if the handler timer is running too fast, and that is alertDialog.show() is not an immediate operation:
AlertDialog alertDialog;
public void checkCountry() {
if ( alertDialog != null && alertDialog.isShowing){
//do something
return;
}
alertDialogueBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogueBuilder.setTitle("VPN Detected!");
alertDialogueBuilder.setMessage("Please Turn Of VPN To Continue!");
alertDialogueBuilder.setIcon(R.drawable.errorstop);
alertDialogueBuilder.setCancelable(false);
alertDialogueBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog = alertDialogueBuilder.create();
alertDialog.show();
}

I want to dismiss the dialog box as soon as it is connected to internet

Here I want to show two dialog boxes...one for if there is net connection available and other if there is no connection..but i want that when one dialog box is shown, the other dialogue box should be dismissed .......dismiss() is not working in this case....and somehow if I use AlertDialog instead of AlertDialog.Builder to use dismiss(), then i am not able give setPositive, setNegative and setNeutral buttons....any help will be appreciated.......
BroadcastReceiver br;
#Override
protected void onCreate(Bundle savedInstanceState) {
...........//
getStarted();
}
private void getStarted() {
if (br == null) {
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
...............//
if (state == NetworkInfo.State.CONNECTED) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setCancelable(false);
builder1.setTitle("Connected");
builder1.setMessage("Online");
builder1.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder1.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
builder.setTitle("No Internet ");
builder.setMessage("Offline");
builder.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder.show();
}
}
};
final IntentFilter if = new IntentFilter();
if.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(br, if);
}
}
}
Dismiss Your dialog if NetworkInfo.State.CONNECTED is connected,Please change builder1.show(); into builder1.dismiss();
if (state == NetworkInfo.State.CONNECTED) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setCancelable(false);
builder1.setTitle("Connected");
builder1.setMessage("Online");
builder1.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder1.dismiss();
}
Use broadcast receiver to react when the connection is changed with intent filter android.net.ConnectivityManager.CONNECTIVITY_ACTION. So, you can do your stuffs when the receiver receive the intent (or there connection is changed). See here.

Alert Dialog with EditText closes if input is empty

I have alert dialog with edit text. User must enter something and if not and then system should alert him that this input is required.
This is code for Alter Dialog:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Razlog storniranja?");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setSingleLine(false);
input.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("Spremi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Otkaži", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if (m_Text.length()==0)
{
input.setHint("Morate upisati razlog storniranja kartice (naloga)!");
input.setError("Upišite razlog storniranja!");
}
}
});
builder.show();
But when user click on positive button and input is empty the dialog is closed. Is something missing in my code to avoid closing dialog?
EDIT
I think I found solution. The last line builder.show(); should be deleted and instead, this piece of code should be added:
builder.setView(input);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean wantToCloseDialog = (input.getText().toString().trim().isEmpty());
// if EditText is empty disable closing on possitive button
if (!wantToCloseDialog) {
input.setHint("Morate upisati razlog storniranja kartice (naloga)!");
input.setError("Upišite razlog storniranja!");
alertDialog.dismiss();
}
}
});
I hope this will help others.
Well, I do not have any clue of what you are trying to do.
The error that I had when using your code was:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
m_Text needs to be initialized.
in case m_Text is not initialized, on the onDismiss method you might need to change:
if (m_Text != null && m_Text.length()==0){ //this line
input.setHint("Morate upisati razlog storniranja kartice (naloga)!");
input.setError("Upišite razlog storniranja!");
}
Regarding the cancelable, you need to builder.cancelable(false); and whenever needed, builder.dismiss().
builder.setPositiveButton("Spremi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
if (m_Text.isEmpty()) {
input.setHint("Morate upisati razlog storniranja kartice (naloga)!");
input.setError("Upišite razlog storniranja!");
input.setFocusable(true);
}else{
dialog.dismiss();
}
}
});
Use TextUtils.isEmpty() to check the empty string.
Try this:
builder.setPositiveButton("Spremi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(TextUtils.isEmpty(input.getText().toString())) {
// Empty
input.setError("Input is required!");
} else {
// Do something...
}
}
});
Hope this will help~

why I can't get my alertdialog.builder to show() on my screen

I am trying to get a number of cards to pop up using alertdialog.builder. Even though I did .create().show(); the dialog does not show on my screen. I'm not sure what is causing this problem.
I have marked the place where I am getting nothing in the comments.
Java Code:
ImageView image_questionmark= new ImageView(this);
final ImageView image_pass = new ImageView(this);
final ImageView image_youpay = new ImageView(this);
image_questionmark.setImageResource(R.drawable.card_questionmark);
image_pass.setImageResource(R.drawable.card_pass);
image_youpay.setImageResource(R.drawable.card_youpay);
AlertDialog.Builder dialog = new AlertDialog.Builder(PayActivity.this);
for(int i=0; i<people; i++) {
/*PASS*/
if(array[i] == 0) {
dialog.setView(image_questionmark);
dialog.setPositiveButton("FLIP", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new AlertDialog.Builder(PayActivity.this)
.setView(image_pass)
.setPositiveButton("NEXT", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish(); /*move on to next value in array*/
}
}).create().show(); /*HERE: Nothing showed on my screen when running debugger...*/
}
});
dialog.create().show();
/*If not the first card, show previous card*/
if(i!=0) {
dialog.setNegativeButton("PREVIOUS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
i--; /*return to previous value in array*/
} /*First card*/
else {
dialog.setNegativeButton("PREVIOUS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "No previous card", Toast.LENGTH_LONG).show();
}
});
}
}/*YOU PAY*/
else {
dialog.setView(image_questionmark);
dialog.setPositiveButton("FLIP", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new AlertDialog.Builder(PayActivity.this)
.setView(image_youpay)
.setPositiveButton("NEXT", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish(); /*move on to next value in array*/
}
}).create().show();
}
});
dialog.create().show();
/*If not the first card, show previous card*/
if(i!=0) {
dialog.setNegativeButton("PREVIOUS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
i--; /*return to previous value in array*/
} /*First card*/
else {
dialog.setNegativeButton("PREVIOUS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "No previous card", Toast.LENGTH_LONG).show();
}
});
}
}
}
Thank you for your time :)
I did not try your code.But you can try it like -
First initilise your image object then assign to another final variable.
I think it will work.
ImageView image_pas1 = new ImageView(this);
final ImageView image_youpay = new ImageView(this);
image_questionmark.setImageResource(R.drawable.card_questionmark);
image_pass1.setImageResource(R.drawable.card_pass);
image_youpay.setImageResource(R.drawable.card_youpay);
final ImageView image_pass=image_pass;
You need to set LayoutParams for your ImageView in order to know how to draw itself. Maybe something like this:
image_questionmark.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, // width
LayoutParams.WRAP_CONTENT)); // height
And do this as well for your other 2 ImageViews
First of all, Dialogs need
buildervariablename.create();
only.
Second, every single Dialog has to be in a seperate class, like this:
public class TestDialog extends DialogFragment
{
// Put your dialog code in here
}
And then you just call your dialog there, where it is needed. Inside another method, or even another dialog, by using the following:
DialogFragment fragment = new TestDialog();
fragment.show(getFragmentManager(),"testdialog");
Hope this helped you, if you have further questions, just comment this answer.

android alert box with multiple options, how to use those options?

I am a beginner, so if anyone would help me out. I created a list in the dialogue box , now how do i use those options? Like click one and it does something , click another and it does something else.
CharSequence features[] = new CharSequence[] {"Save", "Send", "Something", "Something"};
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Options");
alertDialog.setItems(features, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"Eta chu ma aile",
Toast.LENGTH_LONG).show();
}
});
alertDialog.show();
return true;
}
If you know exact position of every item, just compare it with which param.
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
// handle "Save" option
} else if (which == 1) {
// handle "Send" option
} ...
}
You can use following code:
Somewhere in another function:
String title = "My Alert Box";
String msg = "Choose Option";
alertfunc(title,msg);
The main alert function:
private void alertfunc(String title, String msg) {
if (title.equals(TASK_VIEW_PROFILE)) {
new AlertDialog.Builder(MainActivity.this)
.setTitle(title)
.setMessage(msg)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
//Do something
}
})
.setNegativeButton("Send",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which)
{
//Do something
}
}).create().show();
.setNegativeButton("Something",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which)
{
//Do something
}
}).create().show();
//...and so on
}
}

Categories