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 trial

Android Build an Interactive Story App (Retired) Intents and Multiple Activities Adding a Second Activity

Matthew Francis
Matthew Francis
6,967 Points

Clarification on Intent(Context a, Class b)

In this code:

class Bob{
  String red = "red";
  void method1(){...}

  void method2(){
   Intent(this, ClassName.java);
   intent.putExtra(getString(R.string.key_name), name);
  }
}

I'm guessing the "this" is saying, "hey transfer "this" data(does it only send the putExtra data, or does it send every data in the Bob Class, such as the fields and methods?) to ClassName.java", correct? By this understanding that means "this" can be any class that you want to transfer data to.

Resource:http://stackoverflow.com/questions/8180180/android-can-somebody-please-explain-what-is-activity-context-intent-in-android

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

Hi Matthew - this does not refer to any data or any class that you want to transfer data to. The Intent class's constructor expects a Context as the first argument and since the Activity class is a subclass of the Context class you can use this, which refers to the instance of the current activity, for the first argument. Also, the Intent object does not automatically transfer data from one activity to another. You need to add any data that you want to pass to the second activity as an extra using the putExtra() method.

Hope this helps.

Matthew Francis
Matthew Francis
6,967 Points

Ahh makes sense, what is the purpose of including the Context as the first argument though? what is it's usage?

Matthew Francis
Matthew Francis
6,967 Points

Thanks for the resources,I understand it much more better now. However, I am still a bit confused on how it works and it's usage in the Intention Parameter.

As the name suggests, it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity and package/application).

In Intention(), what info is Context sending to the other actiivty? is it sending all of the activity's methods/fields/variables? or it only sending whatever is in putExtra? would putExtra not work without Context?