Reputation: 742
So I am trying to initiaze each calendar cell with a color that is based on some info on my firebase database and for that I use a flag which is set as false and then it becomes true if the conditions are met. The thing is that the addListenerForSingleValueEvent is an async method so the flag returns all the time as false. How should I handle it?
mCalendar.addDecorator(new DayViewDecorator() {
@Override
public boolean shouldDecorate(final CalendarDay day) {
final boolean[] flag = {false};
final String currentDate = day.getCalendar().get(Calendar.YEAR)
+ "" + day.getCalendar().get(Calendar.MONTH)
+ "" + day.getCalendar().get(Calendar.DAY_OF_MONTH);
database.child(currentDate).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
flag[0] = true;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return flag[0];
}
@Override
public void decorate(DayViewFacade view) {
view.addSpan(new ForegroundColorSpan(
ContextCompat.getColor(getApplicationContext(), R.color.material_red_a200)));
}
});
Upvotes: 0
Views: 664
Reputation: 138824
To solve this, move the declaration of your boolean[] flag
array inside the onDataChange()
method, otherwise it will be always null.
public void onDataChange(DataSnapshot snapshot) {
final boolean[] flag = {false};
if (snapshot.exists()) {
flag[0] = true;
}
Log.d("TAG", flag[0]);
}
This is happening due the asynchronous behaviour of onDataChange()
method, which is called before even you are trying to get the value from that array.
Moving the declaration inside the method and using it also there, solves your problem.
If you want to use the value of that array outside that method, please take a look at my answer from this post, How To Get Async Value Outside onDataChange() Method.
Upvotes: 1