androidkotlinandroid-activitylocalizationandroid-resources

Localization of text outside of activities in Android?


I have an app with a clear distinction between domain, data, and presentation layers. I have my data model which is fetched from my server, which gets converted to a domain model and that is delivered to the presentation to be used for bindings and so on. I've been trying to localize my project. I have text that reads when a post was posted. eg. "1 hour ago", "Moments ago"...

I wanted to localize this and translate it but I cannot access string res from a data class without context. And I'd like to avoid passing context everywhere. How is this usually handled? It seems like a pretty common use-case of getString, but it seems I was wrong.


Solution

  • getResources(), which you need for the text localization, is the method of the abstract Context class. Activity just inherits it, meaning you don't actually need a reference to an Activity to get the package resources. Application context is enough.

    As to using Context in a data layer, you might create an instance (better singleton) of, let's call it ResourceProvider, passing in the application context. For example,

    interface ResourceProvider {
        fun getString(@StringRes id: Int): String
    }
    
    class ResourceProviderImpl constructor(private val context: Context) : ResourceProvider {
    
        override fun getString(id: Int): String = context.getString(id)
    }
    

    Just make sure you pass the applicationContext to the constructor of ResourceProviderImpl in order to avoid a memory leak on the context whose lifecycle is shorter than that of the application.