Firebase does not save data

Asked

Viewed 577 times

0

so I’m having a little problem and I can’t solve it for studies I’m creating an app already famous and my doubt is the following when registering a user your name and email are not recorded in the database follows Excerpt of all 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;
    }
}

1 answer

0


Whoa, that’s all right!?

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

Soon after I call a function to record the data in the database (so I saw you do not give the setValue, maybe this is it).

Follow the code (firebase is already started on 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 call the function to save the data(note in setValue, it saves the data in 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();
}

Browser other questions tagged

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