It's posible inject an anonymous class? I'm having the following error:
java.lang.IllegalArgumentException: No inject registered for members/com.acme.MyFragment$1. You must explicitly add it to the 'injects' option in one of your modules.
Example:
public class MyFragment extends Fragment {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MyTrask(getActivity()) {
protected void onPostExecute(String result) {
// Stuff
}
}.execute();
}
}
public class MyTask extends AsyncTask<Void, Void, String> {
@Inject
UserApi userApi;
public MyTask(Context context) {
App.getInstance().inject(this);
}
@Override
protected String doInBackground(Void... params) {
return "Hello World!";
}
}
You should inject the AsyncTask into MyFragment rather than using "new MyTask(..)". The MyTask constructor should take an UserApi instance and a Context object which can be provided by the module with code akin to;
/**
* The application module.
*
* @param context The context.
*/
public MyModule(final Context context) {
this.context = context.getApplicationContext();
}
/**
* Provides context.
*
* @return the application context.
*/
@Provides @Singleton Context provideContext() {
return context;
}
Your fragment code should then look like;
public class MyFragment extends Fragment {
@Inject Provider<MyTask> myTaskProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inject(this);
myTaskProvider.get().execute();
}
}
And your AsyncTask API should be;
@Inject
public MyTask(Context context, UserApi userApi) { }
Notice I used a Provider for the injection of the AsyncTask. This is necessary to avoid exceptions akin to "You can only execute a task once" that you would get if you called execute against the same AsyncTask object more than once. You then register MyFragment under your module injects = { } annotation arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With