---
title: "Inside OnClickListener I cannot access a lot of things - how to approach?"  
description: "Inside OnClickListener I cannot access a lot of things - how to approach?"  
author: "Anonymous User"  
published: 2015-12-14  
updated: 2015-12-14  
canonical: https://www.mindstick.com/forum/33726/inside-onclicklistener-i-cannot-access-a-lot-of-things-how-to-approach  
category: "android"  
tags: ["android", "java"]  
reading_time: 2 minutes  

---

# Inside OnClickListener I cannot access a lot of things - how to approach?

Inside an OnClickListener I [cannot access](https://answers.mindstick.com/qa/50453/how-to-fix-an-iphone-x-that-cannot-access-internet-even-if-connected-to-wi-fi-network) most [variables](https://www.mindstick.com/articles/715/php-variables) "outside" of the [scope](https://www.mindstick.com/interview/372/what-are-the-different-scopes-for-java-variables), like this:

```
findViewById(R.id.Button01).setOnClickListener(new OnClickListener()        {            @Override            public void onClick(View v)            {                Intent mainApps = new Intent(Intent.ACTION_MAIN);                mainApps.addCategory(Intent.CATEGORY_LAUNCHER);                List<ActivityInfo> activities = this.getPackageManager().queryIntentActivities(mainApps, 0);                /*                Intent intent = new Intent("com.sygic.drive/com.sygic/drive/.SygicDriveActivity");                startActivity(intent);*/            }        });
```

\
in this example I need to get the PacketManager, and I cannot get it since I do not have the [Context](https://www.mindstick.com/forum/23245/what-is-context-in-android) available inside the OnClickListener.\
I could make a [static](https://www.mindstick.com/articles/12098/the-static-keyword-the-static-methods) [reference](https://www.mindstick.com/forum/774/reference-what-does-this-error-mean-in-php) outside, and use it inside, but is that correct? Seems [odd](https://yourviews.mindstick.com/view/86337/delhi-odd-even-scheme-is-active-again-what-is-it-and-why-it-is-in-the-news) to have to do that all the time?

## Replies

### Reply by Anonymous User

Replace this in your code with MyActivity.this where MyActivity is the class name of your Activity subclass.\
Explanation: You are creating an anonymous inner class when you use this part of your code: new OnClickListener() {Anonymous inner classes have a reference to the instance of the class they are created in. It looks like you are creating it inside an Activity subclass because findViewById is an Activity method. Activity's are a Context, so all you need to do is use the reference to it that you have automatically.


---

Original Source: https://www.mindstick.com/forum/33726/inside-onclicklistener-i-cannot-access-a-lot-of-things-how-to-approach

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
