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();
Related
I am in an activity and I am trying to display an alert dialog. The code is this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("xx");
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
built.dismiss();
}
});
builder.setNegativeButton(R.string.giveup, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
built.dismiss();
}
});
builder.setCancelable(true);
built = builder.create();
built.show();
The thing is, the same code is called in two different places in the activity and one works while the other doesn't! I don't understand because they are literally the same...
There are questions like this in this site and I tried most of them. I changed the this in the parameter to the activity name, I set a position, I put show() method, etc... I do not know how to proceed
And I put breakpoints in both of the places. The working one goes smoothly. But when it does not get displayed, the breakpoint crashes at 'builder.create()'. It doesn't go further than this (it doesnt see the next breakpoint which is built.show). It says "frames are not available"
I found it. Just putting it here in case someone needs it. I found it from here: Listener method (interface in Service) in my Activity doesn't want to display a simple message
The problem was that, I was calling the "not-working" one from an emitter.listener, thus it was not working on the correct thread. We need this to work on UI thread. When I added this:
runOnUiThread(new Runnable(){
public void run(){
showAlertDialog();
}
});
It worked!
I am trying to run a "presence check" on a radio group, to determine what happens if 1 of 2 radiobuttons are selected in the group (if statement), if the other of the 2 radiobuttons is selected instead (else if statement) or if neither are selected (else statement). The code for this is as follows:
if (rdbAM.isSelected()) {
strTime = rdbAM.getText().toString();
} else if(rdbPM.isSelected()){
strTime = rdbPM.getText().toString();
} else {
AlertDialog.Builder WrongDateFormat = new AlertDialog.Builder(this);
WrongDateFormat.setMessage("Please Select AM or PM");
WrongDateFormat.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertWrongDateFormat = WrongDateFormat.create();
alertWrongDateFormat.show();
return;
}
So basically, what this should do is either, set the variable called "strTime" to whatever the text of the selected radiobutton in the radiogroup is, or display an error message if neither are selected. It is instead always displaying this error message, regardless of whether either radiobutton is selected or not:
(As you can see above, the "AM" radiobutton is selected, but error is still being displayed).
Any suggestions as to why this may be would be appreciated. Please note that I am relatively new to Android development, so if it is clearly something obvious then I apologise, but I have been trying to get my head round this for several days now! If you would like to see any further code, please let me know and I'll be happy to provide it, but am trying to keep it as private as possible, so didn't want to post everything in the initial post if not necessary. Thanks in advance.
According the documentation the RadioButton extends the CompoundButton that offers the method isChecked(). However there is poorly described the difference from the method isSelected() from the extended class View that might be confusing.
Do the following and it should work:
rdbAM.isChecked();
Instead of using isSelected() go for isChecked().
A RadioButton is a two-states button that can be either checked or unchecked. For this compound button, you should use method isChecked() to know its current state.
See documentation.
Update your code as below:
if (rdbAM.isChecked()) {
strTime = rdbAM.getText().toString();
} else if(rdbPM.isChecked()){
strTime = rdbPM.getText().toString();
} else {
AlertDialog.Builder WrongDateFormat = new AlertDialog.Builder(this);
WrongDateFormat.setMessage("Please Select AM or PM");
WrongDateFormat.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertWrongDateFormat = WrongDateFormat.create();
alertWrongDateFormat.show();
return;
}
After a check demanding the user to switch on internet services and I try to click on a button my app crashes with the error message
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
On this line it crashes, I have tried doing this but not resolved absolutely
if(alert.getContext() != null){
alert.show();
}
This is the complete code
else if (id == R.id.xyz) {
//startActivity(borrowIntent);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("xyz");
input.setFilters(new InputFilter[] {
// Maximum 2 characters.
new InputFilter.LengthFilter(6),
// Digits only.
DigitsKeyListener.getInstance(),
});
// Digits only & use numeric soft-keyboard.
input.setKeyListener(DigitsKeyListener.getInstance());
input.setHint("xyz");
alert.setView(input);
alert.setPositiveButton("Borrow", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(input.getText().length() == 0)
{
input.setError("xyz is required !");
}
else
{
if(isNetworkAvailable())
{
xyz( input.getText().toString());
}else{
//setContentView(R.layout.main);
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setCancelable(false);
builder.setTitle("xyz");
builder.setMessage("Please enable wifi services");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
dialog.dismiss();
}
});
AlertDialog alerts = builder.create();
alerts.show();
}//end of block
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
if(alert.getContext() != null){
alert.show(); //crashes at this line
}
}
Please what am I missing?
The problem is on this line:
alert.setView(input);
You added input View that have already parent.
Create new input instance.
according to this post, add this check to remove input from it's parent and readd it:
if(input.getParent()!=null)
((ViewGroup)input.getParent()).removeView(input); // <- fix
alert.addView(input);
Put following line
final AlertDialog alertd = alert.create();
After
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
Following situation can also happen (happened to me):
Sometimes when you use a listview you initialize it with an adapter, which belongs to a certain layout. Now lets say the root view of this layout file is a <LinearLayout> with the id "root_view".
If you register now for a context menu in your activity and create an AlerdDialog.Builder which appears after choosing a certain menu element and initialize it with a layout file, which also has a root element with an id called "root_view" where all elements which belong to your AlertDialog are children of it, then those elements "will not be found". You will not be able to access those elements with findViewById, instead you can only access the elements from the of your list view and you get the same error message at the line where you call builder.show() (or in the case here alert.show()).
So generally it is a good idea to name the ids of your elements in the layout files uniquely, for your project.
I forgot to call create() on the AlertDialog.Builder. When you call show() without calling the create() method, the AlertDialog instance gets created. This worked the first time but then subsequent clicks got the IllegalStateException. As I was calling show() inside of my onClickListener, it was going to create a new AlertDialog instance every time button was clicked.
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!
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