2

I am at baby step level of programming on Android (and in Java in general). I do understand that Activity inherits from the Context class. However in every code snippet I have come across, every time a context must be mentionned, it is set to "this".

My question is : when is a context different from "this" ? Could you provide an real life example of context needing to be different from "this"?

Thank you very much.

1

5 Answers 5

3

Typically, you will want to use this when you are "inside" of an Activity. However, when you are using for example a Helper class, the reference this will not work. An example can be something like this:

public class MyActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
    }
}

A case, where you cannot:

public class MyHelper
{
    /* some code of yours */

    public void lockOrientation(Activity activity)
    {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
    }
}

The above code locks the orientation to the current orientation. Notice that you need to supply the method with an Activity parameter, since you cannot use:

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

In the first example, you could use this to achieve this, because you were "inside" of an Activity.

Another type of example, how do you set onClickListener.

First example, when you use this:

public class MyActivity extends Activity implements View.OnClickListener
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Button btn=(Button)findViewById(R.id.mybutton);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v)
    {
        //handle the click event
    }
}

In this example, you can use this because in the first line, we wrote implements View.OnClickListener, so the class inherits from the given interface. Without the implements thingie, you couldn't do it. An example of setting the onClickListener without this:

public class MyActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Button btn=(Button)findViewById(R.id.mybutton);
        btn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //handle the click event
            }
        });
    }
}

In the second example, we are defining an Anonymous Inner Class, which will handle the click event of the button. Notice that in this case, our Activity does NOT implements View.OnClickListener.

Sign up to request clarification or add additional context in comments.

5 Comments

@warm: In non-activity class you can not use "this".. while in activity class you can use "this".. rest is explained above.
Thank you, this answers my question. I understand why "this" is not used in your second example. Do you have another case in mind where, within an Activity, you would pass another value than "this" as the context ?
You can globally define context variable as, Context context = this; and use variable "context" instead of "this".
See the updated answer with another example. There are loads of cases when you cannot use this, but this two is kinda easy to understand.
@android_beginner Careful with saving the Context in a variable, especially if it is a static one. You can really mess with the Garbage Collector, and cause serious memory leaks. Unless you don't have to, try to avoid this. :)
1
  1. In Outer Class you directly use "this" reference
  2. In Inner Class Or Abstract Class implementation Or Interface implementation use "classname.this" reference

Comments

1

Example:

class Example{
    int number = 0;

    public Example(int number){
        this.number = number;
    }
}

notice that number in the contructor and number in the class are not the same. Altough they have the same name. Saying number = number doesn't make sense. Be using this you can asses number in the class.

Comments

0

For example when you are implementing an OnClickListener the "this" is different.

2 Comments

Yes, but you still type "this". My question was when do you not type "this" as a context. hundeva provides an answer to that. I am curious to find other examples if there are.
Inside an Activity, create a variable, Context context. Then on onCreate method you can do context=this, and later use that variable for anything you want.
0

this is a reference to the current object — the object whose method or constructor is being called.

Inside an Activity's method this can be used as a Context object because Activity inherits from ContextThemeWrapper, which inherits from ContextWrapper, which inherits from Context.

A Fragment on the other hand does not inherit from Context. So to get the Context inside a Fragment you would have to call getActivity() for example.

This applies to any object you are calling this from.

Consider you are inside the OnClick() method of a View.OnClickListener and you want to start an Activity:

button.setOnClickListener (new View.OnClickListener() {
    public void onClick(View v) {

        Intent intent = new Intent(this, NextActivity.class); // wrong because 'this' is the OnClickListener object

        Intent intent = new Intent(CurrentActivity.this, NextActivity.class); // correct because 'this' is the CurrentActivity object

        startActivity(intent);
    }
});

1 Comment

Benito, while this is great information it is not exactly what I am looking for ultimately (my question is surely ill formatted). Even though you help clear a possible confusion between different "this", in the end the code you provide uses "this" as a context and my question is when is the context different from "this". I do understand the information you provide, and I am grateful for it, but again my question is when do we avoid typing "this" as a context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.