android - 在 Kotlin 中从 AsyncTask 返回一个值

标签 android kotlin android-asynctask

我正在使用 Room 和 LiveData 制作一个遵循 MVVM 模式的 Android 应用程序,但我需要返回一个表中最后一次插入的 ID,因为用于在 ID 是外键的其他表中添加值,我知道我可以实现从 DAO 返回它:

@Dao
interface TratamientoDao {
    @Insert
    fun insert(tratamiento : Tratamiento): Long
}

但问题是我需要从插入新条目的 AsyncTask 返回一个值,我尝试了这个问题中解释的方法:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

但在我的例子中,方法 processFinish 从未被调用。

这是我的代码:

interface AsyncValue{
    fun processFinish(lastID: Long?) : Long?
}

class TratamientoRepository (application: Application): AsyncValue {

    val tratamientoDao : TratamientoDao

    init{
        val database = MMRDataBase.getInstance(application)
        tratamientoDao = database.tratamientoDao()
    }

    fun insert(tratamiento: Tratamiento) : Long? {
        InsertTratamientoAsyncTask(tratamientoDao).execute(tratamiento)
        return 45
    }

    override fun processFinish(lastID: Long?): Long? {
        Log.d("ValorIngresado:", lastID.toString())
        return lastID
    }


    private class InsertTratamientoAsyncTask constructor(private val tratamientoDao: TratamientoDao) : AsyncTask<Tratamiento, Void, Long>(){

        var  completionCode : AsyncValue? = null
        override fun doInBackground(vararg params: Tratamiento): Long?{

            return tratamientoDao.insert(params[0])
        }

        override fun onPostExecute(result: Long?) {
           completionCode?.processFinish(result)
            //Log.i("TAMANO", result.toString())

        }

    }

}

那么,我如何才能从 Kotlin 中的 AsyncTask 返回一个值?

最佳答案

我花了一整天的时间来解决这个问题,协程是我的解决方案!!!

首先,创建你的 AsyncTask 对象......不要忘记使用正确的参数类型而不是所有 Any

@SuppressLint("StaticFieldLeak")
class AsyncTaskExample(private var activity: MainActivity?) : AsyncTask<Any, Int, Any?>() {

    override fun onPreExecute() {
        super.onPreExecute()
        // do pre stuff such show progress bar
    }

    override fun doInBackground(vararg req: Any?): Any? {

        // here comes your code that will produce the desired result
        return result 

    }

    // it will update your progressbar
    override fun onProgressUpdate(vararg values: Int?) {
        super.onProgressUpdate(*values)

    }


    override fun onPostExecute(result: Any?) {
        super.onPostExecute(result)

        // do what needed on pos execute, like to hide progress bar
        return
    }

}

然后调用它(在本例中,来自主 Activity )

var task = AsyncTaskExample(this)
var req = { "some data object or whatever" }

GlobalScope.launch( context = Dispatchers.Main){

   task?.execute(req)
}

GlobalScope.launch( context = Dispatchers.Main){

   println( "Thats the result produced by doInBackgorund: " +  task?.get().toString() )
}

关于android - 在 Kotlin 中从 AsyncTask 返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942296/

相关文章:

android - Proguard 混淆使我的应用程序崩溃

android - 用apktools编译snapchat安装失败

android - 只能使用 releaseImplementation 和 debugImplementation 从 maven 添加 Kotlin Multiplatform Mobile 库

java - 如何访问同一android项目另一个文件夹中另一个类的变量?

android - 对于 startActivity,ActivityManager Log 正在显示,但没有调用 Activity 的 onCreate

android - 进度对话框在异步任务中只显示很短的时间并且 Activity 加载缓慢

android - AsyncTask 中的 OnPostExcecute 方法可以返回值吗?

android - ActivityRecognitionApi 与 ActivityRecognitionClient 问题

spring - MapStruct 未注入(inject) Kotlin 项目中

android - 从 AsyncTask 调用 Realm