Search code examples
androidkotlinandroid-roomkotlin-coroutinesuse-case

Error with String to listOfDoubles in Kotlin


I want to parse ClientEntity.weight in String to ClientDetails.weight which is List of Doubles and use it in my Screen.

My mapper:

fun ClientEntity.toClientDetails() : ClientDetails{
    return ClientDetails(
        id = id,
        name = name,
        age = age,
        picture = picture,
        aboutUser = aboutUser,
        weight = toListOfDoubles(weight = weight) ?: emptyList()
    )
}

fun toListOfDoubles(weight: String?): List<Double>? {
    return weight?.split(", ")?.map { it.toDouble() } ?: emptyList()
}

In my viewModel:

 val result = getClientDetailsUseCase.invoke(clientId)

UseCase:

suspend operator fun invoke(clientId: Int) : Result<ClientDetails> = suspendCoroutine { continuation ->
    val coroutineScope = CoroutineScope(Dispatchers.IO)
    coroutineScope.launch {
        val result = clientDetailsRepository.getClientDetailsById(clientId)
        continuation.resume(result)
    }
}

RepoImpl:

  override suspend fun getClientDetailsById(clientId: Int): Result<ClientDetails> {
        return try {
            val response = clientDao.getClientsDetailsById(clientId)
                .toClientDetails()

            Result.Success(data = response, errorMessage = "Client details")
        } catch (e: Exception) {
            Result.Error(data = null, errorMessage = e.message ?: "Problem")
        }
    }

My screen viewModel call:

val viewModel = hiltViewModel<ClientDetailsViewModel>()
    val data = clientId?.let { viewModel.getClientDetailsById(clientId = it) }
    val response = viewModel.clientDetailsResponse.value

In my ClientDetailsScreen i got error: For input String "1.1, 2.2, 3.3"

Edit:

With chatGPT I got this:

You are using this function in your toClientDetails() function to convert the weight value from the ClientEntity object to a List of Doubles before creating a ClientDetails object.


Solution

  • You sure the input string that caused the issue is exactly how you pasted it here, whitespace and all? Seems like an issue with parsing the string into a list of doubles. Would probably be less error-prone if you first removed all whitespace and then split by a single comma instead or with regex to match all potential whitespace that comes after the comma i.e. something like:

    weight?.split(",\\s*".toRegex())?.map { it.toDoubleOrNull() }?.filterNotNull() ?: emptyList().

    Even if it doesn't fix the issue, it would still be good to sanitize the input string as much as possible.