Home > Enterprise >  Extract String in useCase in Composable
Extract String in useCase in Composable

Time:12-17

My task is to show error when user click submit (if there is one).

For that I have :

data class ValidationResults(
    val successful: Boolean,
    val errorMessage: String? = null
)

Example of input mistake:

@Singleton
class ValidateUsername @Inject constructor() {
    fun execute (username: String) : ValidationResults{

       if(username.isBlank()){
                return ValidationResults(
                    successful = false,
                    errorMessage =  R.string.register_user_empty_user_field.toString()
                )
            }

In presentation:

if(state.username != null){
        Text(
            text = state.usernameError,
            color = Color.Red
        )
    }

But I only get Int enter image description here

How to properly call String from Resources.

EDIT: I get this error if using:

stringResource(id = R.string.register_user_empty_user_field)

@Composable invocations can only happen from the context of a

CodePudding user response:

You need call stringResource(id = R.string.register_user_empty_user_field)

CodePudding user response:

I injected Application in ViewModel:

@HiltViewModel
class RegistrationViewModel @Inject constructor(
    private val validateUsername: ValidateUsername,
    private val validatePassword: ValidatePassword,
    private val validateRepeatedPassword: ValidateRepeatedPassword,
    private val applicationContext: Application
    ) : ViewModel() 

And then just send it to function and use it like this:

 errorMessage = applicationContext.getString(R.string.register_user_username_field_to_short)
  • Related