1
votes

I am totally new to dagger2 hopefully help me :)

I am implementing a small demo but I'm conguiente the following error: Error: (20, 10) error: android.net.ConnectivityManager can not be provided without an @Inject builder or from an @ or @ Produces Provides--annotated method. com.edwin.dagger1.MainActivity.connectivityManager [Injected field of type: android.net.ConnectivityManager connectivityManager]

public class Dagger2Application extends Application {

    private SystemComponent systemComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        systemComponent = DaggerSystemComponent.builder()
                .systemModule(new SystemModule(this))
                .build();
    }

    public SystemComponent getSystemComponent() {
        return systemComponent;
    }
}
@Module
public class SystemModule {
    private final Application application;

    public SystemModule(Application application) {
        this.application = application;
    }

    @Provides
    @Singleton
    public Context provideContext(){
        return application;
 
@Singleton
@Component(modules = SystemModule.class)
public interface SystemComponent {
    void inject(MainActivity activity);
}

public class MainActivity extends AppCompatActivity {

    @Inject
    ConnectivityManager connectivityManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Dagger2Application dagger2Application=(Dagger2Application)getApplication();
        dagger2Application.getSystemComponent().inject(this);


        boolean activeNetworkMetered = connectivityManager.isActiveNetworkMetered();
        Log.d("Network is metered? " , activeNetworkMetered+"");
    }
}
1

1 Answers

0
votes

The problem is in injecting the ConnectivityManager class. I modified some code. Please have a look, hope this wil help you

public interface IConnectivityManager {
    boolean getActiveNetworkMetered();
}


public class IConnectivityManagerImpl implements IConnectivityManager {

    private Context context;

    public IConnectivityManagerImpl(Context context) {
        this.context = context;
    }

    @Override
    public boolean getActiveNetworkMetered() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return connectivityManager.isActiveNetworkMetered();
    }
}

MainActivity.class

 @Inject
    IConnectivityManager connectivityManager;
 boolean activeNetworkMetered = connectivityManagers.getActiveNetworkMetered();
        Log.d("Network is metered? " , activeNetworkMetered+"");

SystemModule.class

   @Provides
    @Singleton
    public IConnectivityManager provideConnectivity(Context context){
        return new IConnectivityManagerImpl(context);
    }