Activity.setTitle doesn't work in runOnUiThread block

142 Views Asked by At

I need to get a Note() object from my room database from a background thread and set the title of the note as my activity title, but title = note.title doesn't work and I see my application name in the toolbar. I have also tried supportActionBar?.title and toolbar.title but none of them solved the issue. I'm sure that the database is giving me the right data and I don't know where is the problem. Any help is appreciated.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_show_note)
    setSupportActionBar(toolbar)
    supportActionBar?.setDisplayHomeAsUpEnabled(true)
}

override fun onResume() {
    super.onResume()
    intent.extras?.also {
        val id = it.getInt(ID_EXTRA)
        Thread(Runnable {
            note = db.noteDao().getNote(id)
            runOnUiThread {
                title = note.title
                tvShowNote.text = note.note
                tvShowTime.text = note.time.format()
            }
        }).start()
    }
}
2

There are 2 best solutions below

0
karan On

setTitle is method of action bar, you need to use actionbar's instance to set its property. try using below code after you have set your toolbar as support actionbar.

val actionBar = supportActionBar
actionBar!!.title = "your_title"
0
Ashik Lanjewar On

You have to set something like this.

supportActionBar!!.title = title //your_title_put_here

Have you tried the same without runOnUiThread.