Home > DeveloperSection > Forums > Inside OnClickListener I cannot access a lot of things - how to approach?
JAMES Williams
JAMES Williams

Total Post:7

Points:49
Posted on    December-14-2015 12:47 AM

 Android Android  Java 
Ratings:


 1 Reply(s)
 248  View(s)
Rate this:
Inside an OnClickListener I cannot access most variables "outside" of the scope, 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 available inside the OnClickListener.

I could make a static reference outside, and use it inside, but is that correct? Seems odd to have to do that all the time?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    December-14-2015 1:12 AM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick