Android Build an Interactive Story App Intents and Multiple Activities Sending Data to a New Activity

Why couldn't you set the variable as private and use it throughout the project?

They're asking to have a parameter in the "StartStory" method but instead of passing a parameter why couldn't you just define what name is in the beginning like so?

public class MainActivity extends AppCompatActivity {

    private EditText mEditText;
    private Button mStartButton;
    private String mName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mEditText = (EditText) findViewById(R.id.nameEditText);
        mStartButton = (Button) findViewById(R.id.startStory);

        mStartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mName = mEditText.getText().toString();

                if (mName.matches("")) {
                    Toast.makeText(MainActivity.this, "Please enter a valid User name", Toast.LENGTH_LONG);
                    return;
                } else {
                    startStory(mName);
                }
            }
        });
    }

    private void startStory(String mName) {
        Intent intent = new Intent(this, StoryActivity.class);
        intent.putExtra("UserName", mName);
        startActivity(intent);
    } 

1 Answer

Ranvir Sahota
Ranvir Sahota
9,844 Points

Though this question may be old I will answer it for anyone else that may get confused. The question was answered in the video but Ben did simply not explain in-depth. The keyword was "coupling" which is defined as a principle in OOP as a way of separation of concerns. The aim to prevent objects being intrinsically tied together,. this helps keep code clean and reusable as stated in the video.

Look at this link: https://gamedevelopment.tutsplus.com/tutorials/quick-tip-the-oop-principle-of-coupling--gamedev-1935 Which is how I came to understand this concept.