gpt4 book ai didi

java - 无法从 Firebase 数据库接收数据

转载 作者:行者123 更新时间:2023-12-02 10:35:13 25 4
gpt4 key购买 nike

为了简短起见。当我想从 Firebase 数据库接收数据时,应用程序崩溃。这是代码:

database = FirebaseDatabase.getInstance();
commu = database.getReference("Community");

longi = voteLoni.getText().toString();
lati = voteLati.getText().toString();
final String latiLong = lati + " - " + longi;

commu.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Community")
.child(latiLong);

ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
count= dataSnapshot.child("count").getValue(long.class);
....

结构:社区的 child 是协调

DB
- Community
- 89.8 - 90.9
- count: 4
- example: 2
- example2: 4
- example3: 8
- 120.9 - 89.9
- count: 45
- example: 24
- example2: 40
- example3: 81

这就是错误:

Process: package, PID: 21441
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at app.Activity.Real$2$1.onDataChange(Real.java:122)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@16.0.3:183)
at com.google.firebase.database.obfuscated.zzap.zza(com.google.firebase:firebase-database@@16.0.3:75)
at com.google.firebase.database.obfuscated.zzca.zza(com.google.firebase:firebase-database@@16.0.3:63)
at com.google.firebase.database.obfuscated.zzcd$1.run(com.google.firebase:firebase-database@@16.0.3:55)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:251)
at android.app.ActivityThread.main(ActivityThread.java:6589)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

但在另一项 Activity 中我使用相同的代码 count= dataSnapshot.child("count").getValue(long.class); - 计算用户的点击次数 - 它正在工作......

提前致谢

编辑:我已将第二个子项和一些值添加到数据库中。 DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Community").child(latiLong);也被编辑了,但这不正确?

最佳答案

无需编写嵌套监听器..

如果你有这样的结构:

DB
- Community
- 1
- count: 4

并且您无权访问子1,则只需执行以下操作:

database = FirebaseDatabase.getInstance();
commu = database.getReference("Community");

commu.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
count= ds.child("count").getValue(Long.class);
}
}
.....

这将检索count的值

关于java - 无法从 Firebase 数据库接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53343157/

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