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

Iro*_*ugh 5 java android firebase

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

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

{
 "groups": [
    {
        "isPublic": true,
        "members": [
            true
        ],
        "numberOfMembers": 1,
        "groupId": "-LAOPAzMGzOd9qULPxue"
    },
    {
        "isPublic": true,
        "members": [
            true
        ],
        "numberOfMembers": 1,
        "groupId": "-LAOP7ISDI2JPzAgTYGi"
    }
 ]
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试执行相同的操作并在我的 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;
            }
        });
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Ato*_*ean 7

如果您只是对从端点获取 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());
                    }
                }
            });
Run Code Online (Sandbox Code Playgroud)