0

I would like to inject resource and use it in the constructor of singleton class with roboguice injection. Below is an example that shows what I need but injected field is null in the constructor. I was reading something about providers and overthink another special class for getting url but I am not so sure if it's convenient solution. Code below:

@Singleton
public class ProductService implements IProductService {

    @InjectResource(R.string.server_url)
    private String serverBaseUrl;

    IProductAPI productAPI;

    public ProductService() {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(serverBaseUrl)
                .build();
        productAPI = restAdapter.create(IProductAPI.class);
    }

    public ProductDTO retrieveProductByEan(String productEan) throws RetrofitError {
        return productAPI.getProductByEan(productEan);
    }
}
Tr0k
  • 91
  • 1
  • 8

1 Answers1

0

As I can see reading the Roboguice documentation, Roboguice framework is only thought for Android programming. See the following link.

Injections are done when the super.onCreate() method is called in an Activity.

Here is a portion of code of a full example in github:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // @Inject, @InjectResource, and @InjectExtra injection happens during super.onCreate()

        sayText.setOnEditorActionListener(new OnEditorActionListener() {
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {

                // Have the remoteControl tell Astroboy to say something
                remoteControl.say(textView.getText().toString());
                textView.setText(null);
                return true;
            }
        });

So I recommend to use a static value to refer serverBaseUrl.

A-Tomy-k
  • 91
  • 5