Android EditText getText always return the first text?
The other day, I had this weird bug on my Android project. I couldn't find some helpful information on the Internet. I decided to make a post about this weird bug.
First, I create an EditText variable and initialize it in OnCreate().
//...
private EditText search_bar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_list);
search_bar = (EditText) findViewById(R.id.search_bar);
generate_class_list(db);
}
// I think I can get the latest value of the editText in the onClick method
// But it turned out I can't get the updated value.
// No matter how I change the text in the editText, it always gives me the first value
public void onClick_to_search (View view) {
search_bar = (EditText) findViewById(R.id.search_bar);
String keyword = search_bar.getText().toString().trim().toLowerCase();
}
It make me really confused in the beginning.
After half an hour of debugging, I realized that it might be the problem of the initialization.
I initialized the variable in the onClick method. Problem solved. Yay!
//...
//private EditText search_bar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_list);
//search_bar = (EditText) findViewById(R.id.search_bar);
generate_class_list(db);
}
public void onClick_to_search (View view) {
EditText search_bar = (EditText) findViewById(R.id.search_bar);
String keyword = search_bar.getText().toString().trim().toLowerCase();
}
Conclusion: I entered value in editText after the completion of onCreate() method. So that means I could not get the updated value.
That's why I should put the variable inside the onClick method.
Comments
Post a Comment