Data is loaded from Firebase asynchronously. By the time you call formatter.parse(datebp)
the onDataChange
method hasn't run yet, and datebp
hasn't been set. You will need to move the parsing of the data into onDataChange
:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("bpfragmentTable");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<BPFragmentTable> bpfragmentTableList = new ArrayList<>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
BPFragmentTable bpfragmentTable = dataSnapshot1.getValue(BPFragmentTable.class);
systolic = bpfragmentTable.getSystolicbp();
diastolic = bpfragmentTable.getDiastolicbp();
date = bpfragmentTable.getDatebp();
time = bpfragmentTable.getTimebp();
bpfragmentTableList.add(bpfragmentTable);
System.out.println( "systolicbp" + systolicbp );
System.out.println( "diastolicbp" + diastolicbp );
System.out.println( "datebp" + datebp );
System.out.println( "timebp" + timebp );
try {
@SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a\nMMM dd yyyy");
dateValued = formatter.parse(datebp);
dateInMills = dateValued.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
This asynchronous nature is a common pitfall for developers new to Firebase. Since asynchronous APIs are extremely common in modern programming, I highly recommend you learn about them quickly. For some good introductory material, see:
- getContactsFromFirebase() method return an empty list (which also shows how to use an interface to get the values out of
onDataChange
)
- this blog post on asynchronous APIs
- Setting Singleton property value in Firebase Listener (where I explained how in some cases you can get synchronous data loading, but usually can't)