Is it possible to save language option in DataStore?

Viewed 33

I'm using single activity pattern on my android project in kotlin.

The users can change language inside the app. I'm trying to store the option into Data store. Then every time user start the activity/App then it can load the last option in Data store.

That is:

    override fun attachBaseContext(newBase: Context) {
        runBlocking {

 DatastoreManager.instance.getUserLanguage(this@AppActivity).collect {
                LanguageManager.currentLanguage = Language.valueOf(it.uppercase())
            }
        }
        newBase.resources?.configuration.locale = LanguageManager.currentLanguage.locale
        super.attachBaseContext(newBase)
    }

However,

attachBaseContext starts before onCreate, I think that's the reason why I got:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

Please correct me if I'm wrong. So my question is any way to achieve this usage? Thanks!

EDIT I'm trying to use application context to replace use activity to read the flow value in data store:

runBlocking {
        DatastoreManager.instance.getUserLanguage(getAppContext()).collect {
           
        }
    }

The error is gone, BUT the UI is blocked. Not sure why? runBlocking never return??

1 Answers

Since you're using the application context. You can call this function before the super.onCreate(savedInstanceBundle)

override fun onCreate(savedInstanceState: Bundle ? ) {
    runBlocking {
        DatastoreManager.instance.getUserLanguage(getAppContext()).collect {}
    }
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
}
Related