An Inject with a constructor that accepts a parameter using RoboGuice 2

This is the first time I'm trying to use RoboGuice2 for Android (and Guice), and now I'm stuck. I could not find an example of how to do this, and I would like someone to show me the right way with an explanation. I want a @Inject object that takes a string as a parameter in the constructor. Example below:

public class MyActivity extends RoboFragmentActivity { @Inject MyObject obj; public void onCreate(Bundle savedInstanceState) { super.onCreate(); obj.print(); } } public class MyObject { private String name; @Inject public MyObject(String name) { this.name = name; } public void print() { Log.d("debug", this.name); } } 

I would be very grateful for an example and explanation of this.

+4
source share
1 answer

I'm not sure that you can add a RoboGuice object when passing a parameter to its constructor (and this, of course, is not recommended) . Maybe you should consider changing any method that you call for this object that writes to the file system to accept this String parameter. If you do not like this parameter, you can simply use the public method to set this parameter before calling the write function.

Example:

 @Inject private MyClass myClass; public void onCreate(Bundle savedInstanceState) { super.onCreate(); myClass.setFileName("somefile.txt"); myClass.writeToFile(); } 

or

 @Inject private MyClass myClass; public void onCreate(Bundle savedInstanceState) { super.onCreate(); myClass.writeToFile("somefile.txt"); } 

EDIT:

So, after some research, I am returning my statement about this, not encouraging. From the examples I saw, your code looks mostly correct. This link provided the most comprehensive example I could find. There seem to be two options if you want to insert a String into the constructor. you can configure it in your application configuration settings (which essentially creates a singleton that you probably don't need). The second option is to create a Provide (similar to Factory) and use this provider. Both of these options are outlined in the article above.

+2
source

All Articles