Intent Constructor


#1

Hi

Im a little confused by the need to specify the activity name in the creation of the intent.

the contstructor we are using is:

public Intent(Context packageContext, Class<?> cls)

which means which package and which class ??

The code in the book is :

Intent i = new Intent(QuizActivity.this, CheatActivity.class);
startActivity(i);

Why can’t I use Intent i = new Intent([color=#0000FF]this[/color], CheatActivity.class); ?? as “A Context as its first parameter (this is used because the Activity class is a subclass of Context)”.

For example, developer.android.com/training/b … ivity.html only uses ‘this’ as the Context rather than ‘ActivityName.this’.


#2

Try it yourself - you will see that it doesn’t work. This is because the code in the book is within an anonymous inner class. If you used this code instead:

Intent i = new Intent(this, CheatActivity.class); startActivity(i);

It will not compile, because “this” is an instance of View.OnClickListener, not Context.


#3

That makes total sense, I forgot that I was inside an anonymous class.

Thank you for the very fast response. This book is great!


#4

Hi,

You said: “The Context object tells the ActivityManager which package the Class object can be found in.” (pag.100). Why cannot use ‘CheatActivity.this’ instead of ‘QuizActivity.this’ for ‘packageContext’ parameter?

Thank you,

Madalin


#5

You can. Any Context that lives in your package will work.

(I can’t think of a situation when you’d have a Context that wouldn’t be in your package, by the way.)


#6

[quote=“Madalin”]Hi,

You said: “The Context object tells the ActivityManager which package the Class object can be found in.”

Madalin[/quote]

I am confused about this statement in the book. The Class object has a getPackage() function that returns the package the Class belongs too. See: docs.oracle.com/javase/6/docs/ap … etPackage(

I don’t understand why ActivityManager needs a context for the purpose stated above.