I have tried dagger2 in my sample application after completion i try to build my code it is showing this exception.
code:
@Singleton
@Component(modules = {UserModule.class,BackendServiceModule.class})
public interface AppComponent {
BackendServiceModule provideBackendService();
// allow to inject into our Main class
// method name not important
void inject(MainActivity mainActivity);
}
public class AppGlobal extends Application
{
AppComponent appComponent;
public static AppGlobal global;
@Override
public void onCreate() {
super.onCreate();
global = this;
initAppComponent();
}
private void initAppComponent() {
}
public AppComponent getDataComponent() {
return appComponent;
}
}
public class BackendService {
@Inject
public User user;
private String serverUrl;
@Inject
public BackendService(@Named("serverUrl") String serverUrl) {
this.serverUrl = serverUrl;
}
public boolean callServer() {
if (user !=null && serverUrl!=null && serverUrl.length()>0) {
System.out.println("User: " + user + " ServerUrl: " + serverUrl);
return true;
}
return false;
}
}
@Module
public class BackendServiceModule
{
@Provides
@Singleton
BackendService provideBackendService(@Named("serverUrl") String serverUrl) {
return new BackendService(serverUrl);
}
@Provides
@Named("serverUrl")
String provideServerUrl() {
return "http://www.vogella.com";
}
@Provides
@Named("anotherUrl")
String provideAnotherUrl() {
return "http://www.google.com";
}
}
public class MainActivity extends AppCompatActivity {
@Inject
BackendService service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppGlobal.global.getDataComponent().inject(this);
TextView result = (TextView) findViewById(R.id.resulttxt);
result.setText(service.callServer()+"");
}
}
public class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return "User [firstName=" + firstName + ", lastName=" + lastName + "]";
}
@Module
public class UserModule
{
@Singleton
@Provides
User providesUser()
{
return new User("syam","jjjj");
}
}
exception: Error:(16, 26) error: com.example.intrio.daggersample2.BackendServiceModule cannot be provided without an @Inject constructor or from an @Provides-annotated method. com.example.intrio.daggersample2.BackendServiceModule is provided at com.example.intrio.daggersample2.AppComponent.provideBackendService()