简体   繁体   中英

Getting user attributes from Cognito User Pool

I tried the below code to get a user's attribute (email-id) from cognito user pool of AWS, but it doesn't seem to work.

How can this be done and what is the problem in my code?

AWSMobileClient.getInstance().initialize(this, new AWSStartupHandler() {
    public DynamoDBMapper dynamoDBMapper;

    @Override
    public void onComplete(AWSStartupResult awsStartupResult) {
        PinpointConfiguration pinpointConfig = new PinpointConfiguration(
                getApplicationContext(),
                AWSMobileClient.getInstance().getCredentialsProvider(),
                AWSMobileClient.getInstance().getConfiguration());
        pinpointManager = new PinpointManager(pinpointConfig);

        // Start a session with Pinpoint
        pinpointManager.getSessionClient().startSession();

        AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(AWSMobileClient.getInstance().getCredentialsProvider());
        this.dynamoDBMapper = DynamoDBMapper.builder().dynamoDBClient(dynamoDBClient).awsConfiguration(AWSMobileClient.getInstance().getConfiguration()).build();
        identityManager=new IdentityManager(getApplicationContext(),AWSMobileClient.getInstance().getConfiguration());
        CognitoUserPool userPool = new CognitoUserPool(getApplicationContext(),"xx-xxxxx-xxxx-xx","xxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

        CognitoUser user = userPool.getUser(identityManager.getCachedUserID());
        GetDetailsHandler handler = new GetDetailsHandler() {
            @Override
            public void onSuccess(CognitoUserDetails cognitoUserDetails) {
                Map user = cognitoUserDetails.getAttributes().getAttributes();
                Collection<Object> keys = user.keySet();
                for (Object entry:keys
                     ) {
                    Log.d("key",entry.toString());
                }
            }

            @Override
            public void onFailure(Exception exception) {
                Log.d("details","fail");
            }
        };
        user.getDetails(handler);

Try using entrySet() and make sure userPool have (email-id) attribute

    @Override
    public void onSuccess(CognitoUserDetails cognitoUserDetails) {
        Map<String, String> user = cognitoUserDetails.getAttributes().getAttributes();
        for (Map.Entry<String, String> entry : user.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            Log.d("key", "key: " + key);
            Log.d("key", "value: " + value);
            settings.edit().putString(key, value).apply();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM