Firebase does not save data

0

So I'm having a problem and I can not solve it in order to study. I'm creating an already famous app and my doubt is the following when registering a user. Your name and email are not saved in the database. all the codes for this function:

registration page:

package com.example.bruno.organizze.Activity;

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

import com.example.bruno.organizze.Helper.Base64Custom;
import com.example.bruno.organizze.R;
import com.example.bruno.organizze.config.ConfigFirebase;
import com.example.bruno.organizze.model.User;
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.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseAuthWeakPasswordException;

public class CadastroActivity extends AppCompatActivity {

//atributos btn´s e campos

private Button btnCadastrar;
private EditText editNome, editEmail, editSenha;
private FirebaseAuth autentica;
private User user;


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

    btnCadastrar = findViewById(R.id.btnCadastrar);
    editEmail = findViewById(R.id.editEmail);
    editNome = findViewById(R.id.editNome);
    editSenha = findViewById(R.id.editSenha);


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

            cad();

        }
    });

}

public void cadastrarUsuario() {

    autentica = ConfigFirebase.getFirebaseAutenticacao();
    autentica.createUserWithEmailAndPassword(user.getEmail(), user.getSenha()
    ).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {

                String idUsuario = Base64Custom.codificarBase64(user.getEmail());
                user.setIdUsuario(idUsuario);
                user.salvar();


                telaPrincipal();

            } else {

                String exc = " ";

                try {
                    throw task.getException();
                } catch (FirebaseAuthWeakPasswordException e) {
                    exc = "Digite uma senha mais forte";
                } catch (FirebaseAuthInvalidCredentialsException e) {
                    exc = "Por favor digite um email valido";
                } catch (FirebaseAuthUserCollisionException e) {
                    exc = "Conta já cadastrada";
                } catch (Exception e) {
                    exc = "Erro ao cadastrar " + e.getMessage();
                    e.printStackTrace();
                }


                Toast.makeText(CadastroActivity.this, exc, Toast.LENGTH_LONG).show();
            }
        }
    });

}

public void cad() {


    //Strings campos
    String textNome = editNome.getText().toString();
    String textEmail = editEmail.getText().toString();
    String textSenha = editSenha.getText().toString();

    //validar os campos

    if (!textNome.isEmpty()) {
    } else {
        Toast.makeText(CadastroActivity.this, "Preencha o nome", Toast.LENGTH_LONG).show();
    }
    if (!textEmail.isEmpty()) {

    } else {
        Toast.makeText(CadastroActivity.this, "Preencha o campo E-mail", Toast.LENGTH_LONG).show();
    }

    if (!textSenha.isEmpty()) {

        user = new User();
        user.setNome(textEmail);
        user.setEmail(textEmail);
        user.setSenha(textSenha);
        cadastrarUsuario();


    } else {
        Toast.makeText(CadastroActivity.this, "Preencha o campo senha", Toast.LENGTH_LONG).show();
    }
}

public void telaPrincipal() {
    startActivity(new Intent(this, PrincipalActivity.class));
    finish();
}


parte onde trata toda a referencia do db

    package com.example.bruno.organizze.config;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class ConfigFirebase {
    private  static  DatabaseReference firebase;
    private static FirebaseAuth auth;


    //retorna a instancia do FirebaseDatabase
    public static DatabaseReference getFirebaseReference(){
        if ( firebase == null ){
            firebase = FirebaseDatabase.getInstance().getReference();
        }
        return firebase;
    }



    public static FirebaseAuth getFirebaseAutenticacao(){

        if (auth == null ) {
            auth = FirebaseAuth.getInstance();
        }
        return auth;
    }

}


classe para manipulação:

package com.example.bruno.organizze.model;

import com.example.bruno.organizze.config.ConfigFirebase;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.Exclude;

public class User {
    private String idUsuario;
    private String nome;
    private String email;
    private String senha;


    public User() {
    }



    public void salvar(){
        DatabaseReference firebase = ConfigFirebase.getFirebaseReference();
        firebase.child("usuarios")
                .child( this.idUsuario )
                .push(this);
    }



    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Exclude
    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    @Exclude
    public String getIdUsuario() {
        return idUsuario;
    }

    public void setIdUsuario(String idUsuario) {
        this.idUsuario = idUsuario;
    }
}
    
asked by anonymous 24.12.2018 / 20:54

1 answer

2

Oops, all right!?

My logic was as follows, I create the user with the firebase function: createUserWithEmailAndPassword

Then I call a function to save the data in the database (so I saw you do not setValue, maybe that's it).

Follow the code (the firebase is already started in my onCreate):

//criar eleitor
mAuth.createUserWithEmailAndPassword(mEmail, mSenha)
        .addOnCompleteListener(CadastroEleitorActivity.this, new OnCompleteListener<AuthResult>() {
            @SuppressLint("RestrictedApi")
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                // If sign in fails, display a message to the mUser. If sign in succeeds
                // the mAuth state listener will be notified and logic to handle the
                // signed in mUser can be handled in the listener.
                if (task.isSuccessful()) {
                    mID = mAuth.getUid();
                    if (myBitmap != null) {
                        mEleitorModel.setNome(txtNome.getText().toString() + " "+ txtSobrenome.getText().toString());
                        mEleitorModel.setEmail(txtEmailCadastro.getText().toString());
                        uploadImagem(myBitmap, txtNome.getText().toString().trim());
                    }
                    else {
                        mEleitorModel.setDataCadastro(mDataHora);
                        gravarNovoEleitor(mID, txtNome.getText().toString().trim(), mEmail, mDataHora);
                    }
                }
                else {
                    mProgressDialog.dismiss();
                    if (task.getException().getLocalizedMessage().contains("The email address is already in use by another account.")) {
                        android.support.v7.app.AlertDialog.Builder alertaLogin = new android.support.v7.app.AlertDialog.Builder(CadastroEleitorActivity.this);
                        alertaLogin.setMessage("Este email já consta em nosso cadastro, efetue o Login ou Relembre sua mSenha.")
                                .setTitle("Atenção")
                                .setNeutralButton("Relembrar Senha", new DialogInterface.OnClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i)
                                    {
                                        Intent intent = new Intent(CadastroEleitorActivity.this, AlterarSenhaActivity.class);
                                        startActivity(intent);
                                    }
                                })
                                .setPositiveButton("Login", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                        Intent intent = new Intent(CadastroEleitorActivity.this, LoginActivity.class);
                                        startActivity(intent);
                                    }
                                });
                        alertaLogin.setCancelable(false);
                        alertaLogin.show();
                    }
                }
            }
        });

In case of success I call the function to save the data (note in the setValue, it saves the data in the firebase):

private void gravarNovoEleitor(String userId, String nome, String email, String dataCadastro) {
    mEleitorModel.setId(userId);
    mEleitorModel.setNome(nome);
    mEleitorModel.setEmail(email);
    mEleitorModel.setDataCadastro(dataCadastro);

    mDatabase
            .child("eleitores")
            .child(userId)
            .setValue(mEleitorModel);
    mProgressDialog.dismiss();

    Intent intent = new Intent(this, PrincipalActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
}
    
03.01.2019 / 19:34