我正在使用 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/