Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDavid Cutler
9,536 PointsEdit text view returning ... something
I tried to implement a default name to use in the event the user left the edit text view blank.
Tried:
if (mName == null) mName = getString(R.string.default_name);
but didn't work, after a quick Google I ended up with:
if (mName.trim().length() == 0) mName = getString(R.string.default_name);
I'm guessing that in MainActivity
String name = mNameField.getText().toString();
is returning something even when blank and so never == null
I'm not really sure what trim() does though - the docs didn't make much sense to me.
2 Answers
Afik Paryente
2,042 PointsIm not 100% sure what you ment to ask here, but here is a quick explenation on EditTexts: Retriving the content of an EditText:
String name = mNameEditText.getText().toString();
getText() returns type called 'Editable'. We use the 'toString' methode to, well, convert it to string! So - variable 'name' will get the content of the EditText.
Setting the content of an EditText:
String name = getString(R.string.default_name);
mNameEditText.setText("Default name is "+name);
What trim does: clearing the 'empty spaces' at the beginning and end of a string. For example:
String strToTrim = " Hi David ";
String afterTrim = strToTrim.trim();
afterTrim will be equal to "Hi David". Hope it helps.
David Cutler
9,536 PointsYou've answered my question which was essentially what the trim() function does - so thanks for that.
I'll just explain the context briefly - the getString method above pulls the name from another class which uses the code as you suggested above which is following the video guide.
String name = mNameField.getText().toString();
I'd forgotten where the string was pulled out of the edit text view because I came back to this bit at the end of the project. Because it returns something the == null condition never evaluates as true as suggested in the video tagged which is where I was getting confused.