I am trying to write data with setValue() to firebase database, but it throws NullPointerException. I have no idea what can cause NullPointerException with this method, so i am asking for help. Here is the error:
Exception in thread "Thread-24" java.lang.NullPointerException
at com.example.maxgm.myapplication.backend.EnergyBar$1$2.onComplete(EnergyBar.java:81)
at com.google.firebase.database.core.Repo$6.run(Repo.java:329)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at com.google.appengine.tools.development.BackgroundThreadFactory$1$1.run(BackgroundThreadFactory.java:60)
Here is my code:
@Override
public void onDataChange(DataSnapshot snapshot)
{
if (snapshot.exists())
{
for (DataSnapshot childSnap : snapshot.getChildren()) {
if (childSnap.child("Character").exists()) {
int energyCurrent;
int energyMax;
int energyObtain;
energyCurrent = (int) (long) childSnap.child("Character").child("energyCurrent").getValue();
energyMax = (int) (long) childSnap.child("Character").child("energyMax").getValue();
energyObtain = (int) (long) childSnap.child("Character").child("energyObtain").getValue();
float finalEnergy = energyCurrent + (energyMax * (energyObtain / 100));
if (finalEnergy > energyMax) {
childSnap.getRef().child("Character").child("energyCurrent").setValue(energyMax, new DatabaseReference.CompletionListener() {
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
throw databaseError.toException();
}
});
} else {
childSnap.getRef().child("Character").child("energyCurrent").setValue((int) finalEnergy, new DatabaseReference.CompletionListener() {
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
throw databaseError.toException();
}
});
}
}
}
}
}