Can't read data from Database Firebase using class

I'm very new on Stackoverflow an even newer on programing.

I'm creating an app to Android with firebase auth and firebase realtime database. Auth is ok, and i'm writing data with a class very well.

The problem is to read data by my class1, its retur nothing on my text view. Where am I wrong ?

I saw lots of post of people having the same trouble but I could'n found any error on my program.

The ondatachange toast is working and when I try to read data fron my http url i can read just the first child.

MainActivity.java:

insira o código aquipackage 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() {...}

}

classe1.java witch I use to write data and I'd like to read from:

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;}

} tks

Upvotes: 0

Views: 730

Answers (2)

Thanks for the help @GastónSaillén, @AlexMamo, @KostasPoime. Fortunately I fixed my code taking the @JuniaMontana's example. Now this code can write and read parameters of a class and after pressing a button show a textview all the children and its atributes. The next step is to download a txt file whit that info, but its not implemented yet.

Here is the code working properly.

    public class MainActivity extends AppCompatActivity {

    // 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



    //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
        this.mDatabaseRef1 = FirebaseDatabase.getInstance().getReference().child("cadastros"); // cria um filho ao objeto de referencia e atualiza o referencial
       // mDatabaseRef1.child(uId).setValue("value1");

        // AUTENTICAÇÃO inicia o listener do estado da autenticação
        mAuthStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {// informa se o usuario está autenticado no momento
                FirebaseUser user = firebaseAuth.getCurrentUser(); //cria a variavel user para armazenar o status conectado ou desconectado
                if (user != null) {// usuario está autenticado
                    // Toast.makeText(MainActivity.this, "You're now signed in.", Toast.LENGTH_SHORT).show();
                }
                else { // usuario nao esta autenticado
                    startActivityForResult(
                            AuthUI.getInstance()// inicia a activity de login gerada automaticamente pelo firebase
                                    .createSignInIntentBuilder()
                                    .setIsSmartLockEnabled(false)
                                    .setAvailableProviders(Arrays.asList(
                                            new AuthUI.IdpConfig.EmailBuilder().build(),
                                            new AuthUI.IdpConfig.GoogleBuilder().build()
                                            //new AuthUI.IdpConfig.FacebookBuilder().build(),
                                            //new AuthUI.IdpConfig.TwitterBuilder().build(),
                                            //new AuthUI.IdpConfig.GitHubBuilder().build(),
                                            //new AuthUI.IdpConfig.PhoneBuilder().build(),
                                            //new AuthUI.IdpConfig.AnonymousBuilder().build()
                                    ))
                                    .build(),
                            RC_SIGN_IN //bandeira
                    );
                }
            }
        };

        //LER DATABASE

        //lets initialize the valueEventListener
        this.mValueEventListener = getClasse1Information();

        //now lets attach the valueEventListener
        this.mDatabaseRef1.addValueEventListener(mValueEventListener);
    }

    //Now, lets create the method getClasse1Information() which will return ValueEventListener
    // MÉTODO PARA RECEBER DADOS DO FIREBASE USANDO A classe1
    private ValueEventListener getClasse1Information(){

        atualizaRef1();//atualiza a mDatabaseRef1

        return mValueEventListener = new ValueEventListener() {

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


                //now we'll have to iterate over the data on the firebase
                for(DataSnapshot snapshot: dataSnapshot.getChildren()){

                    if(snapshot != null){
                        // call your class here and register it
                        classe1 cla = snapshot.getValue(classe1.class);

                        // now just show the value
                        if(cla != null) {
                            String cmp1 = cla.getCampo1();
                            String cmp2 = cla.getCampo2();
                            String cmp3 = cla.getCampo3();

                            TextView t = (TextView)findViewById(R.id.textView2);
                            t.append("cmp1: " + cmp1 + ", cmp2: " + cmp2 + ", cmp3: " + cmp3);
                            t.append("\n");
                            t.append("\n");
                            //t.setText(cmp1 + cmp2 + cmp3);
                            //Toast.makeText(MainActivity.this, "cmp1: " + cmp1 + ",cmp2: " + cmp2 + ",cmp3: " + cmp3, Toast.LENGTH_SHORT).show();
                        }
                    }
                }


            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        };
    }


    // MÉTODO PARA FAZER LOGOUT DDA AUTENTICAÇÃO

    public void fsignOut(View view) {

        AuthUI.getInstance()
                .signOut(this)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    public void onComplete(@NonNull Task<Void> task) {
                    }
                });
    }
    // MÉTODO PARA ENVIAR DADOS AO FIREBASE USANDO A classe1

    public void enviardata(View view) {

        atualizaRef1();//atualiza a mDatabaseRef1

        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);
        //mDatabaseRef1.child("filho").setValue(cla);

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

    // MÉTODO PARA ATUALIZAR A mDatabaseRef1 CRIANDO CHILD COM ID DO USUARIO
    public void atualizaRef1(){
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        String uNome = user.getDisplayName();
        String uId = user.getUid();
        String uEmail = user.getEmail();// email não funciona não sei por que
        mDatabaseRef1 = FirebaseDatabase.getInstance().getReference().child("cadastros").child(uId);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mFirebaseAuth.removeAuthStateListener(mAuthStateListener); // remove o listener da autenticação
    }

    @Override
    protected void onResume() {
        super.onResume();
        mFirebaseAuth.addAuthStateListener(mAuthStateListener); // adiciona o listener da autenticação
    }
}

my class is the same:

    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 filho1,String filho2,String filho3) {
        this.campo1 = filho1;
        this.campo2 = filho2;
        this.campo3 = filho3;
    }

    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;}
}

Print of my Firebase database:

Upvotes: 1

Junia Montana
Junia Montana

Reputation: 623

I highly recommend you to read firebase docs. However, check below to see how to read data from firebase and get basic knowledge on how to get started with Firebase Database:

  1. When you have created a class say Post, and provided class variable say,

    String postId; String post; String userEmail; String userImage; String datePosted;

Now in your firebase database you have to make sure that you have constructed your database with same variables for e.g :

-user_post(database_name)
 -key(userEmail)
   postId:"someId"
   post:"some posts"
   datePosted:"some date"
   userImage:"userImage url"

Okay! You get the point. Now to fetch data All you have to do create a reference of DatabaseReference and ValueEventListener in your mainActivity/fragment. Check out code to understand how it works:

inside your MainActivity/fragment:

    private DatabaseReference databaseRef;
    private ValueEvenetListener valueEventListener;
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState){
           
        // initializing the databaseRef by hooking it up with the Firebase database.
        // Note: if you are using user's email as key to your database, make sure
        // you encode the email.
        this.databaseRef = FirebaseDatabase.getInstance().getReference()
        .child(DATABASE_NAME).child(DATABASE_KEY);
    
        //lets initialize the valueEventListener
        this.valueEventListener = getPostInformation(); 
    
        //now lets attach the valueEventListener
        this.databaseRef.addValueEventListener(valueEventListener);

}

//Now, lets create the method getPostInformation() which will return ValueEventListener
    
private ValueEventListener getPostInformation(){
    
     return new ValueEventListener(){
       
       @Override
       public void onDataChanged(@Nullable DataSnapshot dataSnapshot){
       
       //now we'll have to iterate over the data on the firebase
       // you've missed this part in your code
       //so
       for(DataSnapshot snapshot: dataSnapshot.getChildren()){
     
           if(snapshot != null){
            
            // call your class here and register it 
            Post post = snapshot.getValue(Post.class);
            
            // now just show the value
            if(post != null){

            String id = post.getId();
            String userEmail = post.getUserEmail();
            String userImage = post.getUserImage();
            String date = post.getDatePosted();
           
            Toast.makeText(getActivity(), "Id: " + id + ",Email: " + userEmail + ",Image:  " + userImage + ", Date: " + date, Toast.LENGTH_SHORT).show();;
           
             }
           }
         }
       }
    }
 }

Upvotes: 0

Related Questions