Julian Julian - 3 months ago 8
Java Question

How can I make this Variable by UserInput work? android

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mButton = (Button)findViewById(R.id.okay);
mEdit = (EditText)findViewById(R.id.name);
final TextView questionOne =(TextView)findViewById(R.id.questionOne);
final String name = mEdit.getText().toString(); //

mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText", mEdit.getText().toString());
}
});

mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

questionOne.setText("Tell me your lucky number, " + name + "!");

} });
}


}

So, my goal is to let the user write his name and then print it out with the setText method. In order to do this I declared the variable "name". But when I run the app and enter my name, it just prints out "Tell me your lucky number, !". So the variable name is missing completely. Can someone tell me what I did wrong with the variable, please?
Thank you in advance!

Answer

First of all, you over-wrote the button's one click listener. You were logging the EditText content just fine at one point.

Anyways, this gets the text immediately when the View is loaded. (And unless you put default text into that field, it is an empty string)

final String name = mEdit.getText().toString(); 

And it is final, so that variable can never even change values.

You need to "react" to the button event. So, do that.

mButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        String name = mEdit.getText().toString();
        questionOne.setText("Tell me your lucky number, " + name + "!");
    }         
});