在Firebase上創建數據後。我嘗試從Firebase中檢索數據。但我有問題,我想可能是Log.d(TAG,list.size())在ref.addChildEventListener(childEventListener)之前運行;完成。誰能幫我 ?在Firebase中回撥android
public class NewFirebase extends AppCompatActivity {
List <Product> list = new ArrayList < >();
private static final String TAG = "Firebase";
DatabaseReference ref;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
ref = FirebaseDatabase.getInstance().getReference();
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
Product comment = dataSnapshot.getValue(Product.class);
for (DataSnapshot child: dataSnapshot.getChildren()) {
Product post = child.getValue(Product.class);
list.add(post);
}
// ...
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
}
};
ref.addChildEventListener(childEventListener);
Log.d(TAG, list.size() + "");
}
class RetrievingData extends AsyncTask < Void, Void, Void > {
@Override
protected Void doInBackground(Void...voids) {
return null;
}
}
}
是'Log.d(TAG,則爲list.size())REF之前運行。 addChildEventListener(childEventListener);完成「,但你想要什麼下一步 –
該數據異步加載,所以它可能需要一段時間,纔可用於您的應用程序的代碼。您現在還不能返回*尚未加載的內容。有關異步行爲的一個很好的解釋,請參閱此問答:http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –
我想ref.addChildEventListener(childEventListener );在Log.d(TAG,list.size())之前完成運行。 – TungLoGach