Firebase登录 - 加载卡住

时间:2018-05-08 18:49:41

标签: java android firebase authentication firebase-authentication

我的问题是,在完成注册或注册表单后 - 用户正在我的Firebase中正确显示 - 但加载不断转动,不要转到下一页。

表单如下:LoginActivity.java然后menuPrincipal.java

- 或 - ,profileRegistration.javaprofileRegistration.java,然后是menuPrincipal.java

代码中没有显示错误。唯一奇怪的是profileRegistration.java:

public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        progressBarImage.setVisibility(View.GONE);
                        profileImageUrl =   taskSnapshot.getDownloadUrl().toString();
                    }

.getDownloadUrl()被越过,它表示它已被弃用,但它没有发生任何错误。

这是我的LoginActivity.java

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class LoginActivity extends AppCompatActivity implements     View.OnClickListener {

FirebaseAuth mAuth;
EditText emailLogin, passwordLogin;
ProgressBar progressBar;

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

    mAuth = FirebaseAuth.getInstance();


    findViewById(R.id.signUp).setOnClickListener(this);
    findViewById(R.id.logNow).setOnClickListener(this);

    emailLogin = (EditText) findViewById(R.id.emailLogin);
    passwordLogin = (EditText) findViewById(R.id.passwordLogin);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);


}

private void userLogin() {

    String email = emailLogin.getText().toString().trim();
    String password = passwordLogin.getText().toString().trim();

    if(email.isEmpty()) {
        emailLogin.setError("Email is required.");
        emailLogin.requestFocus();
        return;
    }

    //Ceci est pour check si l'adresse email est valide
    if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
        emailLogin.setError("Please Enter a valide email.");
        emailLogin.requestFocus();
        return;
    }

    //Ceci est pour vérifier si le champs du mot de passe est rempli
    if (password.isEmpty()) {
        passwordLogin.setError("Password is required");
        passwordLogin.requestFocus();
        return;
    }

    //Ceci est la condition du mot de passe qui doit être de plus de 6 caractères
    if (password.length()<6) {
        passwordLogin.setError("Minimum length of password is 6.");
        passwordLogin.requestFocus();
        return;
    }

    //Ceci est pour le gif loading pendant la création du compte
    progressBar.setVisibility(View.VISIBLE);

    //Ceci permet de passer au Menu Principal une fois que le login est successful
    mAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                     // signed in user can be handled in the listener.
                    progressBar.setVisibility(View.GONE);
                    if (!task.isSuccessful()) {

                    }
                      else{
                        Intent intent = new Intent(LoginActivity.this, menuPrincipal.class);
                        startActivity(intent);
                        finish();
                    }
                }
 });


 }

 @Override
 public void onClick(View view) {
    switch (view.getId()) {
        case R.id.signUp:

            startActivity(new Intent(this, RegistrationActivity.class));

            break;

        case R.id.logNow:
          userLogin();
          break;
    }
  }
}

以下是RegistrationActivity.java

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;

public class RegistrationActivity extends AppCompatActivity implements View.OnClickListener {

ProgressBar progressBar;
Button returnButton, doneRegister;
EditText emailRegister, passwordRegister;

private FirebaseAuth mAuth;

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

    returnButton = (Button) findViewById(R.id.returnButton);
    doneRegister = (Button) findViewById(R.id.doneRegister);
    emailRegister = (EditText) findViewById(R.id.emailRegister);
    passwordRegister = (EditText) findViewById(R.id.passwordRegister);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    returnButton.setOnClickListener(this);

    mAuth = FirebaseAuth.getInstance();

    findViewById(R.id.doneRegister).setOnClickListener(this);
    doneRegister.setOnClickListener(this);

}

//Ceci est si les champs email ou mot de passe ne sont pas remplis
private void doneReg(){

    String email = emailRegister.getText().toString().trim();
    String password = passwordRegister.getText().toString().trim();

    if(email.isEmpty()) {
        emailRegister.setError("Email is required.");
        emailRegister.requestFocus();
        return;
    }

    //Ceci est pour check si l'adresse email est valide
    if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
        emailRegister.setError("Please Enter a valide email.");
        emailRegister.requestFocus();
        return;
    }

    //Ceci est pour vérifier si le champs du mot de passe est rempli
    if (password.isEmpty()) {
        passwordRegister.setError("Password is required");
        passwordRegister.requestFocus();
        return;
    }

    //Ceci est la condition du mot de passe qui doit être de plus de 6 caractères
    if (password.length()<6) {
        passwordRegister.setError("Minimum length of password is 6.");
        passwordRegister.requestFocus();
        return;
    }

    //Ceci est pour le gif loading pendant la création du compte
    progressBar.setVisibility(View.VISIBLE);

    //Ceci est pour la création de nouveaux utilisateurs
    mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            Toast.makeText(RegistrationActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
            if(task.isSuccessful()) {
                //Ici, si l'inscription est successful on va arriver au profile
                Intent intent = new Intent(RegistrationActivity.this, profileRegistration.class);
                //Cette ligne empêche de revenir au loginActivity
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

            } else {
                //Si l'utilisateur veux s'inscrire avec un email déjà existant
                if (task.getException()instanceof FirebaseAuthUserCollisionException) {
                    Toast.makeText(getApplicationContext(), "You are already register. Please log in.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
}

//Passer d'une activité à une autre
@Override
public void onClick(View view) {
    switch (view.getId()){

//Retourner au Log normal, ceci est le bouton retour
        case R.id.returnButton:

         startActivity(new Intent(this, LoginActivity.class));

            break;

//Ceci est le bouton get started, il confirme le formulaire
            case R.id.doneRegister:

          doneReg();

            break;
    }
 }
}

这是profileRegistration.java

 import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.storage.FirebaseStorage;
 import com.google.firebase.storage.StorageReference;
 import com.google.firebase.storage.UploadTask;

 import java.io.IOException;

 public class profileRegistration extends AppCompatActivity {

private static final int CHOOSE_IMAGE = 101;
ImageView pictureSelect;
EditText pseudoRegister;
Button saveProfil;

Uri uriProfileImage;
//ProgressBar progressBarImage;

String profileImageUrl;
FirebaseAuth mAuth;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile_registration);
    mAuth = FirebaseAuth.getInstance();

    pictureSelect = (ImageView) findViewById(R.id.pictureSelect);
    pseudoRegister = (EditText) findViewById(R.id.pseudoRegister);
    //progressBarImage = (ProgressBar) findViewById(R.id.progressBarImage);
    saveProfil = (Button) findViewById(R.id.saveProfile);


    //Dans ce OnClick on va appeler la méthode Action_GET_CONTENT
    pictureSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showImageChooser();
        }
    });


    findViewById(R.id.saveProfile).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveUserInformations();
        }

        });

    Intent intent = new Intent(profileRegistration.this,  LoginActivity.class);
    startActivity(intent);
}

@Override
protected void onStart() {
    super.onStart();
    if (mAuth.getCurrentUser() == null) {
        finish();
        startActivity(new Intent(this, menuPrincipal.class));
    }
}



//Method pour enregistrer les info quand on clique sur DoneRegister
private void saveUserInformations() {

    String displayName = pseudoRegister.getText().toString();

    if(displayName.isEmpty()){
        pseudoRegister.setError("Pseudo is required");
        pseudoRegister.requestFocus();
        return;
    }

    FirebaseUser user = mAuth.getCurrentUser();

    if(user!=null && profileImageUrl!=null){
        UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
                .setDisplayName(displayName)
                .setPhotoUri(Uri.parse(profileImageUrl))
                .build();

        user.updateProfile(profile)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if(task.isSuccessful()) {
                            Toast.makeText(profileRegistration.this, "Profile is done", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
 }

 //Clic droit, generate, override, Method to override to get the image from the chooserImage
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
        uriProfileImage = data.getData();

        //Now we can select the image and display it
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
            pictureSelect.setImageBitmap(bitmap);

            //Commande pour créer  la méthode pour stocker dans Firebase
            uploadImageToFirebaseStorage();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  }


  //On va mettre la photo dans le cloud de Firebase
    private void uploadImageToFirebaseStorage(){
        StorageReference profilImageRef = FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");

        if (uriProfileImage != null) {
            //progressBarImage.setVisibility(View.VISIBLE);
            profilImageRef.putFile(uriProfileImage)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            //progressBarImage.setVisibility(View.GONE);
                            profileImageUrl = taskSnapshot.getDownloadUrl().toString();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            //progressBarImage.setVisibility(View.GONE);
                            Toast.makeText(profileRegistration.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
        }


    }

//Méthode pour la selection de la photo
private void showImageChooser() {

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"Select Profile Image"), CHOOSE_IMAGE);
 }

 }

我还是新手,所以如果问题非常明显而我没有看到,我很抱歉。提前谢谢!

1 个答案:

答案 0 :(得分:0)

您的注册应为:

auth.createUserWithEmailAndPassword(email, password)
                        .addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);

profileRegistration中,您应该致电LoginActivity

@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBarImage.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.getDownloadUrl().toString();
}

您需要添加

Intent intent = new Intent(profileRegistration.this,  LoginActivity.class);
                            startActivity(intent); 

LoginActivity 应该是

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Get Firebase auth instance
        auth = FirebaseAuth.getInstance();

        if (auth.getCurrentUser() != null) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        // set the view now
        setContentView(R.layout.activity_login);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        inputEmail = (EditText) findViewById(R.id.emailLogin);
        inputPassword = (EditText) findViewById(R.id.passwordLogin);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        btnSignup = (Button) findViewById(R.id.signUp);
        btnLogin = (Button) findViewById(R.id.logNow);

        //Get Firebase auth instance
        auth = FirebaseAuth.getInstance();

        btnSignup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegistrationActivity.class));
            }
        });

        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = inputEmail.getText().toString();
                final String password = inputPassword.getText().toString();

                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                    return;
                }

                progressBar.setVisibility(View.VISIBLE);

                //authenticate user
                auth.signInWithEmailAndPassword(email, password)
                        .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                progressBar.setVisibility(View.GONE);
                                if (!task.isSuccessful()) {
                                    // there was an error
                                    if (password.length() < 6) {
                                        inputPassword.setError(getString(R.string.minimum_password));
                                    } else {
                                        Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
                                    }
                                } else {
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        });
            }
        });
    }
}