[英]How to inject resource and use it in the constructor
我想注入资源,并在具有roboguice注入的singleton类的构造函数中使用它。 下面是显示我需要的示例,但在构造函数中注入的字段为null。 我在阅读有关提供程序的内容,并考虑了另一个用于获取url的特殊类,但是我不确定这是否是方便的解决方案。 代码如下:
@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);
}
}
如我所见,阅读Roboguice文档时,仅将Roboguice框架用于Android编程。 请参阅以下链接 。
在Activity中调用super.onCreate()方法时,将完成注入。
这是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;
}
});
因此,我建议使用静态值来引用serverBaseUrl 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.