Skip to content

User Management

Introduction

If you have configured your application, you can start using GetSocial without any additional steps. GetSocial creates anonymous user by default, so you can access all the features right after SDK gets initialized.

Anonymous user is just a user, that has no identities added. User is created per device and stays there for next sessions. Anonymous users have default names like “User 12345678”, but you can change it using GetSocial.User.setDisplayName method.

To check if user is anonymous use GetSocial.User.isAnonymous().

Login

If you have internal login system or use any social authentication, you should connect your account to GetSocial user, so you can retrieve the same GetSocial user from another devices or recover it once app was reinstalled or user was logged out.

To connect GetSocial user with yours, you should add your identity to GetSocial user.

Identities

An identity is some unique user data to identify them among other users. You can use any auth provider to create an identity (your custom login, facebook, twitter, google, github, etc). Each user may have any number of different identities, but only one of the same provider. It means that you may attach one facebook, one twitter and one custom identity, but you can not attach two facebook identities. Read more how to attach multiple identities.

To create an identity, use AuthIdentity.createFacebookIdentity(fbAccessToken) for Facebook or AuthIdentity.createCustomIdentity(providerId, userId, accessToken) for any other provider, where:

  • providerId is a unique String defined by you for each provider (twitter, my_auth_system, gamecenter, etc).
  • userId is a unique String for each user in the provided authentication system. So pair providerId-userId is unique for each user and helps GetSocial identify a user if them try to login from another device.
  • accessToken is a String for security check, that could be some internal hash function in your app based on userId. If user is trying to authenticate again with the same providerId and userId, but different accessToken - GetSocial won’t allow to authenticate. accessToken can not be changed.

Add Identity

You have to add an identity to GetSocial user in the success callback of your authentication system.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public void onLoginSuccess() {
    String userId = getCurrentUserId(); // get user ID on your login provider
    String accessToken = calculateAccessTokenForUser(userId); // see the example of such a function below
    final AuthIdentity identity = AuthIdentity.createCustomIdentity("my_auth_system", userId, accessToken);

    GetSocial.User.addAuthIdentity(identity, new AddAuthIdentityCallback() {
            @Override
            public void onComplete() {
                Log.d("GETSOCIAL", "Successfully logged into " + userId);
            }

            @Override
            public void onFailure(GetSocialException exception) {
                Log.d("GETSOCIAL", "Failed to log into " + userId + ", exception: " + exception.getMessage());
            }

            @Override
            public void onConflict(ConflictUser conflictUser) {
                handleConflict(identity, conflictUser);
            }
        })
}

// it should be always the same for the same value, so hashCode method perfectly fits to this job, but you can introduce something more advanced
public static String calculateAccessTokenForUser(String userId) {
    return String.valueOf(userId.hashCode());
}

Add Facebook Identity

To add Facebook identity, you should provide the token you got from Facebook SDK after user’s authentication.

  1. Integrate Facebook Android SDK into your app as described in the Official Guide.

  2. Add Facebook identity to GetSocial user. Sample code is below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
final AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
    @Override
    protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken) {
        stopTracking(); // stop tracking facebook access token changes as we don't need it anymore

        AuthIdentity authIdentity = AuthIdentity.createFacebookIdentity(newAccessToken.getToken());
        GetSocial.User.addAuthIdentity(authIdentity, completionCallback);
    }
};
accessTokenTracker.startTracking();

LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_friends")); // we need "user_friends" permission to import list of Facebook friends to GetSocial Social Graph

For Facebook, we will retrieve the list of Facebook friends and import them to Social Graph, so you can get list of user’s friends through GetSocial.

GetSocial doesn’t automatically sync your Facebook profile info

Don’t forget to sync the display name and avatar of the GetSocial user with the values from Facebook. You can do it with a batch update to make it in one call.

Facebook SDK compatibility

GetSocial is compatible with Facebook Android SDK v4.x, older versions are not supported.

Handle Conflicts

Besides onSuccess and onFailure methods, AddAuthIdentityCallback has onConflict. Conflict happens when identity you’re trying to add is already attached to one of GetSocial users. It may happen when:

  • User has already logged in on another device.
  • User reinstalled the application.
  • User cleared application data.

Depending on the user intention and your application logic, you can choose one of the following strategies to resolve the conflict.

Strategy 1: stay with current user and don’t add identity:

1
2
3
4
5
@Override
public void handleConflict(AuthIdentity identity, ConflicUser conflictUser) {
    // Do nothing in onConflict and user will stay the same.
    // Identity won't be added to any of the users.
}

Strategy 2: switch to conflict user:

1
2
3
4
5
6
7
@Override
public void handleConflict(AuthIdentity identity, ConflicUser conflictUser) {
    // Call switchUser to replace current user with conflict one and add identity to conflict user.
    // After the successful switch, current user and his referral data will be lost. 
    // To save the data: 1. copy data to intermediate variables; 2. save in to the conflict user properties after the successful switch.  
    GetSocial.User.switchUser(identity, completionCallback);
}

Logout

If your users can log out of your app, you should log out of GetSocial user too. Otherwise it will stay the same and will have connection with another user that will login after.

1
2
3
4
public void onLogoutSuccess() {
    // New anonymous will be created. If your current user is anonymous - it will be lost.
    GetSocial.User.reset(completionCallback);
}

If you’re subsribed to GetSocial user change then your OnUserChangedListener will be invoked.

Change Logged In User

If you want to switch from one logged in user to another, do Logout first and then Login with a new user.

Warning

Don’t forget to do the logout, it is important to keep your user connected with proper GetSocial user, so you will receive correct analytics and referral data.

Manage User Profile

Display Name

Check current username with GetSocial.User.getDisplayName() method. To update display name use GetSocial.User.setDisplayName(newDisplayName, completionCallback).

Avatar

Get current avatar URL with GetSocial.User.getAvatarUrl() method. You can set a new avatar in two ways:

  • Set a URL - GetSocial.User.setAvatarUrl(avatarUrl, completionCallback).
  • Set a Bitmap object - GetSocial.User.setAvatar(bitmapAvatar, completionCallback). Recommended size is 300x300 px, bigger images will be automatically downscaled.

User Properties

Custom properties are String to String map of any information your want to store.

There’re some limitations about properties:

  • Max key length is 32 symbols.
  • Max value length is 1024 symbols.
  • Min value length is 1 symbol, you can not set an empty property, it will just remove a current value if it exists.

There are Public and Private properties. Private properties are accessible only by current user with methods listed in GetSocial.User class, Public can be accessed by other users with methods from PublicUser object.

Private Properties

To set a private property:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
GetSocial.User.setPrivateProperty(key, value, new CompletionCallback() {
    @Override
    public void onSuccess() {
        Log.d(TAG, "Successfully set a private property");
    }

    @Override
    public void onFailure(GetSocialException exception) {
        Log.d(TAG, "Failed to set a private property, error: " + exception);
    }
});

In case if user already had a value for a current key, it will be overriden. You can prevent it with checking if property already exists:

1
boolean hasPrivateProperty = GetSocial.User.hasPrivateProperty(key);

You can get the current property value:

1
String currentValue = GetSocial.User.getPrivateProperty(key);

If you’re not interesting in keeping property for a user, remove it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
GetSocial.User.removePrivateProperty(key, new CompletionCallback() {
    @Override
    public void onSuccess() {
        Log.d(TAG, "Property was successfully removed");
    }

    @Override
    public void onFailure(GetSocialException error) {
        Log.d(TAG, "Failed to remove a property, error: " + error);
    }
});

You can get all properties as unmodifiable copy of origin map:

1
Map<String, String> userProperties = GetSocial.User.getAllPrivateProperties();

Note

You can not modify properties with this map. Also, changes in user properties won’t affect your copy, so you need to refresh it after any user changes. To have up-to-date information, we suggest to use GetSocial SDK methods.

Public Properties

You have similar methods to work with public properties, as for private ones:
setPublicProperty, getPublicProperty, hasPublicProperty and removePublicProperty.

In addition to this, Public properties are visible for other users, so if you have some PublicUser entity, you can get his public properties:

1
String value = user.getPublicProperty(key);

Or, you can check does user have a property:

1
boolean hasProperty = user.hasPublicProperty(key);

You can get all properties as unmodifiable copy of origin map:

1
Map<String, String> userProperties = user.getAllPublicProperties();

Note

You can not modify properties with this map. Also, changes in user properties won’t affect your copy, so you need to refresh it after any user changes. To have up-to-date information, we suggest to use GetSocial SDK methods.

Batch Properties Update

If you want to perform multiple updates of user data, you can do it with UserUpdate class. It allows you update few user properties(custom and not) in one request:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
UserUpdate batchUpdate = UserUpdate.createBuilder()
        .updateAvatarUrl(newAvatarUrl)
        .updateDisplayName(newDisplayName)
        .setPublicProperty(publicProperty1, newPublicValue)
        .removePublicProperty(publicProperty2)
        .setPrivateProperty(privateProperty1, newPrivateValue)
        .removePrivateProperty(privateProperty2)
        .build();

GetSocial.User.setUserDetails(batchUpdate, new CompletionCallback() {
    @Override
    public void onSuccess() {
        Log.d(TAG, "User details were successfully updated");
    }

    @Override
    public void onFailure(GetSocialException exception) {
        Log.d(TAG, "Failed to update user details, error: " + exception);
    }
});

Handle Multiple User Identities

You may want to connect multiple identities (login with Facebook and Google at the same time). It will allow to log into that user with different login providers.

Your user may have any number of different identities attached for different login providers, but only one identity for each provider.

To add a new identity use GetSocial.User.addAuthIdentity method. Once it is successfully added, you can log in using that identity.

To remove identity from user use GetSocial.User.removeAuthIdentity and pass the provider to be remove as first parameter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
String providerId = "my_auth_system";
GetSocial.User.removeAuthIdentity(providerId, new CompletionCallback() {
    @Override
    public void onSuccess() {
        Log.d("GETSOCIAL", "Identity successfully removed.");
    }

    @Override
    public void onFailure(GetSocialException e) {
        Log.d("GETSOCIAL", "Failed, while removing identity.");
    }
});

To get all user identities call GetSocial.User.getAuthIdentities(), it will return a map of identities, where key is providerId and value is userId for that provider.

Subscribe to User Lifecycle Changes

Implement im.getsocial.sdk.usermanagement.OnUserChangedListener interface in your activity:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MainActivity extends Activity implements OnUserChangedListener {

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

        // Setup GetSocial
        GetSocial.User.setOnUserChangedListener(this);

        ...
    }

    @Override
    public void onUserChanged() {
        Log.d(TAG, "Is SDK initialized?        " + GetSocial.isInitialized());
        Log.d(TAG, "Is user anonymous?         " + GetSocial.User.isAnonymous());
        Log.d(TAG, "What's user's avatar?      " + GetSocial.User.getAvatarUrl());
        Log.d(TAG, "What's user's name?        " + GetSocial.User.getDisplayName());
        Log.d(TAG, "List of user's identities: " + GetSocial.User.getAuthIdentities());
    }
}

Get Users

Get Current User

It is not possible to obtain the instance of a current user object, but SDK provides methods to read and update user properties via static GetSocial.User class.

Get User By ID

Public user profile is represented by PublicUser class. Object is read-only and provide access to name, avatar url, list of identities and public properties.

The easiest way to get instance of PublicUser is by GetSocial User Id:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
GetSocial.getUserById("GetSocial User Id", new Callback<PublicUser>() {
    @Override
    public void onSuccess(PublicUser publicUser) {
        // process user data
    }
    @Override
    public void onFailure(GetSocialException e) {
        // Ooops. There was some exception while getting other user details.
    }
});

Also you can get users by their identities:

Find Users

You can find users by their display name using GetSocial.findUsers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
UsersQuery query = UsersQuery.usersByDisplayName("John Doe").withLimit(10);
GetSocial.findUsers(query, new Callback<List<UserReference>>() {
    @Override
    public void onSuccess(List<UserReference> users) {
        // Show list of users
    }

    @Override
    public void onFailure(GetSocialException exception) {
        // Error occured
    }
});

Next Steps

Well-done! Your user is set up, see what to do next:

  • Connect your user with others using our Social Graph.
  • Post to global or custom news feeds and communicate with others with Activity Feed.

Give us your feedback! Was this article helpful?

πŸ˜€ πŸ™