Firebase database resets data when logo

1

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

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

First login:

Clickthebutton:

Secondsign-in:

WhatwouldIhavetochangeatthetimeofloggingin?

publicclassMainActivityextendsAppCompatActivity{FirebaseAuthauth;FirebaseUserfireuser;DatabaseReferencerootReference;GoogleSignInClientmGoogleSignInClient;SignInButtongbutton;protectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);auth=FirebaseAuth.getInstance();rootReference=FirebaseDatabase.getInstance().getReference();gbutton=(SignInButton)findViewById(R.id.btnGoogle);GoogleSignInOptionsgso=newGoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();mGoogleSignInClient=GoogleSignIn.getClient(this,gso);gbutton.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){IntentsignInIntent=mGoogleSignInClient.getSignInIntent();startActivityForResult(signInIntent,101);}});}privatevoidfirebaseAuthWithGoogle(GoogleSignInAccountaccount){AuthCredentialcredential=GoogleAuthProvider.getCredential(account.getIdToken(),null);auth.signInWithCredential(credential).addOnCompleteListener(this,newOnCompleteListener<AuthResult>(){@OverridepublicvoidonComplete(@NonNullTask<AuthResult>task){if(task.isSuccessful()){//Signinsuccess,updateUIwiththesigned-inuser'sinformationfireuser=auth.getCurrentUser();UsermyUserInsertObj=newUser(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  {

                }
            }
        }
    }
    
asked by anonymous 09.05.2018 / 05:01

1 answer

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

You are using this line right after logging in with the firebase, you are creating a new object, not retrieving 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();
                                }
                            }
                     });
    
09.05.2018 / 20:44