2

Hi i am trying to understand the use of context though i couldn't. Following is a program using context. My question is what is the significance of " context = class.this " ?

class public VcardActivity extends Activity
   {
   String Vcard = "vcard";
   Context context;
   }
   public void onCreate ( Bundle bn )
   { 
    super.onCreate(bn);
    setContentView(R.layout.main);
    context = VcardActivity.this;
   }

3 Answers3

0

In your case, the field context is not necessary at all. It rather is used as a shortcut to VcardActivity.this here. You could remove it without any problems and use VcardActivity.this or even only this where you used to use context.

FD_
  • 12,947
  • 4
  • 35
  • 62
0

Your current code doesn't show the use of context. It shows that the Activity is a context.

TextView someText=new TextView(context);

This code of mine shows, I am passing a context into the constructor of a TextView in order to make this object. The reason is, this object needs to know the information, state of the current context, and this is the reason why many views, classes, helpers needs a context.

 context = VcardActivity.this;

in your code you are having your activity object to assign to the Context context. This works because Activity class inherits from Context and many classes needs a Context to create it.

wtsang02
  • 18,603
  • 10
  • 49
  • 67
  • Thanks @wtsang. But what if i dont assign activity object to context. Is it really compulsory to call the state. – Varun Singh Jul 31 '13 at 20:32
  • Assigning your activty to context in your current code has no use at all. Assigning it to the context as a member of the class allows other methods of the class access this context. However, it would not be useful because your activity is a context itself, so you can just use `this` in your other methods. – wtsang02 Jul 31 '13 at 20:34
0

You don't need to create a separate Context variable inside of an Activity. You use Context for certain objects/methods that need to know what is starting them. Activity already has a Context so you don't need to create it. If you need to use Context within an Activity, say when creating an Intent you can just use ActivityName.this or here VcardActivity

See this SO answer for a good explanation of using which kind of Context when.

Context Docs

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93