Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot call AsyncTask from a static method?

I can't seem to call a AsyncTask from a static method. It says "cannot be referenced from a static context". It is important that this method IS static and I need to have it like that for a few other processes of mine.

Is there a way to call the AsyncTask from 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: Anands solution worked however it threw this exception as soon as it got to 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)

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

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

Looks like it can't get hold of the SharedPreferences from the AsyncTask method now. It worked well before. What is wrong with it?

like image 709
Dinuka Jay Avatar asked Aug 23 '26 14:08

Dinuka Jay


1 Answers

If Async class is a non-static inner class inside of your Activity, then you need an instance of the enclosing class in order to instantiate the inner class.

You have to call like this way inside static method:

SearchPeopleTab outerClass = new SearchPeopleTab(); //Outer class
        GetSearchResults task = outerClass.new GetSearchResults(requestSearch);
        task.execute();
like image 60
Anand Singh Avatar answered Aug 26 '26 04:08

Anand Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!