4

I don't understand why I'm receiving this compile error; none of my classes or methods involved here are static. Maybe someone can shed some light here.

In my MainActivity class I have declared a public class that extends AsyncTask:

public class AsyncStuff extends AsyncTask<String, Void, String> {
    ...
}

In my non-activity class I have a public function that should fire the async task:

public class Util {
    public void ExecuteAsyncMethod(){
        MainActivity.AsyncStuff.execute(new String[]{"test" }); // error here
    }
}

I have also tried to instantiate an object of the MainActivity.AsyncStuff class and execute its execute() method, but this doesn't work either since it's not in an enclosing class. I can't move it somewhere else because I need to update the UI so it needs to stay in the MainActivity class.

Anyhow, I need help to figure out why my ExecuteAsyncMethod() method doesn't compile.

Thank you!!

Ben Cox
  • 1,393
  • 10
  • 28
user_noname_00
  • 269
  • 3
  • 8
  • I guess you need the instance of outer class( MainActivity instance , achieved by `this`) to create inner class instance `MainActivity.this.new AsyncStuff().execute(new String[]{"test" });` – devcodes Jul 16 '15 at 23:01
  • possible duplicate of ["Non-static method cannot be referenced from a static context" error](http://stackoverflow.com/questions/4922145/non-static-method-cannot-be-referenced-from-a-static-context-error) – Solomon Slow Jul 16 '15 at 23:17

2 Answers2

7

Define like this:

public static class AsyncStuff extends AsyncTask<String, Void, String> {
    ...
}

and run like this:

public class Util {
    public void ExecuteAsyncMethod(){
        new AsyncStuff().execute(new String[]{"test" });
    }
}
Theo Lassonder
  • 1,019
  • 9
  • 16
  • If I do it this way, I cannot reference non-static variables in my onPostExecute(). Any fix for this? – Taslim Oseni Jul 10 '19 at 09:41
  • To reference non-static variables, use normal Java idiom: pass them into `ExecuteAsyncMethod()`, then into the `AsyncStuff()` constructor, and store them in member variables. Then you can access the values in `onPostExecute()`. – Theo Lassonder Jul 11 '19 at 10:24
  • I eventually fixed my issue. There was a silly semantic mistake I was making somewhere. This worked. Thank you. – Taslim Oseni Jul 11 '19 at 10:37
5

The reason you're getting that error is that you have to instantiate your AsyncTask, you're trying to call execute() as if it was a static method.

As for if you can move your AsyncTask, yes you can, just make the class static (or make it its own class entirely) and have a weak reference to the activity, so you don't hold it in ram should it finish prior to your AsyncTask. This is something you want to do regardless of if you keep it inside your MainActivity or not.

xp500
  • 1,426
  • 7
  • 11
JohanShogun
  • 2,956
  • 21
  • 30