Android data binding? issue after calling recreate activity

Viewed 18

First of all, I am not sure if this is a data binding issue, that is just a guess. Please ignore it. Problem is as follows:

In my MainActivity.kt, I use DataBinding as follows:

class MainActivity: BaseActivity(){
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        ...

        binding.someText.text = "A text"
    }
    ...
}

BaseActivity.kt, extends AppCompatActivity(). Now, upon clicking on a button, which changes user locale (and language of the app), I recreate the activity by calling recreate() in the MainActivity.kt. And the user locale changes, language of the app changes, so no problem here.

However, after the recreation, value of the someText becomes an empty string even though the onCreate method is called and the value is set (I observed this via debugging). My question is what could cause the value of someText to be an empty string exactly, why it is not set?

1 Answers

I found the following solution, in case someone else had the same problem.

Inside my onCreate() method, I simply run post() method on my main layout with an action that loads the my data on the UI. In this way, I simply made sure that the data is loaded after the outside most view is created.

Related