Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
how can i get a pointer to my activity object instance from within an anonymous method in Java/Android.

The problem is that the 'this' pointer gives me an instance to the function:

Error:(44, 17) error: constructor MyTask in class MyTask cannot be applied to given types;
required: Activity
found: anonymous OnCheckedChangeListener
reason: actual argument <anonymous oncheckedchangelistener=""> cannot be converted to Activity by method invocation conversion

<pre lang="java">
public class MyActivity extends AppCompatActivity {

    Switch mySwitch = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        mySwitch = (Switch) findViewById(R.id.myswitch2);
        mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String val= "0";

                new MyTask(this).execute(val); <----- this pointer here
            }
        });
    }
}


MyTask constructor
Java
MyTask(Activity activity)
{
    caller = activity;
}


I would like to avoid having a stored reference to the instance in my class.

Thanks!

What I have tried:

this.class
this.getClass()
getActivity()
getApplicationContext()
Posted
Updated 28-Apr-16 1:45am
v3

1 solution

You could try any of the two approaches :
1. inside MyActivity create a method which return "this" . i.e
Java
Activity getActivity(){

 return this;
}

and then call this method from anonymous method.
Java
new MyTask(getActivity()).execute(val);

2. or you can use this to access the "this" .

OuterClass.this

In your case
Java
new MyTask(MyActivity.this).execute(val); 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900