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.
The time the statement
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