gpt4 book ai didi

java - 无法从静态方法调用 AsyncTask?

转载 作者:太空宇宙 更新时间:2023-11-03 11:56:23 25 4
gpt4 key购买 nike

我似乎无法从静态方法调用 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。它以前工作得很好。有什么问题吗?

最佳答案

如果Async 类是Activity 中的非静态 内部类,那么您需要一个实例 为了实例化内部类

你必须在 static 方法中这样调用:

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

关于java - 无法从静态方法调用 AsyncTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31645577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com