Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-static method execute() cannot be referenced from a static context

Tags:

java

android

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!!

like image 613
user_noname_00 Avatar asked Dec 14 '22 13:12

user_noname_00


2 Answers

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" });
    }
}
like image 104
Theo Lassonder Avatar answered Dec 21 '22 11:12

Theo Lassonder


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.

like image 44
JohanShogun Avatar answered Dec 21 '22 11:12

JohanShogun