У меня проблема с приложением в аутентификации Google.Когда я пытаюсь нажать на кнопку входа в Google, мне не удается войти на главную страницу.
Вот код:
открытый класс RegisterActivity расширяет AppCompatActivity реализует GoogleApiClient.OnConnectionFailedListener {
private static final int PERMISSION_SIGN_IN = 9999;
GoogleApiClient mGoogleApiClient;
SignInButton signInButton;
private EditText userEmail,userPassword,userName;
private Button regBtn;
private FirebaseAuth mAuth;
AlertDialog waiting_dialog;
FirebaseAuth firebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
configureGoogleSignIn();
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
userEmail = findViewById(R.id.regMail);
userPassword = findViewById(R.id.regPassword);
userName = findViewById(R.id.regName);
regBtn = findViewById(R.id.regBtn);
mAuth = FirebaseAuth.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
regBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
regBtn.setVisibility(View.INVISIBLE);
final String email = userEmail.getText().toString();
final String password = userPassword.getText().toString();
final String name = userName.getText().toString();
if ( email.isEmpty() || name.isEmpty() || password.isEmpty() ) {
showMessage("Please Verify all fields");
regBtn.setVisibility(View.VISIBLE);
}
else {
CreateUserAccount(email, name, password);
}
}
});
ImgUserPhoto = findViewById(R.id.regUserPhoto) ;
ImgUserPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 22) {
checkAndRequestForPermission();
}
else
{
openGallery();
}
}
});
}
private void signIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(intent,PERMISSION_SIGN_IN);
}
private void configureGoogleSignIn() {
GoogleSignInOptions options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(RegisterActivity.this,"Something Went Wrong", Toast.LENGTH_SHORT).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API,options)
.build();
mGoogleApiClient.connect();
}
private void openGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,REQUESCODE);
}
private void checkAndRequestForPermission() {
if (ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(RegisterActivity.this,"Please accept for required permission",Toast.LENGTH_SHORT).show();
}
else
{
ActivityCompat.requestPermissions(RegisterActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PReqCode);
}
}
else
openGallery();
}
private void CreateUserAccount(String email, final String name, String password) {
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// user account created successfully
showMessage("Account created");
// after we created user account we need to update his profile picture and name
updateUserInfo(name ,pickedImgUri ,mAuth.getCurrentUser());
}
else
{
// account creation failed
showMessage("account creation failed" + task.getException().getMessage());
regBtn.setVisibility(View.VISIBLE);
}
}
});
}
// update user photo and name
private void updateUserInfo(final String name, Uri pickedImgUri, final FirebaseUser currentUser) {
// first we need to upload user photo to firebase storage and get url
StorageReference mStorage = FirebaseStorage.getInstance().getReference().child("users_photos");
final StorageReference imageFilePath = mStorage.child(pickedImgUri.getLastPathSegment());
imageFilePath.putFile(pickedImgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// image uploaded succesfully
// now we can get our image url
imageFilePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
// uri contain user image url
UserProfileChangeRequest profleUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(uri)
.build();
currentUser.updateProfile(profleUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
// user info updated successfully
showMessage("Register Complete");
updateUI();
}
}
});
}
});
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == PERMISSION_SIGN_IN)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess())
{
waiting_dialog.dismiss();
GoogleSignInAccount account = result.getSignInAccount();
String idToken = account.getIdToken();
AuthCredential credential = GoogleAuthProvider.getCredential(idToken,null);
firebaseAuthWithGoogle(credential);
}
else {
Log.e("Error","Login failed");
Log.e("Error",result.getStatus().getStatusMessage());
}
}
if (resultCode == RESULT_OK && requestCode == REQUESCODE && data != null ) {
// the user has successfully picked an image
// we need to save its reference to a Uri variable
pickedImgUri = data.getData() ;
ImgUserPhoto.setImageURI(pickedImgUri);
}
}
private void firebaseAuthWithGoogle(AuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Intent intent = new Intent(RegisterActivity.this,Home.class);
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(RegisterActivity.this, "wrong "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void updateUI() {
Intent home = new Intent(getApplicationContext(),Home.class);
startActivity(home);
finish();
}
private void showMessage(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(this, "dfassd"+connectionResult.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
это при нажатии появляется, но после нажатия не получается
Это макет моего приложения