CognitoUserPool userPool = new CognitoUserPool(this, AWSMobileClient.getInstance().getConfiguration()); is giving null value

737 Views Asked by At

I am using AWS cognito for login in. I don't want to hardcode the values of userPoolId, clientId , clientSecret and region. I found a way using

CognitoUserPool userPool = new CognitoUserPool(this, AWSMobileClient.getInstance().getConfiguration());

but userPool is giving null value.

awsconfiguration.json is placed in res/raw/awsconfiguration.json

Thankyou for the help in advance!!!

2

There are 2 best solutions below

0
Roshan On BEST ANSWER

Elaborating on the point made in comment by Karthikeyan, you would have to ensure that the AWSMobileClient is indeed initialized before you can use it to get AWS Configuration. Following snippet demonstrates one way of achieving what you are looking for :

    CognitoUserPool cup;
    final CountDownLatch latch = new CountDownLatch(1);

    AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {

                @Override
                public void onResult(UserStateDetails userStateDetails) {
                    Log.i("INIT", "onResult: " + userStateDetails.getUserState());
                    latch.countDown();
                }

                @Override
                public void onError(Exception e) {
                    Log.e("INIT", "Initialization error.", e);
                    latch.countDown();
                }
            }
    );

    try {
        latch.await();
        cup = new CognitoUserPool(getApplicationContext(), AWSMobileClient.getInstance().getConfiguration());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

Hope it helps!

0
Harsha Jayamanna On

According to the documentation,

https://aws-amplify.github.io/docs/sdk/android/authentication

You need to go to your MainActivity and inside the onCreate() run the initialize() routine:

AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {

        @Override
        public void onResult(UserStateDetails userStateDetails) {
            Log.i("INIT", "onResult: " + userStateDetails.getUserState());
        }

        @Override
        public void onError(Exception e) {
            Log.e("INIT", "Initialization error.", e);
        }
    }
);

Since you haven’t logged in yet it will print a state of SIGNED_OUT.