Java – Can’t call AsyncTask from a static method?

Can’t call AsyncTask from a static method?… here is a solution to the problem.

Can’t call AsyncTask from a static method?

I can’t seem to call AsyncTask from a static method. It says “cannot be referenced from a static context”. The important thing is that this method is static and I need to use it like several of my other processes.

Is there a way to call AsyncTask from within the method?

public static void UpdateResults(String requestSearch){
    new GetSearchResults(requestSearch).execute(); shows an error
}

class GetSearchResults extends AsyncTask<Void, Void, Void> {

String requestSearch;

GetSearchResults(String searchtext){
        this.requestSearch = searchtext;
    }

@Override
    protected Void doInBackground(Void... params) {
        functions continuing 
    }
}

EDIT: The Anands solution works, but it throws this exception as soon as it arrives at the method:

FATAL EXCEPTION: AsyncTask #1
    Process: com.eproject.eproject.emobile, PID: 26831
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at com.eproject.eproject.emobile.SearchTabs.SearchPeopleTab$GetSearchResults.doInBackground(SearchPeopleTab.java:78)
            at com.eproject.eproject.emobile.SearchTabs.SearchPeopleTab$GetSearchResults.doInBackground(SearchPeopleTab.java:63)

Line 78, which shows the null pointer, points to this line of code:

SharedPreferences accPref = getActivity().getSharedPreferences(
                    "accPref", Context.MODE_PRIVATE);

It looks like it can’t get SharedPreferences from the AsyncTask method right now. It used to work just fine. Any questions?

Solution

If the Async class is a non-static inner class in an activity, then you need an instance in order to instantiate the inner class.

You must call it in the static method:

SearchPeopleTab outerClass = new SearchPeopleTab(); Outer class
        GetSearchResults task = outerClass.new GetSearchResults(requestSearch);
        task.execute();

Related Problems and Solutions