Question

I have a Customer class and i have injected it's dependencies with the @Inject annotation. I'd like to create a method in this class that returns a new instance of the class.

class Customer{

    //the DataSource class is annotated with @Singleton
    @Inject protected DataSource dataSource;

    public DataSource getDatasource(){
        return dataSource;
    }

    public Customer newInstance(){
        return new Customer();
    }
}

In my activity i'm having one customer injected via the @Inject annotation. In the onCreate() method i'm getting another Customer instance by calling customer.newInstance() but when i do the following, the datasource for the second Customer object is null. How do i create a new object on demand through RoboGuice ensuring it has its dependencies?

if(customer.newInstance().getDatasource() == null){
    //This gets logged
    Log.d("DEBUG", "2nd customer's datasource is null");
}

Any help would be much appreciated.

Was it helpful?

Solution

Figured it out with the following.

class Customer{

    //the DataSource class is annotated with @Singleton
    @Inject protected DataSource dataSource;

    @Inject protected Injector injector;

    public DataSource getDatasource(){
        return dataSource;
    }

    public Customer newInstance(){
        return injector.getInstance(getClass());
    }
}

OTHER TIPS

You may try following way to create a new Object for your Customer Class,

Customer newObject; 

newObject = newInstance();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top