我向 Firebase 数据库发出两个请求,然后将数据加载到 XML 中。但它不会加载它们,只是保留默认值,我怀疑这是因为我没有正确处理异步请求。有人可以帮助我吗?
@Override
public View getInfoWindow(@NonNull Marker marker) {
if (!(marker.getTitle().toString().equals("Este es mi perfil"))){
View infoView = LayoutInflater.from(context).inflate(R.layout.custom_info,null);
title_mod = infoView.findViewById(R.id.title_mod);
snipp_mod = infoView.findViewById(R.id.snipp_mod);
imagen_mod = infoView.findViewById(R.id.imagen_mod);
LatLng posicionMarker = marker.getPosition();
String idLocation = String.valueOf(posicionMarker.latitude).replace(".","") + "_" + String.valueOf(posicionMarker.longitude).replace(".","");
DataHandler dataHandler = new DataHandler();
databaseReference = FirebaseDatabase.getInstance().getReference("chismesinfo");
databaseReference.child(idLocation).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
descripcion = snapshot.child("descripcion").getValue(String.class);
user = snapshot.child("user").getValue(String.class);
firstOperation.complete(null);
usersReference = FirebaseDatabase.getInstance().getReference("users");
usersReference.child(user).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
username = snapshot.child("name").getValue(String.class);
if (snapshot.hasChild("profile")) {
foto = snapshot.child("profile").getValue(String.class);
} else {
foto = null;
}
secondOperation.complete(null);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
// Manejar errores si es necesario
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
if (foto != null) {
byte[] imageAsByte = Base64.decode(foto.getBytes(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(imageAsByte, 0, imageAsByte.length);
imagen_mod.setImageBitmap(bitmap);
}
title_mod.setText(username);
snipp_mod.setText(descripcion);
return infoView;
}
我原本希望数据直接加载到界面,但我只是默认获取文本。但是,我第二次触发该事件时,它确实加载了数据。
您对 setText 的调用是同步发生的,但您的网络请求是异步的(因为它们需要如此)。这意味着 setText 将在网络请求之前发生。您需要在 onDataChanged 函数中调用 setText,或者如果发生在主线程之外,则需要在 onDataChanged 中对主线程的调用中调用 setText。