Firebase Database Android does not recover data by class

Asked

Viewed 222 times

1

I’m creating an app Android with authentication and database by Firebase, authentication is working and I can write data through a class normally.

My problem is that when reading the class data does not return me anything in mine TextView. I wonder where I’m going wrong?

I saw several posts similar to mine but it seems that each case is a case and I did not identify anything wrong in my code. Inclusive o toast of onDataChange works and if I try to read the data directly by http address instead of class until I can read the first Child.

mine MainActivity.java:

package com.chruscinski.teste6;  
import...  
public class MainActivity extends AppCompatActivity {



    // classes e atributos AUTENTICAÇÃO
    private FirebaseAuth mFirebaseAuth; // instancia a classe firebaseauth (cria objeto/variável do mesmo tipo da classe)
    private FirebaseAuth.AuthStateListener mAuthStateListener;// cria objeto/variável para armazenar o estado do listener da autenticação
    public static final int RC_SIGN_IN = 1;//bandeira, não entendi direito como funciona isso ainda

    //classes e atributos DATABASE
    private FirebaseDatabase mFirebaseDatabase; //cria um objeto da classe FirebaseDatabaseAPI -> é o ponto de aceso do aplicativo ao database -> instancia
    private DatabaseReference mDatabaseRef1; // cria um objeto de referencia do database da classe DatabaseReferenceAPI-> é o endereço, a referencia do Database
    private ValueEventListener mValueEventListener;

        // >>>>>>>>>>>>>>>ONCREATE<<<<<<<<<<<<<<<<<
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //AUTENTICAÇÃO
        mFirebaseAuth = FirebaseAuth.getInstance();// inicia o objeto mFirebaseAuth

        //DATABASE
        mFirebaseDatabase = FirebaseDatabase.getInstance();//jeito mais longo em 2 linhas
        mDatabaseRef1 = mFirebaseDatabase.getReference().child("cadastros");// faz referencia a uma parte específica do database
        //mDatabaseRef1 = FirebaseDatabase.getInstance().getReference().child("cadastros"); // cria um filho ao objeto de referencia e atualiza o referencial

        //AUTENTICAÇÃO inicia o listener do estado da autenticação
        mAuthStateListener = new FirebaseAuth.AuthStateListener() {...}

        //LER DADOS DATABASE
        mValueEventListener = new ValueEventListener() {

            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        TextView t = (TextView)findViewById(R.id.textView2);    
        classe1 cla = dataSnapshot.getValue(classe1.class);

                t.setText(cla.getCampo1());

                Toast.makeText(MainActivity.this, "ON DATA CHANGE",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(MainActivity.this, "ERRO.",Toast.LENGTH_SHORT).show();
            }
        };
        mDatabaseRef1.addValueEventListener(mValueEventListener);
    }

    // MÉTODO PARA FAZER LOGOUT DDA AUTENTICAÇÃO
    public void fsignOut(View view) {...}

    // MÉTODO PARA ENVIAR DADOS AO FIREBASE USANDO A classe1
    public void enviardata(View view) {

        EditText edt1 = findViewById(R.id.edt1);
        EditText edt2 = findViewById(R.id.edt2);
        EditText edt3 = findViewById(R.id.edt3);

        String sedt1 = edt1.getText().toString();
        String sedt2 = edt2.getText().toString();
        String sedt3 = edt3.getText().toString();

        classe1 cla = new classe1(sedt1, sedt2, sedt3);
        mDatabaseRef1.push().setValue(cla);

        Toast.makeText(MainActivity.this, "SUCESSO", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {...}

    @Override
    protected void onResume() {...}
}

mine classe1.java what use to record data and would like to read data from it:

package com.chruscinski.teste6; 
import... com.google.firebase.database.IgnoreExtraProperties; 

@IgnoreExtraProperties 
public class classe1 {

    public String campo1;
    public String campo2;
    public String campo3;

    public classe1() {
        // Default constructor required for calls to DataSnapshot.getValue(com.chruscinski.teste6.User.class)
    }

    public classe1(String campo1,String campo2,String campo3) {
        this.campo1 = campo1;
        this.campo2 = campo2;
        this.campo3 = campo3;
    }

    public String getCampo1() {return campo1;}
    public void setCampo1(String campo1) {this.campo1 = campo1;}
    public String getCampo2() {return campo2;}
    public void setCampo2(String campo2) {this.campo2 = campo2;}
    public String getCampo3() {return campo3;}
    public void setCampo3(String campo3) {this.campo3 = campo3;}
}
  • 1

    Asked in the right place, the Meta is to address community-related issues as a whole, rule issues, those things, but the programming issues should be posted right here.

1 answer

0


Oops, good morning. blah!?

check on the following line

classe1 cla = dataSnapshot.getValue(classe1.class);

You are taking all the firebase snapshot, the correct would be to put the patch you want, look how I did:

DataSnapshot snapshot;
snapshot = dataSnapshot.child("eleitores").child(mID);
EleitorModel mEleitorModel = snapshot.getValue(EleitorModel.class);

Specify the exact path of your snapshot that you will take in this;

A tip, if you look at class names, a good practice for class names is to be Camelcase.

Hugs!

Browser other questions tagged

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