Aleksey Timoshchenko Aleksey Timoshchenko - 29 days ago 5
Android Question

How to solve inreger issue? Dagger2

I am new at

Dagger2
and tried to build such sample to understood how does it work.

There is my sample code :

MainActivity


public class MainActivity extends AppCompatActivity {

@Inject
protected ApiInterface apiInterface;

@Inject
protected Integer valueInt;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

App.getComponent().inject(this);
}

public void testButton(View view) {
if (apiInterface == null || valueInt == null) {
Log.e("TAG", "apiInterface == null");
} else {
Log.e("TAG", "apiInterface != null : " + apiInterface.value + " : " + valueInt);
}
}
}


Component


@Singleton
@Component(modules = {ModelModule.class, AnotherModule.class})
interface AppComponent {

void inject(MainActivity mainActivity);
}


Module


@Module
class ModelModule {

@Provides
int provideInt() {
return 1;
}

@Provides
ApiInterface provideApiInterface(int i) {
return ApiModule.getApiInterface(i);
}
}


Module


@Module
class AnotherModule {
@Provides
Integer getInt(){
return 3;
}
}


as you can see in my sample in
MainActivity
i inject
Integer


@Inject
protected Integer valueInt;


and also i want to use
int
to provide value as argument for this method
provideApiInterface(int i)
.

And eventually i get such error

Error:(11, 10) error: java.lang.Integer is bound multiple times:
@Provides int com.krokosha.aleksey.daggertwo.ModelModule.provideInt()
@Provides Integer com.krokosha.aleksey.daggertwo.AnotherModule.getInt()


What am i doing wrong?

How am i supposed to provide this argument in proper way to avoid such error?

Answer

You need to use qualifier annotations

@Module
class ModelModule {

    @Provides 
    @Named("FirstInt")
    int provideInt() {
        return 1;
    }
}

@Module
class AnotherModule {

    @Provides 
    @Named("SecondInt")
    int provideInt() {
        return 1;
    }
}

and use this qualifiers when injecting dependecies

@Inject
protected ApiInterface apiInterface;

@Inject 
@Named("FirstInt") //or whatever you need
protected Integer valueInt;

Hope it helps! Also check official docs - http://square.github.io/dagger/

Comments