javaandroidkotlinandroid-credential-manager

How to call androidx CredentialManager's clearCredentialState in Java?


Referring to this method

https://developer.android.com/reference/androidx/credentials/CredentialManager#clearCredentialState(androidx.credentials.ClearCredentialStateRequest)

I was wondering how I can call it from Java?

I am using the following Java code.

Context context = getContext();

// Initialize the CredentialManager instance
CredentialManager credentialManager = CredentialManager.create(context);

// Create a request to clear the credential state
ClearCredentialStateRequest request = new ClearCredentialStateRequest();

credentialManager.clearCredentialState(request);

But, I am getting the following compiler error

required: ClearCredentialStateRequest,Continuation<? super Unit>
found:    ClearCredentialStateRequest
reason: actual and formal argument lists differ in length

Solution

  • The method signature for clearCredentialState shows that is a suspend method that requires the use of Kotlin Coroutines.

    As explained in the documentation for clearCredentialStateAsync:

    This API uses callbacks instead of Kotlin coroutines.

    So you can use that method for clearing the credential state in Java:

    credentialManager.clearCredentialStateAsync(
      request,
      null, // pass in a CancelationSignal to allow cancelling the request
      Runnable::run, // Execute the callback immediately
      new CredentialManagerCallback<Void, ClearCredentialException>() {
        @Override
        public void onResult(@NonNull Void result) {
          // Handle success
        }
    
        @Override
        public void onError(@NonNull ClearCredentialException e) {
          // Handle errors
        }
      });
    );