6

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.

4 Answers 4

7

write this line in outside of button click

EditText et=(EditText)findViewById(R.id.entry); txt=et.getText().toString(); 
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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

1 Comment

dont you think you should vote up the answer if someone already posted it. rather then posting a seprate answer. Guys make this community a benefit to all rather then making a fish market
1
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(); } }); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.