Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject an anonymous inner class with dagger?

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!";
    }
}
like image 910
Brais Gabin Avatar asked Dec 28 '25 15:12

Brais Gabin


1 Answers

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.

like image 129
BrantApps Avatar answered Dec 31 '25 11:12

BrantApps