Home > OS >  android.content.res.Resources$NotFoundException: String resource ID #0x7f Jetpack Compose
android.content.res.Resources$NotFoundException: String resource ID #0x7f Jetpack Compose

Time:12-27

I want to implement search functionality among lists of banks in my app. So somehow I need to use stringResId() but you can't call it without composable func(). Also by using Resources.getSystem().getString() is giving me resources not found exception.

This is my viewModel code

class BankViewModel: ViewModel() {
    private val _bankAccount = MutableStateFlow(BankAccount())
    val bankAccount: StateFlow<BankAccount> = _bankAccount.asStateFlow()

    var bankList = mutableStateOf(Banks)

    private var cachedBankList = listOf<Bank>()
    private var isSearchStarting = true
    var isSearching = mutableStateOf(false)

    fun updateBankSearch(searchName: String) {
        _bankAccount.update { bankAccount ->
            bankAccount.copy(bankName = searchName)
        }
    }
    fun searchBankName(query: String) {
        val listToSearch = if(isSearchStarting) {
            bankList.value
        }else {
            cachedBankList
        }
        viewModelScope.launch {
            if (query.isEmpty()) {
                bankList.value = cachedBankList
                isSearching.value = false
                isSearchStarting = true
                return@launch
            }
            val results = listToSearch.filter {
                Resources.getSystem().getString(it.bankName).contains(query.trim(), ignoreCase = true)
            }
            if (isSearchStarting) {
                cachedBankList = bankList.value
                isSearchStarting = false
            }
            bankList.value = results
            isSearching.value = true
        }
    }
}

This is my Bank

data class Bank (
        @StringRes val bankName: Int,
        @DrawableRes val bankLogo: Int = R.drawable.bank_image_2
        )

So my question is how can I get a string by using id so that I can compare it with the query??

CodePudding user response:

You need to use the Application Context to retrieve resources like these.

If you're not using any DI framework, or you don't want to use custom ViewModelProvider.Factory, extend AndroidViewModel (which holds a reference to Application) instead of regular ViewModel.

Ideally ViewModels shouldn't contain any Android-specific objects, and you would use some custom StringProvider, or something similar, but that's not a topic of your question.

  • Related