Android Build an Interactive Story App Intents and Multiple Activities Introducing Intents

bot .net
bot .net
11,911 Points

Why we pass this to the first parameter of the Intent object and not this.MainActivity?

Hi, Why we pass "this" to the first parameter of the Intent object and not this.MainActivity?, the context is our MainActivity so why not add the name of the file? I understand that "this" refer to the current activity but i want to know if they both valid.

instead of :

  Intent intent = new Intent(this, StoryActivity.class);

we should use:

  Intent intent = new Intent(MainActivity.this, StoryActivity.class);

Lauren Moineau

1 Answer

Hi noob developer. Because in startStory() the intent is executed in the MainActivity itself, so this is enough.

However, if you move all the code from the startStory() method to the onClick() method in the anonymous OnClickListener inner class, you would need to call MainActivity.this, as you would now be in an inner class.

startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameField.getText().toString();
                Intent intent = new Intent(MainActivity.this, StoryActivity.class);
                Resources resources = getResources();
                String key = resources.getString(R.string.key_name);
                intent.putExtra(key, name);
                startActivity(intent);
            }
        });

I hope that makes sense :)

bot .net
bot .net
11,911 Points

Lauren Moineau Thanks for the answer! :D I understand that so i only would call MainActivity.this if its in the onClick method, if its on its own method i would call this?

You're welcome @noob developer :)

  • If you need context in the activity itself, use this.
  • If you need context in an inner class of the activity (anonymous, like when using setOnClickListener(), or not), use ActivityName.this