Question

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!";
    }
}
Était-ce utile?

La solution

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.

Autres conseils

You can't inject into an anonymous class. But you can do inject into the Fragment and it will be visible for the anonymous class, the AsyncTask in this case.

public class MyFragment extends Fragment {

 @Inject
 UserApi userApi;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    App.getInstance().inject(this);

    new MyTrask() {
        protected void onPostExecute(String result) {
            // Stuff
        }
    }.execute();
  }
}

 public class MyTask extends AsyncTask<Void, Void, String> {

 @Override
 protected String doInBackground(Void... params) {
    userApi.callAnyMethod(); // use userApi here
    return "Hello World!";
 }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top