Non-static method execute () cannot refer to static context

I don't understand why I am getting this compilation error; none of my classes or methods used 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 start an asynchronous task:

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

      

I also tried to instantiate an object of the MainActivity.AsyncStuff class and execute its execute () method, but that doesn't work since it is not part of the class. I cannot move it to a different location because I need to update the interface so that it stays in the MainActivity class.

Anyway, I need help to understand why my ExecuteAsyncMethod () method is not compiling.

Thank!

+3


source to share


2 answers


Define the following:

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

      



and follow these steps:

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

      

+5


source


The reason you are getting this error is because you need to create an instance AsyncTask

, you are trying to call execute()

as if it were a static method.



As for, if you can move yours AsyncTask

, yes, you can just make the class static (or make it your own class entirely) and have a weak referencing activity, so you don't keep it in the ram should it finish before yours AsyncTask

. This is what you want to do whether you save it to MainActivity

or not.

+4


source







All Articles