Correct context to use within callbacks
android, android-asynctask, android-context, callback
Solution
Use the Activity's context. Example:
MyAsyncTask mat = new MyAsyncTask(this);
MyAsyncTask contructor:
public MyAsyncTask(MyActivity context) {
mContext = context;
}
To call MyActivity's method `methodToCall()` from within `MyAsyncTask`:
((MyActivity)mContext).methodToCall();
Edit 1:
I am guessing your problem is this:
public class MyActivity extends Activity {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_layout);
b = (Button) findViewById(...);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Button newButton = new Button(this); // Won't work!!
}
});
}
}
Workaround:
Declare a method in MyActivity: `getContext()`
public Context getContext() {
return (Context)this;
}
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Button newButton = new Button(getContext()); // Will work
}
});
Use `MyActivity.this` in place of `this`.
Another way is to state that MyActivity implements the interface:
public class MyActivity extends Activity implements View.OnClickListener {
....
....
@Override
public void onClick(View v) {
Button newButton = Button (this) // Will Work
}
}
Problem
The title pretty much says it all. If you have a callback from one class to another and need to call some method from within the callback that requires a context what is the correct context to use? A common example would be an `AsyncTask` with a callback to the `Activity` or `Fragment` that used it. I generally try to avoid using `getApplicationContext()` but I cannot use `this` as the context from within a callback. Is this a case where using a broader context is appropriate? To clarify further I'm thinking of a callback with an interface between an AsyncTask and an activity. Once I'm inside the overridden interface method I can't get the activities context from within there.