How to get data from Firebase and insert it into a TextView?

I need to define the client data in a TextView. I tried setting the email but it didn't work as the return is null.

public class PerfilActivity extends AppCompatActivity {
    private TextView tv_email;
    private FirebaseAuth auth;
    private Usuario usuario = new Usuario();
    private DatabaseReference firebaseDatabase;
    private ValueEventListener valueEventListener;

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

        tv_email = findViewById(R.id.tv_email_perfil);
        auth = FirebaseAuth.getInstance();

        firebaseDatabase = ConfiguracaoFirebase.getFirebaseDatabase()
                .child("usuarios/clientes"+ usuario.getUid()+ "/email");

        valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                tv_email.setText(String.valueOf(dataSnapshot.getValue()));
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
    }
}

insert the description of the image here

Author: Amelco, 2017-12-16

5 answers

The problem with dataSnapshot being returning null is that its DatabaseReference is not correct. That is, there is no data to be collected on this path passed to the DatabaseReference.

For each data level you need to call the .child() again.

Change Your DatabaseReference to this structure:

firebaseDatabase = ConfiguracaoFirebase.getFirebaseDatabase()
.child("usuarios").child("clientes").child(usuario.getUid())

In addition, it is recommended that you create a template class for your data in Firebase.

For example:

@IgnoreExtraProperties
public class Usuario {

private String id;
private String email;
private String senha;
private String nome;
private String cpfCnpj
private String telefone;
private String endereco;
private int credito;

    public Usuario() {
        // Construtor obrigatório para as chamadas do DataSnapshot.getValue(Usuario.class)
    }

    public Usuario(String id, String email, String senha, String nome, String cpfCnpj, String telefone, String endereco, int credito) {
        this.id = id;
        this.email = email;
        this.senha = senha;
        this.nome = nome;
        this.cpfCnpj = cpfCnpj;
        this.telefone = telefone;
        this.endereco = endereco, 
        this.credito = credito;
    }

} 

Form, just call DataSnapshot.getValue(Usuario.class) inside ValueEventListener() and you will have the user object with the data already loaded from Firebase.


I recommend reading the documentation of the Realtime Database for reference search.

 3
Author: Amelco, 2017-12-20 23:35:25

If you only want to get the value of the email, you should do:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("usuarios");
DatabaseReference clientesref = ref.child("clientes");
DatabaseReference email = clientesref.child("email");

However, this way of programming is not the best. You should have a Java class with the attributes email, name, have, phone, etc. and you should automatically read them at once. It would be something like this:

valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.hasChildren()) {
                <classe criada por ti> a = dataSnapshot.getValue(<classe criada por ti>.class);

                filldata(a.getEmail());
    }
}

public void filldata(String email){
    TextView a = (TextView) findViewforId(R.id.email);

    a.setText(email);

}

Where then in textview you would only need to make a getEmail to your class.

Take a look at this example.

 2
Author: porthfind, 2017-12-17 12:34:12

I believe the fault is here private Usuario usuario = new Usuario();, you instantiate the object with all its attributes null and then try to capture an attribute from it, however it will be null, so your request is calling "usuarios/null/email". To fix this you will need to feed the user UId.

I hope this solution helps you.

 0
Author: Guilherme Montanher, 2017-12-22 16:14:18

You only created the instance of the user object, but did not initialize its attributes, so the uid returns null. Initialize the user's uid with the firebaseauth uid:

public class PerfilActivity extends AppCompatActivity {
    private TextView tv_email;
    private FirebaseAuth auth;
    private Usuario usuario = new Usuario();
    private DatabaseReference firebaseDatabase;
    private ValueEventListener valueEventListener;

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

        tv_email = findViewById(R.id.tv_email_perfil);
        auth = FirebaseAuth.getInstance();

        usuario.setUid(auth.getCurrentUser().getUid());

        firebaseDatabase = ConfiguracaoFirebase.getFirebaseDatabase()
                .child("usuarios/clientes/"+ usuario.getUid()+ "/email");

        valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                tv_email.setText(dataSnapshot.getValue(String.class));
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
    }
}
 0
Author: Rosário Pereira Fernandes, 2017-12-25 14:44:39

Look friend.... Perhaps the error is in the hour of instantiating the class that stores the Firebase data.

Example: Imagine that you have the following class as in the answer above:

Public class User {

Private string id; private string email; private string password; private String name; private string cpfCnpj private string phone; private String endereco; private int credit;

public Usuario() {

}

public Usuario(String id, String email, String senha, String nome, String cpfCnpj, String telefone, String endereco, int credito) {
    this.id = id;
    this.email = email;
    this.senha = senha;
    this.nome = nome;
    this.cpfCnpj = cpfCnpj;
    this.telefone = telefone;
    this.endereco = endereco, 
    this.credito = credito;
}

}

/ / with their respective geters and seters

Imagine that you are in Activity1 and in it you call "Usuario user = New Usuario ()" to write the data coming from Firebase.

Then you go to Activity2 and there you want to set the "Email" recorded in the Usuario class".

To do this, you re-instantiate the class "Usuario user = New Usuario(); and apply the value of the "usuario class Email" >> textView to your textView.setText (user.getEmail)

If this is your case, the error may be found ai!

When you re-instantiate the Usuario class in Activity2, the values stored in the Strings and int add up and with that your textView will appear empty.

To solve this problem, not least because I faced the same problem, was to do so in my Usuario Class:

Public class User {

Private static string id; private static string email; private static string password; private static string name; private static string cpfCnpj private static String phone; private static String endereco; private static int credit;

/ / > See that here I add my Strings and to the int the "static". // > This makes the values applied to it not get lost regardless of how many times I instantiate my Usuario class. // > The value will only change if you change it manually.

public Usuario() {

}

public Usuario(String id, String email, String senha, String nome, String cpfCnpj, String telefone, String endereco, int credito) {
    this.id = id;
    this.email = email;
    this.senha = senha;
    this.nome = nome;
    this.cpfCnpj = cpfCnpj;
    this.telefone = telefone;
    this.endereco = endereco, 
    this.credito = credito;
}

}

/ / The getters and setters must remain as listed below unchanged. Even if the Strings and the int be as static:

Public string getId() { return id; }

public void setId(String id) {
    this.id = id;
}

public String getEmail() {
    return email;
}

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

public String getSenha() {
    return senha;
}

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

public String getNome() {
    return nome;
}

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

public String getCpfCnpj() {
    return cpfCnpj;
}

public void setCpfCnpj(String cpfCnpj) {
    this.cpfCnpj = cpfCnpj;
}

public String getTelefone() {
    return telefone;
}

public void setTelefone(String telefone) {
    this.telefone = telefone;
}

public String getEndereco() {
    return endereco;
}

public void setEndereco(String endereco) {
    this.endereco = endereco;
}

public int getCredito() {
    return credito;
}

public void setCredito(int credito) {
    this.credito = credito;
}
 0
Author: Andre Alas, 2019-03-13 22:04:37