• Home
  • Jobs
  • Courses
  • Teachers
  • For business
  • Blog
  • ES/EN

0

23
Views
How do I get context inside a companion object that is inside a data class Kotlin?

I'm trying to use a resource string inside a companion object that is inside a data class. but I don't Know how to obtain context in that case in Kotlin. Anyone knows how to do it?

data class PhoneCall(
val type: String,
    val code: String,
    val description: String){
companion object{
const val SOLUTION_NO_SOLUTION = "NO_SOLUTION" 
        const val SOLUTION_TOMORROW = "71_INAT"
        const val SOLUTION_TODAY = "72_INAT"

val solutions = listOf(
PhoneCall(Service.Traffic.PICK_UP, SOLUTION_NO_SOLUTION, Resources.getSystem().getString(R.string.makeService))
)
}

I need to use a resource string in the 3 parameter, but I'm not able to get the context.

27 days ago ·

Santiago Trujillo

1 answers
Answer question

0

You can modify you PhoneCall model to store a string resource id instead of the actual string.

data class PhoneCall(
    val type: String,
    val code: String,
    @StringRes val description: Int
) {
    companion object {
        const val SOLUTION_NO_SOLUTION = "NO_SOLUTION" 
        const val SOLUTION_TOMORROW = "71_INAT"
        const val SOLUTION_TODAY = "72_INAT"

        val solutions = listOf(
            PhoneCall(Service.Traffic.PICK_UP, SOLUTION_NO_SOLUTION, R.string.makeService)
        )
    }
}

Then, when you need to display this data in the UI (say a TextView), you can fetch the string from the resource id.

descriptionTextView.text = getString(phoneCall.description)
27 days ago · Santiago Trujillo Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.