【问题标题】:Receiving json data from firebase function in android gives null value从android中的firebase函数接收json数据给出空值
【发布时间】:2022-01-16 16:26:57
【问题描述】:

我尝试通过 firebase 函数从 firestore 获取文档集合。firebase 函数控制台显示文档的 json 数据并将该数据返回到 android 应用程序,但 firebase 函数可调用获取 null 值。你能帮我如何接收文档吗安卓应用中的数据。

我什至关注了这个Question 的答案,但我仍然在我的应用程序中收到空值。

export const getproducts = functions.https.onCall((data, context)=>{
  let productarray = [];
  const productref = admin.firestore().collection("Products")
      .orderBy("product_id").limit(2);
  productref.get()
      .then((DataSnapshot) => {
        productarray=DataSnapshot.docs.map((doc) => {
          return doc.data();
        });
        console.log("products returned.", JSON.stringify(productarray));
        return JSON.stringify(productarray);
      }).catch((error)=> {
        throw new functions.https.HttpsError("unknown", error.message, error);
      });
});

我用于从 android 应用中检索数据的代码

mFunctions = FirebaseFunctions.getInstance();
        return mFunctions
                .getHttpsCallable("getproducts")
                .call()
                .addOnSuccessListener(new OnSuccessListener<HttpsCallableResult>() {
                    @Override
                    public void onSuccess(HttpsCallableResult httpsCallableResult) {
                        try {
                            Gson g = new Gson();
                            String json = g.toJson(httpsCallableResult.getData());
                            ProductModel productModel = g.fromJson(json,ProductModel.class);
                            Log.e("getproducts",productModel.getProduct_id()); //i get null value here.
                        } catch (Exception e) {
                            Log.d("Error", e.toString());
                        }
                    }
                });

控制台中显示的文档:

10:49:59.240 AM
getproducts
products returned. [{"cutted_price":100,"dress_color":"blue","product_id":"000001"},{"cutted_price":500,"dress_color":"gray","product_id":"000002"}]

【问题讨论】:

    标签: android firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您的 Cloud Function 缺少返回语句。

    // ...
    productref.get()
      .then((DataSnapshot) => {
    // ...
    

    应该是

    // ...
    return productref.get() // <----
      .then((DataSnapshot) => {
    // ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多