Home » Android » android – Creating Singleton Classes with Dagger2 throws NullPointerException-Exceptionshub

android – Creating Singleton Classes with Dagger2 throws NullPointerException-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am trying to create Singleton Objects for a few classes using Dagger. my code structure is below. I get NullPointer on calling any methods in all dependencies injected using dagger.
I have used here and here {this does not create DaggerApplicationGraph for me}

Main build.gradle dependencies

...
api 'com.google.dagger:dagger-android:2.24'
implementation "com.google.dagger:dagger:2.24"
annotationProcessor "com.google.dagger:dagger-compiler:2.13"
compileOnly 'javax.annotation:jsr250-api:1.0'
implementation 'javax.inject:javax.inject:1'

Module build.gradle dependencies

...
implementation "com.google.dagger:dagger:2.24"
annotationProcessor "com.google.dagger:dagger-compiler:2.13"
compileOnly 'javax.annotation:jsr250-api:1.0'
implementation 'javax.inject:javax.inject:1'

FactoryUtils.java

@Module
public class FactoryUtils {

    @Provides
    @Singleton
    FirestoreChatEngine getFireStoreEngineFactory(){
        return new FirestoreChatEngine();
    }

    @Provides
    @Singleton
    FirestoreComposer getFireStoreDocumentFactory(){
        return new FirestoreComposer();
    }

    @Provides
    @Singleton
    CentralDataManager getDataAccessorFactory(){return new CentralDataManager();
}

MessageGateway.java

public class MessageGateway {
        @Inject
        FirestoreChatEngine engine;

        private MessageGateway(){
            //ApplicationGraph applicationGraph = DaggerApplicationGraph.create();
            //engine = applicationGraph.createFireStoreEngine();
        }

        public static MessageGateway getInstance() throws GatewayInitException{
            if(null == instance){
                throw new GatewayInitException(GatewayInitException.MESSAGE_NOT_CREATED);
            }
            return instance;
        }
        public void foo(){
            engine.otherMethods();
        }
}

FirestoreChatEngine.java

@Singleton
public class FirestoreChatEngine {

    private FirebaseFirestore database;

    @Inject
    FirestoreComposer composer;
    @Inject
    CentralDataManager accessor;

    @Inject
    public FirestoreChatEngine(){
        this.database = FirebaseFirestore.getInstance();
    }
    public void otherMethods(){
        composer.otherMethods();
        accessor.foo();
    }
}

FirestoreComposer.java

@Singleton
public class FirestoreComposer {

    private FirebaseFirestore database;

    @Inject
    public FirestoreComposer() {
        this.database = FirebaseFirestore.getInstance();
    }
   public void otherMethods(){}
}

CentralDataStore.java

@Singleton
public class CentralDataManager {
    @Inject
    public CentralDataManager(){
        init();
    }
    public void foo(){
       // do something;
    }
}
How to&Answers: