gpt4 book ai didi

java - 身份验证 firebase 在注销后记住我

转载 作者:行者123 更新时间:2023-11-30 05:11:22 26 4
gpt4 key购买 nike

我在 MainActivity 中输入我的主要 Activity ,我已经注册,在注册成功后我想从 firebase 注销,这样他就不会记得我了。

因为当我在注销后返回到 MainActivity 时,当我注册为新用户时,他仍然记得以前的用户。这仅在登录并立即注销后发生。顺便说一句,如果我运行该应用程序,它工作正常。只有当我注销然后转到 RegistrationActivity 注册另一个用户时才会出现问题。

这是 MainActivity 代码:

public class MainActivity extends AppCompatActivity {

private SignInButton signIn;

private int RC_SIGN_IN=1;
private GoogleSignInClient mGoogleSignInClient;
private String TAG = "MainActivity";
private FirebaseAuth mAuth;

private Button registration;

private EditText email;
private EditText password;
private Button login;

private BottomNavigationView bottomNavigationItemView;

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

signIn = (SignInButton)findViewById(R.id.sign_in_button);

mAuth = FirebaseAuth.getInstance();

registration = (Button) findViewById(R.id.registrate);
email = (EditText)findViewById(R.id.email);
password = (EditText)findViewById(R.id.password);
login = (Button)findViewById(R.id.login);


bottomNavigationItemView = (BottomNavigationView)findViewById(R.id.navB) ;
bottomNavigationItemView.getMenu().getItem(0).setChecked(true);


bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.register_menu: {

Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
break;
}
}
return true;
}
});



GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();

mGoogleSignInClient = GoogleSignIn.getClient(this, gso);



signIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});


registration.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
}
});



login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

String email_text = email.getText().toString().trim();
String password_text = password.getText().toString().trim();

if(TextUtils.isEmpty(email_text) || TextUtils.isEmpty(password_text))
{
Toast.makeText(MainActivity.this, "One or more fields are empty", Toast.LENGTH_LONG).show();
}
else
{
mAuth.signInWithEmailAndPassword(email_text, password_text).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {

if(!task.isSuccessful())
{
Toast.makeText(MainActivity.this, "Sign in problem", Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent(MainActivity.this, AccountActivity.class);
startActivity(intent);
}
}
});
}

}
});


}


private void signIn() { /*Sign in to the app with Google Account*/
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);


}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try{
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
}
catch(ApiException e){

Log.w(TAG, "Google Sin in Failed");
}
}
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct)
{
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
@Override
public void onComplete(@NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
Log.d(TAG, "signInWithCredential: success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
}
else
{
Log.w(TAG, "signInWithCredential: failure", task.getException()); /*In case of unsuccessful login*/
Toast.makeText(MainActivity.this, "You are not able to log in to Google", Toast.LENGTH_LONG).show();
//updateUI(null);
}
}
});


}

private void updateUI(FirebaseUser user) /*In case of successful registration*/
{

GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (acct != null) {
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
Toast.makeText(this, "Name of User : " + personName + "UserId is : " + personId, Toast.LENGTH_LONG);


Intent intent = new Intent(this, AccountActivity.class);
intent.putExtra("personPhoto", personPhoto.toString());
startActivity(intent);
}
}

这是 AccountActivity 代码:

public class AccountActivity extends AppCompatActivity {

private GoogleSignInClient mGoogleSignInClient;


private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;


private CardView signOut;
private CardView ratingTable;
private CardView settings;
private CardView map;
private CardView favoritePlaces;

DatabaseReference databaseReference;
FirebaseDatabase database;
List<User> users;

CollapsingToolbarLayout collapsingToolbarLayout;


String photoString="No photo";


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


mAuth = FirebaseAuth.getInstance();


signOut = (CardView) findViewById(R.id.logout);
ratingTable = (CardView) findViewById(R.id.rating);
settings = (CardView)findViewById(R.id.settings);
map = (CardView) findViewById(R.id.map);
favoritePlaces = (CardView)findViewById(R.id.favorite);



database = FirebaseDatabase.getInstance();
databaseReference = database.getReference();
users = new ArrayList<User>();

collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collaps);




if(mAuth.getCurrentUser().getDisplayName()!=null)
{
Intent i = getIntent();
photoString = i.getStringExtra("personPhoto");
}



databaseReference.child("user").addValueEventListener(new ValueEventListener() { /*A new user is registered in the database*/
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot child : children) {
User user = child.getValue(User.class);
users.add(user);
}

if (!findUser()) /*If the user is not found, this is a new user and must be registered*/
addUser();
showName(); /*A user-specific message*/
}


@Override
public void onCancelled(DatabaseError databaseError) {

}
});


GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);




signOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

if(mAuth.getCurrentUser().getDisplayName()!=null)
{
mGoogleSignInClient.signOut();
//Intent intent = new Intent(AccountActivity.this, MainActivity.class);
// startActivity(intent);
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);


}
else
{
mAuth.signOut();
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
});



settings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, SettingsActivity.class);
startActivity(intent);
}
});

map.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, MapsActivity.class);
startActivity(intent);
}
});

favoritePlaces.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, favoritePlacesActivity.class);
startActivity(intent);
}
});

ratingTable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, RatingTableActivity.class);
startActivity(intent);

}
});


}




private void showName() /*A user-specific message*/
{
String name = "";
String userId = mAuth.getUid();
for (User tmpUser : users) {
if (userId.equals(tmpUser.getUserId()))
{
name = tmpUser.getUserName();
break;
}
}
collapsingToolbarLayout.setTitle("Hi " + name);
}



private boolean findUser() /*Check if a logged-on user is already registered in the database*/
{

FirebaseUser user = mAuth.getCurrentUser();
String userId = mAuth.getUid();



for (User tmpUser : users) {
if (userId.equals(tmpUser.getUserId())) {
return true;
}
}
return false;

}

private void addUser() /*In case of registration from Google Account*/
{
String userId = mAuth.getUid();
if(mAuth.getCurrentUser().getDisplayName()!=null) /*In case of registration not from Google Account*/
{
databaseReference = FirebaseDatabase.getInstance().getReference("user");
FirebaseUser user = mAuth.getCurrentUser();
String userName = user.getDisplayName();
User newUser = User.getInstance(userId, userName, photoString);
databaseReference.child(userId).setValue(newUser);
}

else /*If the user is not registered the function registers it in the database*/
{
databaseReference = FirebaseDatabase.getInstance().getReference("user");
Intent i = getIntent();
String firstName = i.getStringExtra("firstName");
String lastName = i.getStringExtra("lastName");


User newUser = User.getInstance(userId, firstName + " " + lastName, photoString);
databaseReference.child(userId).setValue(newUser);
}

}

RegistrationActivity代码:

public class RegistrationActivity extends AppCompatActivity {

EditText email_text;
EditText pass1;
EditText pass2;
EditText first;
EditText last;
Button registrate;

FirebaseAuth mAuth;
private ProgressDialog progressDialog;



private BottomNavigationView bottomNavigationItemView;

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

mAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);

email_text = (EditText)findViewById(R.id.email);
pass1 = (EditText)findViewById(R.id.password1);
pass2 = (EditText)findViewById(R.id.password2);
first = (EditText)findViewById(R.id.first_name);
last = (EditText)findViewById(R.id.last_name);
registrate = (Button)findViewById(R.id.registrate);




bottomNavigationItemView = (BottomNavigationView)findViewById(R.id.navB) ;

bottomNavigationItemView.getMenu().getItem(1).setChecked(true);



bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.Signin_menu: {

Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
break;
}
}
return true;
}
});


registrate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

final String email = email_text.getText().toString().trim();
String password1 = pass1.getText().toString().trim();
String password2 = pass2.getText().toString().trim();
final String first_name = first.getText().toString().trim();
final String last_name = last.getText().toString().trim();
boolean correctFlag=true;

/*All tests for input integrity*/
if(!password1.equals(password2))
{
Toast.makeText(RegistrationActivity.this, "The password does not match", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(password1.equals("") && password2.equals(""))
{
Toast.makeText(RegistrationActivity.this, "No password entered", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(email.equals("") || first_name.equals("") || last_name.equals(""))
{
Toast.makeText(RegistrationActivity.this, "One or more of the parameters are incorrect", Toast.LENGTH_LONG).show();
correctFlag=false;
}

if(correctFlag) /*There is no problem filling the fields*/
{
progressDialog.setMessage("Registrating user...");
progressDialog.show();

mAuth.createUserWithEmailAndPassword(email, password1).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {

if(task.isSuccessful())
{
Toast.makeText(RegistrationActivity.this, "Registered Succesfully", Toast.LENGTH_SHORT).show();
progressDialog.cancel();
Intent intent = new Intent(RegistrationActivity.this, AccountActivity.class);
intent.putExtra("firstName", first_name);
intent.putExtra("lastName", last_name);
startActivity(intent);
}
else
{
Toast.makeText(RegistrationActivity.this, "could not register. please try again", Toast.LENGTH_SHORT).show();
progressDialog.cancel();
}
}
});
}
}
});
}

最佳答案

您需要退出 GoogleSignInClient :

   public void signOut() {
signOutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(getContext(), gso);
mGoogleSignInClient.signOut();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getContext(), LoginActivity.class));
}
});
}

关于java - 身份验证 firebase 在注销后记住我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53686285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com