4

I have an adapter which extends ArrayAdapter<T> and want to inject into them LayoutInflater. Code presented below, but inflater is always null

public abstract class MyAdapter<T> extends ArrayAdapter<T> {

    @Inject
    protected LayoutInflater inflater;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // inflater here is null
    }
}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Dmitriy Tarasov
  • 1,949
  • 20
  • 37

2 Answers2

5

Probably you've created MyAdapter instance with new instead of injecting it.

In this case I would not recommend to inject LayoutInflater, unless you want to use different implementations of this class, example mock of LayoutInflater for testing.

Obtain the instance in constructor:

inflater = LayoutInflater.from(context);

It would be more efficient. I can't see any benefit from injecting LayoutInflater.
Dependency injection is ok, but don't use it when it's not necessary and slow.

pawelzieba
  • 16,082
  • 3
  • 46
  • 72
  • Yes i create my adapter instance with `new` because i should to pass arguments into constructor. How i can inject it into activity? How i can choose requared constructor and pass params to it? – Dmitriy Tarasov Sep 20 '12 at 09:25
  • For passing args into constructor: http://stackoverflow.com/questions/9237996/pass-parameter-to-constructor-with-guice Or `injectMembers`: http://stackoverflow.com/questions/5116383/guice-injectmembers-method Both solutions are ugly in your case :) – pawelzieba Sep 20 '12 at 09:42
5

Inject dependencies in any class

 RoboGuice.getInjector(context).injectMembers(this);

use in constructor, just need context, great works for me

Serhii Bohutskyi
  • 2,261
  • 2
  • 28
  • 28