2014-01-23 2 views
0

나는 android를 처음 사용했습니다. 한 문자열을 매개 변수로 사용하는 asynctask 클래스를 작성했습니다. Asynctask 클래스에는 doinbackground와 onpostexecute의 두 가지 함수가 있습니다. doinbackground는 httppost를 수행하고 게시물이 성공적이면 onpostexecute에 문자열 "Success"를 반환하거나 onpostexecute에 "Failed"를 보냅니다.AsyncTask가 MainActivity에 대한 매개 변수를 반환하는 방법

Mainactivity에서는 아래와 같이 Asyncclass를 호출합니다. new MyAsyncTask(). execute (xmlFile);

하지만 데이터베이스 상태를 기반으로 데이터베이스를 업데이트해야 할 때 주력으로 doinbackground가 반환하는 문자열을 가져와야합니다. 누구든지이 문제에 대해 저를 도울 수 있습니까?

꼽은 나는

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

전달하여 asyncclass을 실행 MainActivity에서 아래 싶지 문자열 ;;;

doinbackground 반환 "성공"업데이트 데이터베이스가 다른

가 업데이트되지 않는 경우

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

감사합니다.

답변

1

인터페이스를 콜백으로 사용할 수 있습니다.

당신은 blackbelts는 아래의 링크를

How do I return a boolean from AsyncTask?

에서 답변을 확인하실 수 있습니다 또는 당신은 AsyncTask 활동의 내부 클래스를 만들어 onPostExecute에 결과를 얻을 수 있습니다.

1

몇 가지 방법이 있습니다. 하나는 Handler을 사용하여 ActivityAsyncTask을 상호 연결합니다. 여기에는 Handler 객체가 Activity에서 AsyncTask으로 전달되어 저장되므로 나중에 사용할 수 있습니다. 이것에 대한 자세한 내용은 here.

또 다른 방법은 BroadcastReceiver입니다. 사용하려는 위치 (예 : Activity의 경우 데이터 수신을 원하는 위치)에 AsyncTask에서 Activity까지 sendBroadcast을 사용합니다. 이것에 대한 자세한 내용은 here입니다.

더 많은 방법이 있지만 가장 널리 사용되는 방법입니다.

1

당신은 아마도 당신의 결과와 http 호출이 성공했는지에 따라 onPostExecute 대신 doInBackground에서 데이터베이스 업데이트를 할 수 있습니다.

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

     } 
    } 
}