2014-01-23 40 views
0

我是android新手。我寫了一個asynctask類,它將一個字符串作爲參數。 Asynctask類有兩個函數doinbackground和onpostexecute。 doinbackground正在執行一個httppost,並且如果該帖子成功,它將返回一個字符串「Success」,以onpostexecute或將「Failed」設置爲onpostexecute。AsyncTask如何將參數返回給MainActivity

In Mainactivity我打電話給下面的Asyncclass: new MyAsyncTask()。execute(xmlFile);

但我需要得到doinbackground在我的主要活動中返回的字符串,因爲我需要更新數據庫字段。任何人都可以幫助我解決這個問題。

打趣我想做低於MainActivity

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

運行通過傳遞asyncclass一個字符串;;;

如果doinbackground返回 「成功」 更新數據庫

否則不更新

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

謝謝

回答

1

你有幾種方法。其中一個使用Handler,將ActivityAsyncTask互通。這將涉及將對象從Activity傳遞到AsyncTask並將其存儲在那裏,以便您稍後可以使用它。更多關於這個here

另一種方法是使用BroadcastReceiver。您可以在要使用它的地方聲明它(即,您想要接收數據的位置,在本例中爲您的Activity),並且您使用從AsyncTaskActivitysendBroadcast。更多關於這個here

還有更多的方法,但這是最廣泛使用的。

1

您可能只需在doInBackground中執行數據庫更新,而不是使用onPostExecute,這樣您的結果以及是否傳遞了http調用。

或者你可以讓AsyncTask返回一個類,看它是否成功,然後結果在onPostExecute中處理,但是你在這個時候回到了UI線程上,可能不想用db來阻塞更新。

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){ 

     } 
    } 
} 
相關問題