【问题标题】:How AsyncTask returns parameters to MainActivityAsyncTask 如何向 MainActivity 返回参数
【发布时间】:2014-02-14 13:11:35
【问题描述】:

我是安卓新手。我编写了一个 asynctask 类,它以一个字符串作为参数。 Asynctask 类有两个函数 doinbackground 和 onpostexecute。 doinbackground 正在执行 httppost,如果发布成功,它会将字符串“Success”返回给 onpostexecute 或将“Failed”传递给 onpostexecute。

在 Mainactivity 中,我调用 Asyncclass,如下所示: 新的 MyAsyncTask().execute(xmlFile);

但我需要获取 doinbackground 在我的 mainactivity 中返回的字符串,因为我需要根据此状态更新数据库文件。谁能帮我解决这个问题。

假设我想在 MainActivity 中执行以下操作

/////////////////////

通过传递一个字符串运行异步类;;;

如果 doinbackground 返回“成功”更新数据库

否则不更新

////////////////////////

谢谢

【问题讨论】:

    标签: android parameter-passing httpresponse main-activity


    【解决方案1】:

    您可以使用接口作为活动的回调。

    您可以在下面的链接中查看黑带答案

    How do I return a boolean from AsyncTask?

    或者您可以将AsyncTask 设为内部活动类,并在onPostExecute 中获取结果。

    【讨论】:

      【解决方案2】:

      你有几种方法。一种是使用Handler,将Activity 与您的AsyncTask 相互通信。这将涉及将Handler 对象从Activity 传递到AsyncTask 并将其存储在那里,以便您以后可以使用它。更多关于这个here

      另一种方法是使用BroadcastReceiver。您将它声明在您想要使用它的位置(即,您想要接收数据的位置,在这种情况下是在您的Activity 中)并且您使用从AsyncTaskActivitysendBroadcast。更多关于这个here

      有更多的方法,但这是最广泛使用的。

      【讨论】:

        【解决方案3】:

        您可能只是在 doInBackground 中而不是 onPostExecute 中更新数据库,这样您就可以得到结果以及 http 调用是否通过。

        或者您可以让 AsyncTask 返回一个类,说明它是否成功,然后在 onPostExecute 中处理结果,但此时您又回到了 UI 线程,可能不想阻止数据库更新.

        private class PostResult {
            boolean succeeded;
            String response;
        }
        private class PostAsync extends AsyncTask<String, String, PostResult> {
            protected PostResult doInBackground(String... xmlToPost) {
                PostResult result = new PostResult();
                try {
                //do you httpPost... with xmlToPost[0];
                    result.response = "your data back from the post...";
                    result.succeeded = true;
                //get your string result
                }catch (Exception ex){
                    result.succeeded = false;
                }
        
                // I would update the db right here, 
                // since it's still on the background thread
        
                return result;
            }
        
            protected void onPostExecute(PostResult result) {
                //you're back on the ui thread...
                if (result.succeeded){
        
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2020-02-27
          • 1970-01-01
          • 2017-01-25
          • 2020-08-15
          • 2011-05-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多