我正在寻找Android中主(UI)线程的方法来获取我对网络SQL服务器运行的SQL查询的结果。
我知道你的第一个答案可能是喊出“ASYNCTASK !!!”,但请耐心等待我解释为什么那不是我想要的。
通过使用AsyncTask,我已经可以运行查询并检索结果而不会出现任何问题。 我正在寻找的是一种能够将所有这些捆绑在一起进行一次调用的方法,它将返回AsyncTask的结果。请参阅下面的伪代码:
public static Object returnQueryResults()
{
// Perhaps show a "Loading" dialog
// Start the AsyncTask that will query the SQL server
// Here is the important part, somehow WAIT for the result
// to be returned or timed out or cancelled or whatever
// return the result gotten by the AsyncTask
}
我知道并且完全理解该函数的WAIT部分不能是实际的wait()
,因为这会阻止UI线程而Android不允许这样做,但我所寻找的只能是必须调用此单个函数来检索结果。
对我来说,问题似乎是如何将结果从AsyncTask的postExecute
传递到主UI线程,同时让UI线程等待结果。
任何想法都会受到赞赏,因为我已经尝试过一段时间来解决这个问题。
答案 0 :(得分:1)
您不能在一个方法块中执行此操作。你需要某种回调机制。 AsyncTask本身可能不是最好的框架,但假设您坚持使用它,那么它就像定义接口一样简单,在Activity / Fragment /中实现该接口,并将AsyncTask传递给实现者(例如在构造函数中)。
AsyncTask本身可能不是最好的框架
public class MyAsyncTask extends AsyncTask<String, Void, MyQueryResult> {
interface MyQueryResultCallback {
void onQueryResult(MyQueryResult result);
}
// assuming you may implement the interface in an Activity/Fragment,
// you probably shouldn't keep a strong reference to it because Android
// can destroy and create new instances of those.
private WeakReference<MyQueryResultCallback> callbackRef;
public MyAsyncTask(MyQueryResultCallback callback) {
callbackRef = new WeakReference<MyQueryResultCallback>(callback);
}
/* doInBackground omitted for brevity */
@Override
protected void onPostExecute(MyQueryResult result) {
MyQueryResultCallback callback = callbackRef.get();
if (callback != null) {
callback.onQueryResult(result);
}
}
}
您可以使用一种方法来显示加载指示器并启动任务,然后您的onQueryResult()
实现将关闭加载指示器并更新UI。
答案 1 :(得分:0)
AsyncTask在UI线程上自动运行onPostExecute(),因此您无需执行任何操作,您可以在该方法中填充UI。请小心并取消onDestroy()中的AsyncTask,以避免在Activity消失时传递结果。