I am new to android development. I am learning android development given here their is a piece of code
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
I want to know why we use String message = editText.getText().toString() after using EditText editText = (EditText) findViewById(R.id.edit_message); What does EditText return?
Using EditText editText = (EditText) findViewById(R.id.edit_message);
This line registers your xml editText with the class file editText. As you develop an app, the design is done in the xml file and coding is in the .class file.
Somewhere it is working as a Listener, like if you write something in the editText then,
Using EditText editText = (EditText) findViewById(R.id.edit_message);
By this line it is notified that the editText is notified.
NOTE: If you do directly String message = editText.getText().toString().without doing thisEditText editText = (EditText) findViewById(R.id.edit_message) you will get NullPointer Exception.
The getText() method of EditText returns a object of Editable, not String (to retrieve the text of EditText, toString() of Editable can be used.).
As we all know that EditText is a space where user can write or type anything and that content has been stored in a string format. So to get the content from user and to store them we use this String message = editText.getText().toString() the getText() method get the content inside editText and toString() will convert it to string format.
Here we are getting the id of EditText for getting the value which you have entered in EditText..
and to store that value we are using
String str=editText.getText().toString();
I hope you got you answer...
EditText editText = (EditText) findViewById(R.id.edit_message);
This line is for is like getting a reference to the Textview.By using reference only u can do whatever functionality on that textview.
String message = editText.getText().toString();
This line after getting reference your are setting the Text to that Textview(using that reference).
Also one more suggestion GOOGLE for android basics..
Edittext returns text which is entered by user which is in editable form after getting editable object you can convert editable to string using below code and store into string variable.
String message = editText.getText().toString();
EditText edt=(EditText)findViewById(R.id.yourid);
it is converting your xml edit text into java EditText. After doing this one only you can access your xml EditText by using the
String gettStr=edt.getText().toString()
来源:https://stackoverflow.com/questions/14050845/why-we-use-string-message-edittext-gettext-tostring-after-using-edittext-e