Listeners from firebase database does not run and does not retrieve data, write - java server desktop

Asked

Viewed 171 times

0

There are a few days I’m trying to understand what is happening with my code that I should write and read in Firebase Realtime Database, but without success and there is no apparent problem, error, exception or any kind of problem to hint at what is going on. I am coding in native Java, used the guidelines of firebase admin page, it is not for Android as virtually all occurrences in my searches return a lot. I made a code also for Android the same operation using the same database and worked perfectly, so I can not understand why it is going wrong and I am consuming a lot of time and energy in this and unsuccessful, if anyone can help, I would really appreciate!!

As in Android is perfectly possible to read and write data, I dismissed the possibility of the problem being in the database. I am following the instructions available on the page of Firebase Admin, as said before, and also there is no error algumn, but also no result. With the same configuration and the json file with the key obtained from Firebase console, is working properly with Firebase Cloud Messaging, I considered that the key is also correct, besides having no error while running the code and I can still recover given by DatabaseReference ref = FirebaseDatabase.getInstance().getReference().

The code is the one that follows below, almost the same as the Firebase page:

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.io.FileInputStream;
import java.io.IOException;

class StarterFRD {

    public static void main(String[] args) throws IOException {

        FileInputStream refreshToken = new FileInputStream("/Users/wdcunha/Development/Java/frdproj/src/main/resources/housecontrolmobile-firebase-adminsdk-qv0hl-f41a07409d.json");

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(refreshToken))
                .setDatabaseUrl("https://housecontrolmobile.firebaseio.com/")
                .build();

        FirebaseApp.initializeApp(options);

     // As an admin, the app has access to read and write all data, regardless of Security Rules
        DatabaseReference ref = FirebaseDatabase.getInstance()
                .getReference("users");

        System.out.println("ref: "+ref);

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Object document = dataSnapshot.getValue();
                System.out.println("document: "+document);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                System.out.println("canceled: "+error.toException());
            }
        });

        Utilizador utilz = new Utilizador("Euquipe", "[email protected]");

        System.out.println("utilz nome: "+utilz.getNome());
        System.out.println("utilz email: "+utilz.getEmail());

        ref.child("2").push().setValueAsync(utilz);

        ref.child("3").setValue("I'm writing data", new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                if (databaseError != null) {
                    System.out.println("Data could not be saved " + databaseError.getMessage());
                } else {
                    System.out.println("Data saved successfully."+databaseReference);
                }
            }
        });
    }
}

{ base de dados (json) esta (link aqui).

If anyone can help with this question, I really appreciate it, because I couldn’t find anything that could shed any light on this problem.

2 answers

0

He’s giving you a List You’re taking it as if it were a single object! has to make a go

for(DataSnapshot snap : dataSnapShot.getValues()){
    Usuario user = snap.getValue(Usuario.class); // Classe usuario tem que estar igual aos dados do firebase, no caso ali email e nome, e adiciona aos dados ali o id tambem
} 

id email name

when writing to Realtime, write the id also to the data.

  • although the problem was what I reported above, thank you for the suggestion Daniel Sampaio!

0


The problem was not being logged in as a server. He was running the code and when he reached the end of it, he was shut down, so there was no time to get the firebase response. When I then put your execution on a server, I was able to see the answer I needed. Simple, but it took me a lot of precious time. If someone goes through the same, remember that this is an asynchronous command and also that depend on the connection and will not be returned immediately, so you need to keep the code running.

Browser other questions tagged

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