如何从Firestore中检索地图中的数据

huangapple go评论88阅读模式
英文:

How to retrieve the data from firestore in maps

问题

以下是您提供的代码的翻译部分:

有没有办法从Firestore中检索地图中的数据 我正在尝试但它返回null
这是我的代码

docRef = db.collection("Buses").document("Bus1");
Button btn=view.findViewById(R.id.submit);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                bus=documentSnapshot.getData();
            }
        });
        if (!bus.get("ID").toString().matches(busId)) {
            DocumentReference reference = db.collection("Buses").document("Bus2");
            reference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                @Override
                public void onSuccess(DocumentSnapshot documentSnapshot) {
                    bus=documentSnapshot.getData();
                }
            });
        }
        if (bus!=null){
            Toast.makeText(getContext(), "数据读取成功", Toast.LENGTH_SHORT).show();
            Intent intent=new Intent(getContext(),MapsActivity.class);
            startActivity(intent);

            CONSTANTS.bus=HomeFragment.this.bus;
            getActivity().finishAffinity();
        }
        else{
            Toast.makeText(getContext(), "数据读取失败", Toast.LENGTH_SHORT).show();
        }

    }
});

但我在这里得到了NullPointerException错误
这是数据库的截图

如何从Firestore中检索地图中的数据

我不明白为什么getdata函数返回null
这是错误日志

java.lang.NullPointerException: 尝试在空对象引用上调用接口方法 'java.lang.Object java.util.Map.get(java.lang.Object)'
at 
com.integratedsoftsols.fyp.bustracking.user.HomeFragment$1.onClick(HomeFragment.java:53)
at android.view.View.performClick(View.java:6274)
at android.view.View$PerformClick.run(View.java:24859)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6710)
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:770)
英文:

Is there any way to retrieve the data from firestore in Maps. I am trying but its returning null
here is my code

docRef = db.collection(&quot;Buses&quot;).document(&quot;Bus1&quot;);
Button btn=view.findViewById(R.id.submit);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
docRef.get().addOnSuccessListener(new OnSuccessListener&lt;DocumentSnapshot&gt;() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
bus=documentSnapshot.getData();
}
});
if (!bus.get(&quot;ID&quot;).toString().matches(busId)) {
DocumentReference reference = db.collection(&quot;Buses&quot;).document(&quot;Bus2&quot;);
reference.get().addOnSuccessListener(new OnSuccessListener&lt;DocumentSnapshot&gt;() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
bus=documentSnapshot.getData();
}
});
}
if (bus!=null){
Toast.makeText(getContext(), &quot;Data read Successfully&quot;, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(getContext(),MapsActivity.class);
startActivity(intent);
CONSTANTS.bus=HomeFragment.this.bus;
getActivity().finishAffinity();
}
else{
Toast.makeText(getContext(), &quot;Data read Failed&quot;, Toast.LENGTH_SHORT).show();
}
}
});

But I am getting NullPointerException here
Here is the screenshot of the database

**如何从Firestore中检索地图中的数据**

I am not getting i why getdata function is returning null
Here is the error log

java.lang.NullPointerException: Attempt to invoke interface method &#39;java.lang.Object java.util.Map.get(java.lang.Object)&#39; on a null object reference
at 
com.integratedsoftsols.fyp.bustracking.user.HomeFragment$1.onClick(HomeFragment.java:53)
at android.view.View.performClick(View.java:6274)
at android.view.View$PerformClick.run(View.java:24859)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6710)
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:770)

答案1

得分: 1

你之所以得到null是因为数据库查询是异步的,会立即返回,而不会等待查询完成。你的代码会继续执行,而服务器则在执行查询,然后在查询完成时调用你提供给addOnSuccessListener的回调函数。

因此,在你记录结果的那行代码被执行时,查询尚未完成,bus还没有你期望的值。如果你在getData之后的立即行添加日志记录,而不是在回调之后,你会明白我的意思。

你的代码需要考虑到数据库调用的异步性质。在查询完成后,才能使用bus

英文:

You are getting null because the database query is asynchronous and returns immediately, before the query is complete. Your code continues to execute while the server performs the query, then the callback you provide to addOnSuccessListener is invoked some time later, whenever the query is complete.

As such, the line of code where you log the result is being executed before the query is complete and bus has the value you expect. If you add logging at the line immediately after getData, within the callback (not after the callback), you will see what I mean.

Your code will have to account for the asynchronous nature of the database calls. You won't be able to use bus until after the query completes.

答案2

得分: 0

Sure, here is the translated code:

docRef = db.collection("Buses").document("Bus1");
Button btn = view.findViewById(R.id.submit);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                bus = documentSnapshot.getData();
                if (!bus.get("ID").toString().matches(busId)) {
                    DocumentReference reference = db.collection("Buses").document("Bus2");
                    reference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                        @Override
                        public void onSuccess(DocumentSnapshot documentSnapshot) {
                            bus = documentSnapshot.getData();
                        }
                    });
                }
                if (bus != null) {
                    Toast.makeText(getContext(), "Data read Successfully", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getContext(), MapsActivity.class);
                    startActivity(intent);

                    CONSTANTS.bus = HomeFragment.this.bus;
                    getActivity().finishAffinity();
                } else {
                    Toast.makeText(getContext(), "Data read Failed", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
});
try this

Please note that I have translated the code, but the code itself remains the same.

英文:
    docRef = db.collection(&quot;Buses&quot;).document(&quot;Bus1&quot;);
Button btn=view.findViewById(R.id.submit);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
docRef.get().addOnSuccessListener(new OnSuccessListener&lt;DocumentSnapshot&gt;() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
bus=documentSnapshot.getData();
if (!bus.get(&quot;ID&quot;).toString().matches(busId)) {
DocumentReference reference = db.collection(&quot;Buses&quot;).document(&quot;Bus2&quot;);
reference.get().addOnSuccessListener(new OnSuccessListener&lt;DocumentSnapshot&gt;() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
bus=documentSnapshot.getData();
}
});
}
if (bus!=null){
Toast.makeText(getContext(), &quot;Data read Successfully&quot;, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(getContext(),MapsActivity.class);
startActivity(intent);
CONSTANTS.bus=HomeFragment.this.bus;
getActivity().finishAffinity();
}
else{
Toast.makeText(getContext(), &quot;Data read Failed&quot;, Toast.LENGTH_SHORT).show();
}
}
});
}
});

try this

huangapple
  • 本文由 发表于 2020年8月1日 03:49:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63198277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定