Firebase用户在重新启动应用程序时获得null。

huangapple go评论67阅读模式
英文:

firebase user getting null on restart of application

问题

public class Authentication extends AppCompatActivity {
    private TextInputLayout e1;
    private TextInputLayout e2;
    private TextInputEditText e21;
    private String email;
    private String password;
    private ProgressDialog progress;
    private FirebaseAuth auth;
    private FirebaseUser user;
    private String user_id;
    private String value;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_authentication);
        e1 = (TextInputLayout) findViewById(R.id.email);
        e2 = (TextInputLayout) findViewById(R.id.password);
        e21 = (TextInputEditText) findViewById(R.id.password_ed);
        e21.addTextChangedListener(new TextWatcher() {
            // TextWatcher methods...
        });
        auth = FirebaseAuth.getInstance();
        progress = new ProgressDialog(this);
        progress.setMessage("Signing In...");
        progress.setCanceledOnTouchOutside(false);
        progress.setCancelable(false);
    }

    public void login(View view) {
        // login method...
    }

    private void login_user(final String email, String password) {
        // login_user method...
    }

    private void showCustomDialog_error() {
        // showCustomDialog_error method...
    }

    private void showCustomDialog_tick() {
        // showCustomDialog_tick method...
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (user != null) {
            Intent intent = new Intent(this, Info.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        }
    }
}

Your Firebase user might be getting null after app restart because the user variable is declared as a class member but is not being initialized in the onStart() method. The onStart() method is called when the activity is starting or returning to the foreground, but in your provided code, I don't see where you initialize the user variable inside the onStart() method.

If you want to ensure that the user is not null after app restart, you need to handle user authentication and the retrieval of the currently authenticated user inside the onStart() method. This might involve using Firebase's authentication state listener (auth.addAuthStateListener()) to update the user variable when the authentication state changes.

Since your issue seems to involve debugging the onStart() and authentication logic, consider checking the following:

  1. Make sure that you have the necessary Firebase authentication configuration set up properly in your project.
  2. Implement the authentication state listener to update the user variable based on authentication state changes.
  3. Double-check the logic inside your login_user() method and ensure that it's correctly updating the user variable after a successful login.

If you've tried the onAuthStateChangeListener and it's not working as expected, double-check the implementation and the timing of when it's added and removed. Also, ensure that the listener is being registered before the authentication is attempted and that the listener's callback is updating the user variable appropriately.

For a comprehensive understanding of why your user might be null after app restart, consider referring to the Firebase Authentication documentation and debugging resources.

英文:
public class Authentication extends AppCompatActivity {
private TextInputLayout e1;
private TextInputLayout e2;
private TextInputEditText e21;
private String email;
private String password;
private ProgressDialog progress;
private FirebaseAuth auth;
private FirebaseUser user;
private String user_id;
private String value;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authentication);
e1=(TextInputLayout) findViewById(R.id.email);
e2=(TextInputLayout) findViewById(R.id.password);
e21=(TextInputEditText) findViewById(R.id.password_ed);
e21.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() > e2.getCounterMaxLength())
e2.setError("Max character length is " + e2.getCounterMaxLength());
else
e2.setError(null);
}
});
auth = FirebaseAuth.getInstance();
progress = new ProgressDialog(this);
progress.setMessage("Signing In...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
}
public void login(View view){
email = e1.getEditText().getText().toString();
password = e2.getEditText().getText().toString();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
Toast.makeText(this, "Empty Credentials", Toast.LENGTH_LONG).show();
} else if (password.length() < 8) {
Toast.makeText(this, "Password Must Be Of Length 8", Toast.LENGTH_LONG).show();
}
else{
login_user(email, password);
progress.show();
}
}
private void login_user(final String email, String password) {
auth.signInWithEmailAndPassword(email, password).addOnSuccessListener(Authentication.this, new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
user= FirebaseAuth.getInstance().getCurrentUser();
if(user.isEmailVerified()){
user_id = user.getUid();
Toast.makeText(Authentication.this,"Login Sucessfully",Toast.LENGTH_SHORT).show();
progress.dismiss();
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference().child(user_id).child("Information");
dbref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
value= dataSnapshot.getValue(String.class);
}
@Override
public void onCancelled(DatabaseError error) {
}
});
}
else{
showCustomDialog_error();
progress.dismiss();
}
}
});
auth.signInWithEmailAndPassword(email, password).addOnFailureListener(Authentication.this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(Authentication.this,"Invalid Credentials",Toast.LENGTH_SHORT).show();
progress.dismiss();
}
});
}
private void showCustomDialog_error() {
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView = LayoutInflater.from(this).inflate(R.layout.error_custom, viewGroup, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
Button bt= (Button) dialogView.findViewById(R.id.buttoncancel);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
Toast.makeText(Authentication.this,"Email Not Verified",Toast.LENGTH_SHORT).show();
e1.getEditText().setText(null);
e2.getEditText().setText(null);
FirebaseAuth.getInstance().signOut();
}
});
Button bt2= (Button) dialogView.findViewById(R.id.buttonsent);
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
user.sendEmailVerification();
showCustomDialog_tick();
}
});
}
private void showCustomDialog_tick() {
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView = LayoutInflater.from(this).inflate(R.layout.tick_custom, viewGroup, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
TextView tv=(TextView)dialogView.findViewById(R.id.customtv);
tv.setText(getResources().getString(R.string.verification_email_sent_successfully));
TextView tv2=(TextView)dialogView.findViewById(R.id.customtv1);
tv2.setText(getResources().getString(R.string.verify_email_and_then_login_again));
Button bt = (Button) dialogView.findViewById(R.id.buttonOk);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
e1.getEditText().setText(null);
e2.getEditText().setText(null);
FirebaseAuth.getInstance().signOut();
}
});
Button bt1 = (Button) dialogView.findViewById(R.id.buttonsent);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
user.sendEmailVerification();
showCustomDialog_tick();
}
});
}
}
@Override
protected void onStart() {
super.onStart();
if (user != null) {
Intent intent = new Intent(this,Info.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
}

my firebase user is getting null after app restart
i.e. onStart method is not working
explain me why my user is getting null after the successfull login and then restarting the application.
i have also tried onAuthStatechangeLitsner but its not working..
it is still get my user null.
i have tried many of the approaches debug the code and search in a logcat too but same issue

答案1

得分: 1

登录后,FirebaseAuth.getInstance().getCurrentUser() 可能尚未设置。因此,您需要从传递给完成处理程序的 AuthResult 参数中获取用户:

auth.signInWithEmailAndPassword(email, password).addOnSuccessListener(Authentication.this, new OnSuccessListener<AuthResult>() {
    @Override
    public void onSuccess(AuthResult authResult) {
        user = authResult.getUser();
        if (user.isEmailVerified()) {
            ...
英文:

After signing in, the FirebaseAuth.getInstance().getCurrentUser() may not be set yet. For this reason, you need to get the user from the AuthResult parameter that is passed to your completion handler:

auth.signInWithEmailAndPassword(email, password).addOnSuccessListener(Authentication.this, new OnSuccessListener&lt;AuthResult&gt;() {
@Override
public void onSuccess(AuthResult authResult) {
user= authResult.getUser();
if(user.isEmailVerified()){
...

huangapple
  • 本文由 发表于 2020年10月25日 21:48:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64524433.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定