Julian A.
Julian A.

Reputation: 11460

Inject Android Activity into a POJO with Roboguice

Is there a way to inject an Android Activity subclass into a POJO using Roboguice?

Upvotes: 2

Views: 2107

Answers (1)

RichardWilliams
RichardWilliams

Reputation: 85

Firstly this is my first ever post on here, so I am being brave and hopefully I can answer your question, and hopefully not go into negative figures as soon as I start.

Bare in mind I have only just discovered Roboguice in the last couple of days so hopefully I can help out here. Also my first stab at Java from using .Net so much so apologies if i have the incorrect syntax for the usual Java style.

I guess it depends on which Activity you want, the activity that creates the instance of the Pojo or another activity.

I will try to put an example here for both on what I set up and tried out.

public interface IMySecondActivity {}
public class MySecondActivity extends RoboActivity implements IMySecondActivity {}

public interface ITestPojo {}
public class TestPojo implements ITestPojo 
{
  @Inject public TestPojo(IMySecondActivity mySecondActivity, Activity activity)
  {
    //So at this point here mySecondActivity is an instance of IMySecondActivity    
    //set up by roboguice
    //and activity is the activity which created this TestPojo
  }
}

public class TestAppModule extends AbstractAndroidModule 
{
  @Override protected void configure()
  {
    bind(ITestPojo.class).to(TestPojo.class);
    bind(IMySecondActivity.class).to(MySecondActivity.class);
  }
}

public class MyActivity extends RoboActivity implements IMyActivity
{
  @Inject ITestPojo testPojo;

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
}

So I have configured the Module for RoboGuice to know how to bind ITestPojo and IMySecondActivity.

Lets assume we are currently on the MyActivity activity, when this starts up, an instance of TestPojo is injected in. During this injection its constructor is called and the parameters to TestPojo constructor are resolved, IMySecondActivity via the binding and Activity from the containing MyActivity.

However, I guess care will have to be taken with this situation as testPojo will still be null inside MyActivity, as TestPojo is still in construction.

There is also another way we could get the Activity and that is to use the Provider

Provider<Activity> activityProvider;
public TestPojo(Provider<Activity> activity)
{
  activityProvider = activity;
}

public void Test()
{
  //This should retrieve your activity.
  Activity activity = activityProvider.get();
}

in the TestPojo class so that the provider can be asked at a later time to retrieve the Activity at the point where its used.

If you know the activity type your pojo is going to use then you can use Provider<MyActivity> instead.

I hope this helps out :-)

Upvotes: 6

Related Questions