Java – how to use Guice to inject impl of some interfaces into Android activity
I use Guice 3.0 on Android to do some di
I have
public interface APIClient { }
and
public class DefaultAPIClient implements APIClient { }
What I do is try to boot Guice in my myapplication class and provide it with a module in the configure method bind (apicclient. Class) There is a statement in to (defaultapicclient. Class);
I did Guice's example to tell me what to do
Injector injector = Guice.createInjector(new APIClientModule()); injector.getInstance(APIClient.class);
I may not understand this correctly, but how do I inject apicclient into several activities that will use it?
I did this in homeactivity
public class HomeActivity extends RoboActivity { @Inject APIClient client; protected void onCreate(Bundle savedInstanceState) { client.doSomething(); } }
This doesn't work. It gives me Guice configuration error: 1) it doesn't implement com mycompany. Apicclient binding
So the only way I can make it work is to delete @ inject from the apicclient client in homeactivity and use client = Guice Createinjector (New apiclientmodule()) injects it getInstance(APIClient.class);
So does this mean that I have to do this in every activity that uses apicclient? I must have done something wrong
Any help would be great thank you!
Solution
If you compare roboguice 2.0 with Guice 3.0_ If noaop is used together, the method of defining other custom modules is through the string array resource file roboguice_ modules:
From document (upgradingto20):
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="roboguice_modules"> <item>PACKAGE.APIClientModule</item> </string-array> </resources>
Therefore, you need to define a custom module as follows:
roboguice_ modules:
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="roboguice_modules"> <item>DONT_KNow_YOUR_PACKAGE.APIClientModule</item> </string-array> </resources>
Of course, there is a binding between apicclient and defaultapicclient
And roboguice should do the rest