Firebase database reset data when soon

Asked

Viewed 67 times

1

I was studying Firebase and created a login method with email and password, but I did not want to use this, so I learned to use Google Auth, so I decided to associate the google auth account in the database.

When already with the account, it opens another Activity, in it has a button in which I wanted to add the time, I use the same method I used to "create the account" in the database, when I soon in the app, all data is reset. (Edit) I put a counter to see, and it also resets, just log back into the app.

First login:

Primeiro login

Click on the button:

Cliquei no botão

Second login:

Segundo login

What I would have to change when logging in?

   public class MainActivity extends AppCompatActivity {
        FirebaseAuth auth;
        FirebaseUser fireuser;
        DatabaseReference rootReference;
        GoogleSignInClient mGoogleSignInClient;
        SignInButton gbutton;

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

        auth = FirebaseAuth.getInstance();

        rootReference = FirebaseDatabase.getInstance().getReference();

        gbutton = (SignInButton)findViewById(R.id.btnGoogle);

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

        mGoogleSignInClient = GoogleSignIn.getClient(this,gso);


            gbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent signInIntent = mGoogleSignInClient.getSignInIntent();
                startActivityForResult(signInIntent, 101);
            }
        });

    }

        private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
            AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
            auth.signInWithCredential(credential)
                    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {

                            if (task.isSuccessful()) {
                                // Sign in success, update UI with the signed-in user's information
                                fireuser = auth.getCurrentUser();

                                User myUserInsertObj = new User(fireuser.getEmail());

                                rootReference.child("User").child(fireuser.getUid()).setValue(myUserInsertObj)
                                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if(task.isSuccessful()){
                                                    Toast.makeText(getApplicationContext(),"User logged in successfully!", Toast.LENGTH_SHORT).show();

                                                    Intent i = new Intent(getApplicationContext(),Logado.class);
                                                    startActivity(i);
                                                    finish();
                                                } else {
                                                    Toast.makeText(getApplicationContext(),"Error logging in with Google Auth.", Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        });

                            } else {
                                // If sign in fails, display a message to the user.
                                Toast.makeText(getApplicationContext(), "Could not log in user", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
            if (requestCode == 101) {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                if (result.isSuccess()) {
                    // Google Sign In was successful, authenticate with Firebase
                    GoogleSignInAccount account = result.getSignInAccount();
                    firebaseAuthWithGoogle(account);
                } else  {

                }
            }
        }
    }

1 answer

2


User myUserInsertObj = new User(fireuser.getEmail());

You are using this line right after login with firebase, you are creating a new object, not recovering one from the server.

fireuser = auth.getCurrentUser();
rootReference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            User tempUser;
            // Listar todos os usuário salvos
            List<User> users = new ArrayList<>();
            for (DataSnapshot child : dataSnapshot.getChildren()) {
                users.add(child.getValue(User.class));
            }

            // Faça um loop nessa lista para procurar o usuário cujo id corresponde ao id do FirebaseUser recém logado e associe-o
            for (User user : users) {
                if (user.getUid().equals(fireuser.getUid())) {
                    tempUser = user; // Aqui está o nosso usuário
                }
            }

            // Criar a instância de user correspondente
            // Se tempUser continuar nulo, crie um novo usando o construtor, se não, use-o como está
            User myUserInsertObj = tempUser == null 
                ? new User(fireuser.getEmail()) // Provavelmente o primeiro login desse usuário
                : tempUser;

             rootReference.child("User").child(fireuser.getUid()).setValue(myUserInsertObj)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if(task.isSuccessful()){
                                    Toast.makeText(getApplicationContext(),"User logged in successfully!", Toast.LENGTH_SHORT).show();

                                    Intent i = new Intent(getApplicationContext(),Logado.class);
                                    startActivity(i);
                                    finish();
                                } else {
                                    Toast.makeText(getApplicationContext(),"Error logging in with Google Auth.", Toast.LENGTH_SHORT).show();
                                }
                            }
                     });
  • Perfect, I had used another solution, but it was a "gambiarra", this was the one I wanted. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.