0

let's say i have an activity with instance variable loadedMovie and a method that executes AsyncTask which is in another file

class MainActivity:AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

 var loadedMovie: Movie? = null

 ....

 fun loadMovie() {
   val task = LoadMovieTask(this)

   task.execute()
 }
}

separate AsyncTask

class LoadMovieTask(val ctx: Activity) : AsyncTask<Void, Void, Void>() {

  var movie: Movie? = null

  override fun onPreExecute() {
    ....
  }

  // loading information from network
  override fun doInBackground(vararg params: Void?): Void? {
    movie = load()

    return null
  }

  // here i modify views with help of kotlin android extensions
  override fun onPostExecute(result: Void?) {
    ....
  }
}

problem is: somehow i can't modify loadedMovie neither from doInBackground (which is ok, because it runs on separate thread) and onPostExecute (which is not ok)

i just type ctx.loadedMovie in onPostExecute and it's not there.. maybe i don't understand something? or maybe there is another way to do it that i'm not aware of

1 Answers1

0

Use this

class LoadMovieTask(val ctx: MainActivity)

instead of

class LoadMovieTask(val ctx: Activity)

MainActivity has the method and not the Android's Activity class itself. So even though you need the context, since you are trying to access the method specific to MainActivity, it is required to pass that

Arun Shankar
  • 2,295
  • 16
  • 20