Search code examples
androidkotlinprogressdialogandroid-library

How to display a ProgressDialog and dismiss it when finished doing a job


I have a method which collects a large amount of data which slows down my application (all call logs). What I am trying to achieve is that before this method is called, it shows a ProgressDialog, this I have achieved. What I am not capable of is that it makes it dismiss when the method gets all the data and displays it on the screen.

For this method I am using the Anko library to make the call to the asynchronous method.

This is my code:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = MyActivityBinding.inflate(layoutInflater)
    setContentView(binding.root)

    var pd = ProgressDialog(this)
    pd.show()
    pd.setContentView(R.layout.myCustomLoading)
    pd.window?.setBackgroundDrawableResource(R.color.transparent)
    pd.setCancelable(false)

    doAsync { //Anko library

        val myList = getData()  //This methood return a List<Model>
        binding.list.adapter = MyAdapter(this@MyActivity, myList)

    }

    pd.dismiss()
}

The problems I have with this code is that the ProgressDialog is not showing and to display the data on the screen in the RecyclerView I must touch the screen or drag it, this is rare.


Solution

  • Move pd.dismiss() to the bottom of async block.

    But don't forget to run it on UI thread activity.runOnUiThread { pd.dismiss() }