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 trialMatthew Francis
6,967 PointsClarification 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.
1 Answer
Kourosh Raeen
23,733 PointsHi 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
6,967 PointsMatthew Francis
6,967 PointsAhh makes sense, what is the purpose of including the Context as the first argument though? what is it's usage?
Kourosh Raeen
23,733 PointsKourosh Raeen
23,733 PointsTake a look at these links for more on Context:
https://teamtreehouse.com/community/context-class-in-android http://stackoverflow.com/questions/3572463/what-is-context-on-android
Matthew Francis
6,967 PointsMatthew Francis
6,967 PointsThanks 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?