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 trialTetsuya Uno
21,024 PointsWhat should I do if I want users to write their own name no matter what?
I want to return error with error message and let users try again if they don't submit their name. Could anyone help?
2 Answers
Seth Kroger
56,413 PointsYou could use a Toast, but you can also use the setError() on the EditText to show an error popup:
Marc Reid
7,830 PointsThis doesn't return an error message but uses a toast to inform the user that they must enter a name to continue.
nameField = (EditText)findViewById(R.id.nameEditText);
startButton = (Button)findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = nameField.getText().toString();
if (name.trim().isEmpty())
{
Toast.makeText(MainActivity.this, "Hello, please enter your name." ,
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this, "Hello," + name, Toast.LENGTH_LONG).show();
startStory(name);
}
}
});
Tetsuya Uno
21,024 PointsTetsuya Uno
21,024 PointsThank you, but would you mind giving me an example? I tried with setError(), but no luck.
Here is my coding.
public class MainActivity extends AppCompatActivity { private EditText nameField; private Button startButton;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
}
@Override protected void onResume() { super.onResume(); nameField.setText(""); }
private void startStory(String name) { Intent intent = new Intent(MainActivity.this, StoryActivity.class); Resources resources = getResources(); String key = resources.getString(R.string.key_name); intent.putExtra(key, name); if (name == null || name.isEmpty()){ name = "Friend"; } startActivity(intent);
}