The right context for use in callbacks

The name says a lot about everything. If you have a callback from one class to another and need to call some method from a callback that requires context, what is the correct context to use? A common example is AsyncTask with a callback to the Activity or Fragment that used it.

I usually try to avoid using getApplicationContext() , but I cannot use this as the context from the callback. Is this the case when using a wider context is appropriate?

To clarify, I am thinking of an interface callback between AsyncTask and activity. Once I get into the redefined interface method, I cannot get the context of the actions from the inside.

+8
android callback android-context android-asynctask
source share
2 answers

Use an Activity context. Example:

 MyAsyncTask mat = new MyAsyncTask(this); 

MyAsyncTask Contractor:

 public MyAsyncTask(MyActivity context) { mContext = context; } 

To call the MyActivity methodToCall() method from MyAsyncTask :

 ((MyActivity)mContext).methodToCall(); 

Change 1:

I assume 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 instead of this .

  • Another way is to indicate 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 } } 
+7
source share

This is a leak theme. Firstly, the action to be taken is not good. According to some other suggestions, people should use getApplication or getApplicationContext. But you can use WeakReference for your wrapper, i.e.

 static class X { WeakReference<Activity> context; X(Activity context) { this.context = new WeakReference<Activity>(context); } } 

Remember that static to mark your class, it can avoid the potential "this" for your host.

Perhaps you gave some suggestions, could not :)

0
source share

All Articles