Reputation: 1200
I have defined new json object and array.
private JSONArray array = new JSONArray();
private JSONObject obj = new JSONObject();
Then i tried to fetch some data form firebase in loop and tried to put it in the defined json object and that object in defined json array. below is my code
for(int i = 1; i < 13; i++){
String str = Integer.toString(i);
mRef.child("calendar").child(str).child("start_date").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
start_date = dataSnapshot.getValue().toString();
try {
obj.put("start_date", start_date);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("start_date", start_date);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mRef.child("calendar").child(str).child("end_date").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
end_date = dataSnapshot.getValue().toString();
try {
obj.put("end_date", end_date);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.d("obje", "" + obj);
array.put(obj);
}
Log.d("arrary", "" + array);
But when I log my array or object it shows empty. Below is a log of json object of a single loop. D/obje: {} and this is my array after loop. D/arrary: [{},{},{},{},{},{},{},{},{},{},{},{}]
But when I log my object inside onDataChange class it logs data. but when I log at the end of loop it shows empty.
And this is log of start date to show that data is comming from firebase D/start_date: 09/17/2016
Upvotes: 2
Views: 3557
Reputation: 11642
The problem is you are trying to get the value from the asynchronous callback. You're for loop will end before you get the callback from asynchronous request so it's showing empty.
Try like this,
for(int i = 1; i < 13; i++){
String str = Integer.toString(i);
mRef.child("calendar").child(str).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String start_date = (String) dataSnapshot.child("start_date").getValue();
String end_date = (String) dataSnapshot.child("end_date").getValue();
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("start_date", start_date);
jsonObject.put("end_date", end_date);
Log.d("obje", "" + jsonObject);
array.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("start_date", start_date);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Upvotes: 1