Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading text of an EditText in android

Tags:

android

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.

like image 532
Vinod Maurya Avatar asked Feb 17 '11 11:02

Vinod Maurya


1 Answers

write this line in outside of button click

EditText et=(EditText)findViewById(R.id.entry);
txt=et.getText().toString();
like image 88
Pinki Avatar answered Oct 02 '22 00:10

Pinki