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!!
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" });
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With