0

I recently started using java and I'm trying to understand what exactly "Context" is, and how to use it properly.

public AdapterView.OnItemClickListener selectDevice = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            String info = ((TextView) view).getText().toString();
            String adress = info.substring(info.length()-17);
            Intent comIntent = new Intent(MainActivity.this, Communication.class); //WHY???


        }
    };

For this example and Intent arguement , why don't we use "getContext()" or "getApplicationContext" or just "this"?

Steve Benett
  • 12,843
  • 7
  • 59
  • 79

2 Answers2

1

Calling getContext() or getApplicationContext() is same as this.getContext() right? this gives an object class where you are in. So when you are able to call getContext() that means you are inside a class which extends Context class and has getContext() function.
For example from Activity you can call getContext() because it has the function. But in this case you are in OnItemClickListener class. And that class has no function getContext(). You have to be in a class which has getContext() function.

oto
  • 383
  • 4
  • 18
1

I'm trying to understand what exactly "Context" is

What is 'Context' on Android?

why don't we use "getContext()" or "getApplicationContext" or just "this"?

Because this does not refer to the Activity in anonymous classes. See here Access "this" from Java anonymous class

Steve Benett
  • 12,843
  • 7
  • 59
  • 79