Я нахожусь в процессе добавления номера телефона и входа в учетную запись Google в мое приложение. (Я даже пытался спросить CHATGPT и Gemini, не помог )
в основном, в каждом способе, когда я пробовал, в итоге не удалось, потому что компилятор не распознает методы в учетных записях (я использую правильный, новый, версия Androidx Imported Class). Фрагмент. Соответствующий код: in oncreateview ():
//the method handling and returning the appropriate Task for the googleID sign-in process:
private Task getGoogleCredentialTask(Context context) {
TaskCompletionSource taskCompletionSource = new TaskCompletionSource();
GetGoogleIdOption googleIdOption = new GetGoogleIdOption.Builder()
.setFilterByAuthorizedAccounts(false)
.setServerClientId(CLIENT_ID)
.build();
GetCredentialRequest request = new GetCredentialRequest.Builder()
.addCredentialOption(googleIdOption)
.build();
Executor executor = context != null ? ContextCompat.getMainExecutor(context) : Runnable::run;
--------**The error is right here!**---------------------------------------------------
credentialManager.getCredential(requireActivity(), request)
.addOnSuccessListener(executor, taskCompletionSource::setResult)
.addOnFailureListener(executor, taskCompletionSource::setException);
-----------------------------------------------------------------------------------
return taskCompletionSource.getTask();
}
//the method to initiate google sign-in with the given GoogleID credential:
private void signInWithGoogleId(Credential credential){
//make sure the given credential is a GoogleID credential:
if(credential instanceof CustomCredential && credential.getType().equals(TYPE_GOOGLE_ID_TOKEN_CREDENTIAL)){
//create GoogleID token from the credential:
CustomCredential customCredential = (CustomCredential) credential;
Bundle bundle = customCredential.getData();
GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(bundle);
//authorize with firebase: with a method.
authorizeWithFirebaseGoogle(googleIdTokenCredential.getIdToken());
} else{
Toast.makeText(getContext(), "Credential type is not of GoogleID!", Toast.LENGTH_SHORT).show();
}
}
//the method to authorize with firebase with a GoogleID token (final step):
private void authorizeWithFirebaseGoogle(String idToken){
AuthCredential authCredential = GoogleAuthProvider.getCredential(idToken, null);
mAuth.signInWithCredential(authCredential).addOnCompleteListener(requireActivity(), new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
handleSignInResult(task);
}
});
}
//as i said, this isn't only for the google sign-in. This method works great.
//handle the sign-in result from the googleID sign-in and phone number sign-in:
private void handleSignInResult(Task task){
if(task.isSuccessful()){
//great! the user has been approved and the sign in was successful.
Toast.makeText(getContext(), "Signed-in successfully! P", Toast.LENGTH_SHORT).show();
//insert the user:
firebaseUser = task.getResult().getUser();
//Done!
} else{
//the sign-in has not been approved.
Toast.makeText(getContext(), "Sign-in failed.", Toast.LENGTH_SHORT).show();
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid:
Toast.makeText(getContext(), "The verification code is wrong. Try again.", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getContext(), "Other Error.", Toast.LENGTH_SHORT).show();
}
}
}
< /code>
Сама ошибка: < /p>
Cannot resolve method 'getCredential(FragmentActivity, GetCredentialRequest)'
Candidates for method call credentialManager. getCredential(requireActivity(), request) are:
Object getCredential(Context, GetCredentialRequest, Continuation
Подробнее здесь: [url]https://stackoverflow.com/questions/79589418/how-to-make-getcredential-work-in-java[/url]
Я нахожусь в процессе добавления номера телефона и входа в учетную запись Google в мое приложение. (Я даже пытался спросить CHATGPT и Gemini, не помог :)) в основном, в каждом способе, когда я пробовал, в итоге не удалось, потому что компилятор не распознает методы в учетных записях (я использую правильный, новый, версия Androidx Imported Class). Фрагмент. Соответствующий код: [b] in oncreateview (): [/b] [code] //instance the mAuth as an instance of FirebaseAuth: mAuth = FirebaseAuth.getInstance(); //instance the CredentialManager: credentialManager = CredentialManager.create(requireContext());
googleSignInButton.setOnClickListener(v -> {
//start the sign-in process: if(isAdded()){ getGoogleCredentialTask(requireContext()) .addOnSuccessListener(response -> { Credential credential = response.getCredential(); signInWithGoogleId(credential); }) .addOnFailureListener(e -> { Log.e(TAG, "Google sign-in failed" + e); Toast.makeText(getContext(), "Google sign-in failed: " + e, Toast.LENGTH_SHORT).show(); }); } } [/code] [b] Outs OncreatView (), на уровне фрагмента: [/b] [code] //the method handling and returning the appropriate Task for the googleID sign-in process: private Task getGoogleCredentialTask(Context context) { TaskCompletionSource taskCompletionSource = new TaskCompletionSource();
GetGoogleIdOption googleIdOption = new GetGoogleIdOption.Builder() .setFilterByAuthorizedAccounts(false) .setServerClientId(CLIENT_ID) .build();
GetCredentialRequest request = new GetCredentialRequest.Builder() .addCredentialOption(googleIdOption) .build();
--------**The error is right here!**--------------------------------------------------- credentialManager.getCredential(requireActivity(), request) .addOnSuccessListener(executor, taskCompletionSource::setResult) .addOnFailureListener(executor, taskCompletionSource::setException); -----------------------------------------------------------------------------------
return taskCompletionSource.getTask(); }
//the method to initiate google sign-in with the given GoogleID credential: private void signInWithGoogleId(Credential credential){ //make sure the given credential is a GoogleID credential: if(credential instanceof CustomCredential && credential.getType().equals(TYPE_GOOGLE_ID_TOKEN_CREDENTIAL)){ //create GoogleID token from the credential: CustomCredential customCredential = (CustomCredential) credential; Bundle bundle = customCredential.getData(); GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(bundle);
//authorize with firebase: with a method. authorizeWithFirebaseGoogle(googleIdTokenCredential.getIdToken());
} else{ Toast.makeText(getContext(), "Credential type is not of GoogleID!", Toast.LENGTH_SHORT).show(); }
}
//the method to authorize with firebase with a GoogleID token (final step): private void authorizeWithFirebaseGoogle(String idToken){ AuthCredential authCredential = GoogleAuthProvider.getCredential(idToken, null); mAuth.signInWithCredential(authCredential).addOnCompleteListener(requireActivity(), new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { handleSignInResult(task); } }); }
//as i said, this isn't only for the google sign-in. This method works great. //handle the sign-in result from the googleID sign-in and phone number sign-in: private void handleSignInResult(Task task){ if(task.isSuccessful()){ //great! the user has been approved and the sign in was successful. Toast.makeText(getContext(), "Signed-in successfully! P", Toast.LENGTH_SHORT).show(); //insert the user: firebaseUser = task.getResult().getUser(); //Done! } else{ //the sign-in has not been approved. Toast.makeText(getContext(), "Sign-in failed.", Toast.LENGTH_SHORT).show(); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid: Toast.makeText(getContext(), "The verification code is wrong. Try again.", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getContext(), "Other Error.", Toast.LENGTH_SHORT).show(); } } }