I'm trying to calling a firebase cloud function that I have written.
I have tested the function using Postman to mimic HTTP requests. Here is the JSON result when I call my function within Postman:
{
"groups": [
{
"isPublic": true,
"members": [
true
],
"numberOfMembers": 1,
"groupId": "-LAOPAzMGzOd9qULPxue"
},
{
"isPublic": true,
"members": [
true
],
"numberOfMembers": 1,
"groupId": "-LAOP7ISDI2JPzAgTYGi"
}
]
}
I am attempting to do the same and retrieve this JSON list within my android app. I am following the example on Firebase's website :https://firebase.google.com/docs/functions/callable
This is Firebase's example on how to retrieve the data:
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;
}
});
It is unclear how I can take the result from my cloud function and use it in the rest of my Android app.
Furthermore, this example returns a Task object which according to Firebase's documentation has now deprecated : https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/tasks/Task)
Is there a clearer, more simple way to handle the data from a function call?
Calling a function is extremely simple so I feel that there must be a more straight forward method to receiving the response.
If you're simply interested in getting JSON from your endpoint, do this from your 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());
}
}
});
If you're using Kotlinx Serialization, you can use org.json.JsonElement
to convert the result data into a format that the serialization framework will accept:
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With