How to get Firebase data and insert it into a Textview?

Asked

Viewed 3,128 times

4

I need to set the client data in a Textview. I tried to set the email, but it didn’t work because 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) {

            }
        };
    }
}

inserir a descrição da imagem aqui

  • "String.valueOf(dataSnapshot.getValue())" returns some value?

  • Does not return no

  • Show your class Configuracaofirebase, pf

  • https://pastebin.com/HYT8dBps

5 answers

2

The problem that dataSnapshot is returning null is that its Databasereference is not correct. That is, there is no data to be collected in this path passed to Databasereference.

For each level of data 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;
    }

} 

That way, you just call DataSnapshot.getValue(Usuario.class) within the 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 searching for references.

  • I’m taking null inter on that part

  • .Child("users"). Child("clients"). Child(usuario.getUid())

  • Check whether the usuario was instantiated correctly. And put the error Stacktrace if possible.

1

If you just 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 form of programming is not the best. You should have a Java class with email attributes, name, have, phone, etc and should automatically read them at once. It would be something like that:

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 later on textview you would only need to make a getEmail to your class.

Take a look at this example.

  • did not work no , the text some , ta returning null value

  • @Paiva but you can already get the value of the email?

  • No it returns no value

0

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

I hope this solution will help you.

0

Look friend.... Maybe the error is at the time of Instantiating the class that stores the Firebase data.

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

public class Usuario {

private string id; private string email; private string password; private string name; private string cpfCnpj Private String telephone; private string address; int private 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 "User user = new User()" to record data coming from Firebase.

Then you go to Activity2 and there you want to set the "Email" saved in the User class".

To do this, you instantiate again the class "User user = new User(); and apply no to your textView the value of the "User class email" >> textView.setText(user.getEmail)

If that is your case, perhaps the error lies there!

When you instantiate the User class in Activity2 again, the values stored in the Strings and int disappear and with that your textView will appear empty.

To solve this problem, because I faced the same problem, I did so in my User class:

public class Usuario {

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 addressee; private Static int credit;

// > See that here I add my Strings and the int the "Static". // > This causes the values applied to it not to be lost regardless of how many times I instate my User 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;
}

}

// Getters and setters should remain as listed below without change. Even if Strings and int are 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

You only created the instance of the User object, but did not initialize its attributes, so uid returns null. Boot user uid with Firebaseuth 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) {

            }
        };
    }
}
  • Changes nothing in textview =/

  • you put the / after-the-way customers? on Child there

  • Yes, I copied and pasted

  • https://pastebin.com/HYT8dBps

  • How are your Realtime Database security rules?

  • You are allowed to read and record

Show 1 more comment

Browser other questions tagged

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