Android Build an Interactive Story App Intents and Multiple Activities Investigating a NullPointerException

Tetsuya Uno
Tetsuya Uno
20,717 Points

What 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
MOD
Seth Kroger
Treehouse Moderator 56,261 Points

You could use a Toast, but you can also use the setError() on the EditText to show an error popup:

Tetsuya Uno
Tetsuya Uno
20,717 Points

Thank 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);

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();

        Toast.makeText(MainActivity.this, "Hello," + name, Toast.LENGTH_LONG).show();
        startStory(name);

    }
});

}

@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);

}

Marc Reid
Marc Reid
4,197 Points

This 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);
        }

    }
});