0

I've just started learning android development with Kotlin. I'm trying to implement MVVM in my project.

Message: Type mismatch. Required:Uri! Found:Task

I have a question: how to cast a Task in the Url! ???

I have ViewModel:

class AddVehicleViewModel(private val vehicleRepository: VehicleRepository,
                          onFailureListener: OnFailureListener): BaseViewModel(onFailureListener) {
    private val _mkVehicleCompletedEvent = SingleLiveEvent<Unit>()
    val mkVehicleCompletedEvent = _mkVehicleCompletedEvent
    val user = vehicleRepository.getUser()

    fun mkVehicle(user: User, imageUri: Uri?, auto: String) {
        if (imageUri != null) {
            vehicleRepository.uploadVehicleImage(user.uid, imageUri).onSuccessTask { downloadUrl ->
                Tasks.whenAll(
                    vehicleRepository.createVehicle(user.uid, mkListVehicle(user, auto, downloadUrl.toString()))
                )
            }.addOnCompleteListener {
                _mkVehicleCompletedEvent.call()
            }.addOnFailureListener(onFailureListener)
        }
    }

    private fun mkListVehicle(user: User, auto: String, imageUri: String): DataVehicles {
        return DataVehicles(
            uid = user.uid,
            image = imageUri,
            auto = auto,
            username = user.username,
            city = user.city.toString()
        )
    }
}

and repository:

class FirebaseVehicleRepository : VehicleRepository {
    override fun uploadVehicleImage(uid: String, imageUri: Uri): Task<Uri> =
        task { taskSource ->
            storage.child("users").child(uid).child("images")
                .child(imageUri.lastPathSegment.toString()).putFile(imageUri).addOnCompleteListener {
                if (it.isSuccessful) {
                    taskSource.setResult(it.result!!.metadata!!.reference!!.downloadUrl)
                } else {
                    taskSource.setException(it.exception!!)
                }
            }
        }

The error is flashing on this line of code:

taskSource.setResult(it.result!!.metadata!!.reference!!.downloadUrl)
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Danis
  • 1
  • 1

1 Answers1

0

You don't cast a Task to a Uri. The "property" downloadUrl is actually an asynchronous Java method called getDownloadUrl() which returns a Task. You need to use attach a listener to the Task to get the Uri, just like you did when you called putFile(), which also returns a Task.

Use the pattern shown in the documentation:

storageRef.child("users/me/profile.png").downloadUrl.addOnSuccessListener {
    // Got the download URL for 'users/me/profile.png'
}.addOnFailureListener {
    // Handle any errors
}

For your case, use it.result!!.metadata!!.reference!!.downloadUrl.addOnSuccessListener...

Also see the java language equivalent: How to get URL from Firebase Storage getDownloadURL

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441