skip to Main Content

I am facing a problem to get a return type in a function in kotlin

The function is

 override suspend fun uploaded_docs_retrival() : ArrayList<String> {

    Firebase.firestore.collection("profiles").whereEqualTo("uid", "$uid").get()
        .addOnSuccessListener { result ->
        for (document in result) {
            val myObject = document.toObject(docretreving::class.java)
            val x = myObject.Docs
        }

    }
    return x
}

Here I am retrieving the information from Fire store Mapping it to a object

However in above Function I am unable to return x as it says x is unresolved

My data class is as Follows:

data class docretreving(
val Docs : ArrayList<String> = arrayListOf<String>()

)

How do I write the code in such a way that I can return value x which is a Array list from my function uploaded_docs_retrival()

Edit the below code worked :-

override suspend fun uploaded_docs_retrival() : ArrayList<String> {
    return try {
        val result = Firebase.firestore.collection("profiles").whereEqualTo("uid", "$uid").get()
            .await()
        result.first().toObject(docretreving::class.java).Docs
    } catch(e: Exception) {
        Log.e("TAG", "Failed to upload: ${e.message.orEmpty()}")
        ArrayList()
    }
}

2

Answers


  1. You are getting ‘x is unresolved’ because the scope of ‘val x’ is within the for loop.

    You won’t be able to access it outside the loop and listener.

    The best way to get list of strings, is to pass a listener as parameter to the method. You can also pass the ‘SuccessListener’ to get the values.

    override suspend fun uploaded_docs_retrival(listener : SuccessListener) = Firebase.firestore.collection("profiles").whereEqualTo("uid","$uid").get() .addOnSuccessListener(listener)

    Login or Signup to reply.
  2. Call await() instead of adding a success listener. Wrap it in try/catch because it throws an exception on failure.

    I’m not sure exactly why you’re returning a single item when Firestore can return multiple. I’m just taking the first item in the results below:

    override suspend fun uploaded_docs_retrival() : ArrayList<String> {
        return try {
            val result = Firebase.firestore.collection("profiles").whereEqualTo("uid", "$uid").get()
                .await()
            require(result.isNotEmpty()) { "No values returned." }
            result.first().toObject(docretreving::class.java).Docs
        } catch(e: Exception) {
            Log.e(TAG, "Failed to upload: ${e.message.orEmpty()}")
            ArrayList() // or you can rethrow or return null if you want
        }
    }
    

    If you don’t have access to the await() extension function, add this dependency in build.gradle:

    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.6.0"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search