我对android开发还很陌生,正在尝试用firebase开发应用程序。我用个人资料照片注册,并将照片名称输入数据库。归档到firestore。在底部代码 mImageUrls.add(uri.toString());
线路不通。但在onsuccess()中会产生toast,只是我不能将数据添加到数组中。我在oncreateview中初始化了数组( final ArrayList<String> mImageUrls = new ArrayList<>();
)和其他数组一样。我需要你的帮助。
lv = (ListView) rootview.findViewById(R.id.lv_main);
final ArrayAdapter adapter = new MyAdapter(getActivity(), name_list,date,imgs);
myref = FirebaseDatabase.getInstance().getReference().child("MusiciansNonSensitive");
final ArrayList<String> mImageUrls = new ArrayList<>();
final StorageReference storageReference = FirebaseStorage.getInstance().getReference();
myref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
String name_value = postSnapshot.child("name").getValue().toString();
String province_value = postSnapshot.child("province").getValue().toString();
final String url_path = postSnapshot.child("photourl").getValue().toString();
StorageReference photo_url = storageReference.child("uploads/"+url_path);
photo_url.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
mImageUrls.add(uri.toString()); // I tried to add Log.d and it adds value every for loop, but after loop it being empty array again.
}
});
//mImageUrls.add("A");
name_list.add(name_value);
date.add(province_value);
}
Log.d("LOGGOGOGOOG",mImageUrls.toString()); // Here being empty
//Toast.makeText(getContext(),list.toString(),Toast.LENGTH_LONG).show();
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
1条答案
按热度按时间hjqgdpho1#
addOnSuccessListener
异步并立即返回。回调会在一段时间后调用,即使在循环完成并调用setAdapter
. 您将不得不重写代码,以便仅在异步获取所有url之后设置适配器。您可以使用Tasks.whenAll()
获取在您提供的任务列表完全完成后将完成的新任务。