Home > Net >  Failed to convert value of type java.lang.Long to String - Android Studio - Firebase Realtime Databa
Failed to convert value of type java.lang.Long to String - Android Studio - Firebase Realtime Databa

Time:02-04

I'm coding a Tic Tac Toe, and while executing it crashes when I tried to read a value from the database.

I'm getting the following error:

com.google.firebase.database.DatabaseException: Failed to convert value of type java.lang.Long to String

The line where it crashes is the following : canPlay = Long.parseLong(snapshot.getValue(String.class));

The function is the following:

refPeutJouer.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        peutjouer = Long.parseLong(snapshot.getValue(String.class));
    }

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

The variable is declared as private long peutjouer at the beginning of the class. I have declared the DatabaseReference as follows: private DatabaseReference refPeutJouer = database.getReference("peutJouer");

Here is a screenshot of the Firebase database:

Screenshot of the Database

I tried to switch from an int to a long, but that didn't change anything.

CodePudding user response:

The peutJouer property in the screenshot you shared is a numeric value. The code you use to read it however does:

snapshot.getValue(String.class)

Since the snapshot does not have a String value, you can't retrieve it like that.

Instead, you'll want to extract is with:

peutjouer = snapshot.getValue(Long.class);
  • Related