无法从静态方法调用AsyncTask?

时间:2015-07-27 05:34:12

标签: java android android-activity android-asynctask static-methods

我似乎无法从静态方法调用AsyncTask。它说"不能从静态上下文中引用"。重要的是这个方法是静态的,我需要像我的其他一些过程一样。

有没有办法从方法中调用AsyncTask?

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

编辑:Anands解决方案有效,但是只要它到达方法就抛出了这个异常:

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)

显示空指针的第78行指向这行代码:

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

现在看起来它无法从AsyncTask方法获取SharedPreferences。之前运作良好。这有什么问题?

3 个答案:

答案 0 :(得分:5)

如果Async类是non-static内的Activity内部类,那么您需要instance封闭类才能instantiate inner class

您必须在static方法中以这种方式调用:

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

答案 1 :(得分:3)

将您的内部类声明为static

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

或将其移至自己的文件中。

答案 2 :(得分:0)

你的方法UpdateResults是静态的,但是内部类GetSearchResults没有定义为静态,你不能在静态方法中不涉及任何静态类,因为没有类属于对象,但是在静态方法中没有ogject