-2

Here I inject a SimpleDynamicString object to my presenter in a MVP structure. To avoid a NullPointerException, I have to implement this.

@Provides
@StringForTextView
static DynamicString provideDynamicString(Application application)
{
    return new SimpleDynamicString(application.getString(R.string.example_string));
}

Since I would like to use this one as a library, I am forced to implement everywhere.

Can I avoid this, so if (accidenataly or not) forgotten, no NullPointerException will happen?

Johnny Five
  • 987
  • 1
  • 14
  • 29
Ralf Wickum
  • 2,850
  • 9
  • 55
  • 103

2 Answers2

2

Your DynamicString's provides method is unscoped. StringForTextView is a qualifier annotation (meaning that Dagger can understand which DynamicString you want if you have more than one provides method). Also currently, because of your provides method is unscoped, Dagger is creating new instances when you inject.

If you want to use same instance of the DynamicString anywhere in your application, you need to create a Singleton component, put this provides method into a Singleton module and make the method's scope Singleton. If you make it Singleton, you can write one provides method and inject anywhere.

@Singleton
@Component(modules = {SingletonModule.class})
public interface SingletonComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        Builder application(Application application);

        Builder singletonModule(SingletonModule singletonModule);

        SingletonComponent build();
    }

    void inject(YourClassToInject yourClassToInject);

}

@Module
public class SingletonModule {

    @StringForTextView // this is qualifier annotation
    @Singleton // this is scope annotation
    @Provides
    DynamicString provideDynamicString(Application application)
        return new SimpleDynamicString(application.getString(R.string.example_string));
    }
}

More information about scopes:

Mustafa Berkay Mutlu
  • 1,929
  • 1
  • 25
  • 37
0

I think you're asking about an optional binding.

@BindsOptionalOf abstract CoffeeCozy optionalCozy();