I am writing a simple android app which have a edittext and a button. Clicking on button should display an alert dialog with text entered in the edittext. For that I have the following code:
String txt;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b=(Button)findViewById(R.id.ok);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Text in edit box: " + txt)
.setCancelable(false)
.setTitle("Info")
.setPositiveButton("Done", new DialogInterface.OnClickListener() {
开发者_开发技巧 public void onClick(DialogInterface dialog, int id) {}
});
final AlertDialog alert = builder.create();
// set click listener on the flag to show the dialog box
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText et=(EditText)findViewById(R.id.entry);
txt=et.getText().toString();
alert.show();
}
});
}
The above code is running fine but the alert dialog shows Text in edit box: null.It should show the text of the editbox.
write this line in outside of button click
EditText et=(EditText)findViewById(R.id.entry);
txt=et.getText().toString();
The time the statement
builder.setMessage("Text in edit box: " + txt)
got executed txt variable has null in it. this the reason.
Try to get this statement get executed after button click. It will 100% for sure remove the problem
Because you build the alert, the txt which in alert is null,when you click the button show the alert which dialog's txt is null, you should the alert after you click the button
Use as following:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
builder = new AlertDialog.Builder(this);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText et = (EditText) findViewById(R.id.editText1);
txt = et.getText().toString();
builder.setMessage("Text in edit box: " + txt)
.setCancelable(false)
.setTitle("Info")
.setPositiveButton("Done",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
final AlertDialog alert = builder.create();
alert.show();
}
});
}
精彩评论