Issue
I'm making a function that counts files endwith ".mp3" from android devices and be in trouble while getting the result from AsyncTask. How can I get it? Here is my AsyncTask class
class CountAsyncTask: AsyncTask<String, Int, Int>() {
private val root = Environment.getExternalStorageDirectory().path + "/Zing MP3"
override fun doInBackground(vararg params: String?): Int {
val a: ArrayList<File> = ArrayList()
val files = File(root).listFiles()!!
for (i in files.indices) {
if (files[i].name.endsWith(".mp3"))
a.add(files[i])
}
Log.e("Counting", a.size)
return a.size
}
override fun onPostExecute(result: Int?) {
super.onPostExecute(result)
}
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
}
}
And HERE is my code in activity
fun countSongsOnDevice() {
if (!checkPermissionForReadExtertalStorage()) {
requestPermissionForReadExtertalStorage()
} else {
CountAsyncTask().execute()
//totalSongsOnDevice = ....
}
}
Thank you
Solution
You should do whatever you want to do with the result in the "onPostExecute" method. This method is executed on the UI thread so you can refer UI elements or whatever logic you want to invoke with result of the background task.
The best way is to do is from onPostExecute method to call some method of your main activity that uses the result to show to the user or whatever you want
Answered By - JArgente
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.