I am trying to use an alert dialog to prompt for a username and a password in android. I have found this code here:
if (token.equals("Not Found"))
{
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.userpasslayout, null);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please Login to Fogbugz");
alert.setMessage("Enter your email and password");
// Set an EditText view to get user input
alert.setView(textEntryView);
AlertDialog loginPrompt = alert.create();
final EditText input1 = (EditText) loginPrompt.findViewById(R.id.username);
final EditText input2 = (EditText) loginPrompt.findViewById(R.id.password);
alert.setPositiveButton("Login", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
input1.getText().toString(); **THIS CRASHES THE APPLICATION**
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
EDIT: I was able to set up the proper layout, but receive an error when I try to access the text field. What is the problem here?
The API Demos in the Android SDK have an example that does just that.
It's under
DIALOG_TEXT_ENTRY
. They have a layout, inflate it with aLayoutInflater
, and use that as the View.EDIT: What I had linked to in my original answer is stale. Here is a mirror.
Use these lines in the code, because the textEntryView is the parent of username edittext and password edittext.
Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.
The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.
Check this code in alert box have edit textview when click OK it displays on screen using toast.