gpt4 book ai didi

java - Firebase Datasnapshot 返回空值

转载 作者:行者123 更新时间:2023-12-01 16:28:41 24 4
gpt4 key购买 nike

我想从这个节点(“id”)检索这个值,并且我得到的值为null。我在谷歌上搜索了很多解决方案,我猜这可能与异步方式或其他方式有关?

这是数据库,突出显示的节点是我想要获取的值:

This is the database, and the highlighted node is the value i would like to get

这是我的代码:

            reference = FirebaseDatabase.getInstance().getReference();
id = null;
Query lastQuery = reference.child("Donation Request").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.child("id").exists())
{
id = dataSnapshot.child("id").getValue().toString();
int index = Integer.parseInt(id) + 1;
id = Integer.toString(index);
Toast.makeText(getApplicationContext(), "It works!!!", Toast.LENGTH_SHORT).show();
}
else
{
id = "1";
Toast.makeText(getApplicationContext(), "It doesn't work.", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
{

}
});

如果有人能帮助我解决这个问题,我将不胜感激!

最佳答案

当您对 Firebase 数据库执行查询时,可能会出现多个结果。因此快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。

您的 onDataChange 需要通过循环 dataSnapshot.getChildren()) 来处理此列表:

reference = FirebaseDatabase.getInstance().getReference();
id = null;
Query lastQuery = reference.child("Donation Request").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
if (snapshot.hasChild("id"))
{
id = snapshot.child("id").getValue(String.class);
int index = Integer.parseInt(id) + 1;
id = Integer.toString(index);
Toast.makeText(getApplicationContext(), "It works!!!", Toast.LENGTH_SHORT).show();
}
else
{
id = "1";
Toast.makeText(getApplicationContext(), "It doesn't work.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
{
throw databaseError.toException(); // never ignore errors.
}
});

还有一些注意事项:

  • 任何 id 的使用都需要在 onDataChange 内部进行,或者从那里调用。除此之外,您无法保证 id 会被分配您期望的值。
  • 使用 toast 进行调试必然会变得困惑。我强烈建议使用 Log.d(...) 和 friend ,并研究应用程序的 logcat 输出中的输出(及其顺序)。

关于java - Firebase Datasnapshot 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62097658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com