如何从Android中异步任务的返回值 [英] How to return value from async task in android

查看:809
本文介绍了如何从Android中异步任务的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个异步任务,叫我的服务器从数据库获取数据。
我需要处理来自HTTP服务器调用返回的结果。
从我的活动我打电话,在许多地方的异步任务。所以我不能用成员变量访问的结果。有没有什么办法吗?

 公开结果CallServer(字符串PARAMS)
{

    尝试
    {
    新MainAynscTask()执行(PARAMS);
    }
    赶上(例外前)
    {
        ex.printStackTrace();
    }
    返回aResultM; //需要找回的结果

}

    私有类MainAynscTask扩展的AsyncTask<字符串,太虚,结果> {


    @覆盖
    保护的结果doInBackground(字符串... ParamsP){
        //调用服务器C $ CS $
        返回aResultL;
    }
    @覆盖
       保护无效onPostExecute(结果结果){
          super.onPostExecute(结果);
          //我怎么会把这个结果在那里我叫这个任务?
       }
 

解决方案

尝试调用的AsyncTask的get()方法调用execute()方法之后。这对我的作品

<一个href="http://developer.android.com/reference/android/os/AsyncTask.html#get()">http://developer.android.com/reference/android/os/AsyncTask.html#get()

 公开结果CallServer(字符串PARAMS)
{
   尝试
   {
       MainAynscTask任务=新MainAynscTask();
       task.execute(PARAMS);
       导致aResultM = task.get(); //添加这
   }
   赶上(例外前)
   {
       ex.printStackTrace();
   }
   返回aResultM; //需要找回的结果

}
...
...
 

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

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆