Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Failed to convert value of type java.lang.Long to String – Android Studio – Firebase Realtime Database

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading