繁体   English   中英

从 Android 中调用 Firebase Cloud Function 接收数据

[英]Receiving data from calling Firebase Cloud Function in Android

我正在尝试调用我编写的 firebase 云函数。

我已经使用 Postman 测试了该功能来模拟 HTTP 请求。 这是我在 Postman 中调用我的函数时的 JSON 结果:

{
 "groups": [
    {
        "isPublic": true,
        "members": [
            true
        ],
        "numberOfMembers": 1,
        "groupId": "-LAOPAzMGzOd9qULPxue"
    },
    {
        "isPublic": true,
        "members": [
            true
        ],
        "numberOfMembers": 1,
        "groupId": "-LAOP7ISDI2JPzAgTYGi"
    }
 ]
}

我正在尝试执行相同的操作并在我的 android 应用程序中检索此 JSON 列表。 我正在关注 Firebase 网站上的示例: https ://firebase.google.com/docs/functions/callable

这是 Firebase 关于如何检索数据的示例:

return mFunctions
        .getHttpsCallable("addMessage")
        .call(data)
        .continueWith(new Continuation<HttpsCallableResult, String>() {
            @Override
            public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                String result = (String) task.getResult().getData();
                return result;
            }
        });

目前尚不清楚如何从我的云功能中获取结果并将其用于我的 Android 应用程序的其余部分。

此外,此示例返回一个 Task 对象,根据 Firebase 的文档,该对象现已弃用: https : //firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/tasks/Task )

有没有更清晰、更简单的方法来处理来自函数调用的数据?

调用函数非常简单,所以我觉得必须有一个更直接的方法来接收响应。

如果您只是对从端点获取 JSON 感兴趣,请从您的 Activity 执行此操作:

        mFunctions
            .getHttpsCallable("getGroups") //Whatever your endpoint is called
            .call()
            .addOnSuccessListener(this, new OnSuccessListener<HttpsCallableResult>() {
                @Override
                public void onSuccess(HttpsCallableResult httpsCallableResult) {
                    try{
                        Gson g = new Gson();
                        String json = g.toJson(httpsCallableResult.getData());
                        Groups groups = g.fromJson(json,Groups.class);
                    } catch (Exception e){
                        Log.d("Error",e.toString());
                    }
                }
            });

如果您使用 Kotlinx 序列化,则可以使用org.json.JsonElement将结果数据转换为序列化框架将接受的格式:

val json = Json(JsonConfiguration.Stable)

fun getPerson(personId: String): Task<Person> {
    val function = functions.getHttpsCallable("getPersonInfo")

    return function.call(mapOf("personId" to personId)).continueWith { task ->
        val result = task.result ?: throw Exception("result is null")

        val jsonString = org.json.JSONObject(result.data as Map<*, *>).toString()
        json.parse(Person.serializer(), jsonString)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM