如何从android中的异步任务返回值 [英] How to return value from async task in android
本文介绍了如何从android中的异步任务返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个异步任务来调用我的服务器以从数据库中获取数据.
我需要处理从 http 服务器调用返回的结果.
从我的活动中,我在很多地方调用了异步任务.所以我不能使用成员变量来访问结果.有什么办法吗?
I created an async task to call my server to get data from DB.
I need to process the result returned from http server call.
From my activity i calling the async task in many places. so i cant use member variable to access the result. is there any way to do?
public Result CallServer(String params)
{
try
{
new MainAynscTask().execute(params);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return aResultM;//Need to get back the result
}
private class MainAynscTask extends AsyncTask<String, Void, Result> {
@Override
protected Result doInBackground(String... ParamsP) {
//calling server codes
return aResultL;
}
@Override
protected void onPostExecute(Result result) {
super.onPostExecute(result);
//how i will pass this result where i called this task?
}
推荐答案
在调用 execute() 方法后尝试调用 AsyncTask 的 get() 方法.这对我有用
Try to call the get() method of AsyncTask after you call the execute() method. This works for me
http://developer.android.com/reference/android/os/AsyncTask.html#get()
public Result CallServer(String params)
{
try
{
MainAynscTask task = new MainAynscTask();
task.execute(params);
Result aResultM = task.get(); //Add this
}
catch(Exception ex)
{
ex.printStackTrace();
}
return aResultM;//Need to get back the result
}
...
...
这篇关于如何从android中的异步任务返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文