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~
Related
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.
guys I've been trying to solve this problem but I couldn't
I want when the user click on the btn_delete he will get a message to insure the delete (Yes or No), I've tried a lot of methods but I don't know exactly what's the problem, I'm new in Android programing so forgive me for my stupid questions, here is my Java code :
public void onDeleteClick(View v) {
int i = Integer.parseInt((String)v.getTag());
Address address = _list.get(_currentPage*PANELS_PER_PAGE + i);
_dbAdapter.deleteAddress(address.Id);
_GetAddresses();
}
Replace the onDeleteClick method with the following method:
public void onDeleteClick(View v) {
int i = Integer.parseInt((String)v.getTag());
AlertDialog.Builder alert = new AlertDialog.Builder(AddressListActivity.this);
alert.setTitle("Delete");
alert.setMessage("Are you sure you want to delete?");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Address address = _list.get(_currentPage*PANELS_PER_PAGE + i);
_dbAdapter.deleteAddress(address.Id);
_GetAddresses();
dialog.dismiss();
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
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
}
}
I have an AlertDialog which displays an array into a single selected choice:
protected boolean blFrom, blTo;
protected void showSelectToDialog() {
boolean[] checkedDate = new boolean[toDate.length];
int count = toDate.length;
DialogInterface.OnClickListener setD2 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO Auto-generated method stub
onChangeSelectedTo(which);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select To Year");
builder.setSingleChoiceItems(toDate, count, setD2);
builder.setCancelable(true);
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
dialog2 = builder.create();
dialog2.show();
}
protected void onChangeSelectedTo(int j) {
bTo.setText(toDate[j]);
sTo = ((AlertDialog)dialog2).getListView().getCheckedItemPosition();
blTo = true;
displayToast(String.valueOf(sTo));
to = j;
dialog.dismiss();
}
What I want to do is the first time it loads it should display the default. Once I select a choice and the dialog closes and I bring up the same dialog again it should show the previously selected choice I made and scroll to it.
How do I accomplish it?
As of right now, I can get the selected position but what next?
You can store the chosen value in a variable of your Activity or using SharedPreferences
Alright, this might be kinda simple, but I cannot figure out how to do this. How can I change this function to return the String class_name? I know that I need to change the function from void to String, but what else do I need to do?
Much appreciated!
public void addClass() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Add Class");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String class_name = input.getText().toString();
}
});
alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
Returning the class_name value doesn't help. You have to implement a callback method that takes the value and performs the required action:
public void addClass() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
// ...
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setClassName(input.getText().toString());
}
});
// ...
}
protected void setClassName(String class_name) {
// do what ever has to be done with class_name
}
The behavior (a synchronous dialog) you are trying to get deliberately does not exist in android. Whatever you want to happen when the dialog button is clicked has to be placed in the OnClickListener.OnClick method.
Assuming alert.show does not return until input.getText() contains the entered value, you could try:
public void addClass() {
final Vector<String> retval = new Vector<String>();
retval.add("");
...
...
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String class_name = input.getText().toString();
retval.set(0,class_name);
}
});
...
...
return retval.get(0);
}
AlertDialog is asynchronous and therefore what you want to achieve is not possible through that code.
you could set String class_name as global ad then initialize it to
class_name = input.getText().toString();
inside the onClick method of alert Button.