2011-10-01 4 views
8

AsyncTask에서 데이터를 가져 오는 방법은 무엇입니까? 내 MainActivity는 AsyncTask를 트리거하는 DataCall.getJSON 함수를 호출하지만 데이터를 원래 Activity로 가져 오는 방법을 모르겠습니다. state_dataAsyncTask 클래스의 데이터 반환

String state_data = DataCall.getJSON(spinnerURL,spinnerContentType); 

DataCall에이를 문자열을 반환하고 저장해야 DataCall에 호출을

MainActivity :

public class DataCall extends Activity { 
    private static final String TAG = "MyApp"; 


    private class DownloadWebPageTask extends AsyncTask<String, Void, String> { 


     protected String doInBackground(String... urls) { 
      String response = ""; 
      for (String url : urls) { 
       DefaultHttpClient client = new DefaultHttpClient(); 
       HttpGet httpGet = new HttpGet(url); 
       try { 
        HttpResponse execute = client.execute(httpGet); 
        InputStream content = execute.getEntity().getContent(); 

        BufferedReader buffer = new BufferedReader(
          new InputStreamReader(content)); 
        String s = ""; 
        while ((s = buffer.readLine()) != null) { 
         response += s; 
        } 

       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
      return response; 
     } 


     protected void onPostExecute(String result) { 
      //THIS IS WHERE I NEED TO RETURN MY DATA TO THE MAIN ACTIVITY. (I am guessing) 
     } 

     } 

    public void getJSON(String myUrlString, String contentType) { 
     DownloadWebPageTask task = new DownloadWebPageTask(); 
     task.execute(new String[] { "http://www.mywebsite.com/" + myUrlString }); 

    } 

} 
+1

서비스 구동 식 REST 호출 모델을 사용해보십시오. 액티비티 종속 스레드에서 요청하는 대신? – Necronet

답변

7

나를위한 열쇠는 URLWithParams 또는 AsyncTask가 IN 유형으로 전송 될 수있는 하나의 클래스 만 허용하므로 URL 요청을 위해 URL과 매개 변수가 모두 필요하기 때문에 클래스를 작성하는 것이 었습니다.

public class URLWithParams { 

    public String url; 
    public List<NameValuePair> nameValuePairs; 

    public URLWithParams() 
    { 
     nameValuePairs = new ArrayList<NameValuePair>(); 
    } 
} 

하고는 나는 JSONClient로 보내 :

public class JSONClient extends AsyncTask<URLWithParams, Void, String> { 
    private final static String TAG = "JSONClient"; 

    ProgressDialog progressDialog ; 
    GetJSONListener getJSONListener; 
    public JSONClient(GetJSONListener listener){ 
     this.getJSONListener = listener; 
    } 

    @Override 
    protected String doInBackground(URLWithParams... urls) { 
     return connect(urls[0].url, urls[0].nameValuePairs); 
    } 

    public static String connect(String url, List<NameValuePair> pairs) 
    { 
     HttpClient httpclient = new DefaultHttpClient(); 

     if(url == null) 
     { 
      Log.d(TAG, "want to connect, but url is null"); 
     } 
     else 
     { 
      Log.d(TAG, "starting connect with url " + url); 
     } 

     if(pairs == null) 
     { 
      Log.d(TAG, "want to connect, though pairs is null"); 
     } 
     else 
     { 
      Log.d(TAG, "starting connect with this many pairs: " + pairs.size()); 
      for(NameValuePair dog : pairs) 
      { 
       Log.d(TAG, "example: " + dog.toString()); 
      } 
     } 

     // Execute the request 
     HttpResponse response; 
     try { 
      // Prepare a request object 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(pairs)); 
      response = httpclient.execute(httpPost); 
      // Examine the response status 
      Log.i(TAG,response.getStatusLine().toString()); 

      BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
      String json = reader.readLine(); 
      return json; 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     return null; 
    } 



    @Override 
    protected void onPostExecute(String json) { 
     getJSONListener.onRemoteCallComplete(json); 
    } 


    public interface GetJSONListener { 
     public void onRemoteCallComplete(String jsonFromNet); 
    } 

} 

그런 말 그렇게 대답 죄송이

public class BookCatalog implements GetJSONListener { 
    private final String TAG = this.getClass().getSimpleName(); 

    private String catalog_url = "URL"; 

    private void getCatalogFromServer() { 

     URLWithParams mURLWithParams = new URLWithParams(); 
     mURLWithParams.url = catalog_url; 

     try { 
      JSONClient asyncPoster = new JSONClient(this); 
      asyncPoster.execute(mURLWithParams); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onRemoteCallComplete(String jsonBookCatalogList) { 

     Log.d(TAG, "received json catalog:"); 
     Log.d(TAG, jsonBookCatalogList); 
    JSONObject bookCatalogResult; 
    try { 
     bookCatalogResult = (JSONObject) new JSONTokener(jsonBookCatalogList).nextValue(); 
     JSONArray books = bookCatalogResult.getJSONArray("books"); 

     if(books != null) { 
      ArrayList<String> newBookOrdering = new ArrayList<String>(); 
      int num_books = books.length(); 
      BookCatalogEntry temp; 

      DebugLog.d(TAG, "apparently we found " + Integer.toString(num_books) + " books."); 
      for(int book_id = 0; book_id < num_books; book_id++) { 
       JSONObject book = books.getJSONObject(book_id); 
       String title = book.getString("title"); 
       int version = book.getInt("price"); 
      } 
     } 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    } 


} 
1

그것을 직렬화하고 다음을 참조하십시오. 내가 아는 유일한 방법. 내가 그 간단한 작업을위한 새로운 활동을 만들 동의하지만

1

startActivityForResult() 

다른 활동에서 데이터를 얻을 수있다.

체크 this. 인 텐트의 엑스트라에 데이터를 저장할 수 있습니다. 그러나 여전히 많은 양의 데이터를 가지고 있다면 파일에 쓰는 것이 더 좋으며 다운로드 한 다른 활동의 결과를 얻은 다음 파일을 읽는 것이 좋습니다.

1

일부 옵션 :

A) 여러분의 빈은 Serializable 인터페이스를 구현합니다, 당신은 다음 의도를 통해 콩을 전달할 수 있습니다.

b) Application 인터페이스 (매니페스트에 항목을 만들어야 함)를 구현하고 Application 클래스에 setter \ getter 메서드가 있어야합니다. 응용 프로그램에서 bean을 AsyncTask 이상으로 설정하고 나중에 Activity에서 가져올 수 있습니다.

public class GetData extends AsyncTask<String, Void, String> 
{ 
    DataDownloadListener dataDownloadListener; 
    public GetData() 
    { 
     //Constructor may be parametric 
    } 
    public void setDataDownloadListener(DataDownloadListener dataDownloadListener) { 
     this.dataDownloadListener = dataDownloadListener; 
    } 
    @Override 
    protected Object doInBackground(Object... param) 
    { 
     // do your task... 
     return null; 
    } 
    @Override 
    protected void onPostExecute(Object results) 
    {  
     if(results != null) 
     {    
     dataDownloadListener.dataDownloadedSuccessfully(results); 
     } 
     else 
     dataDownloadListener.dataDownloadFailed(); 
    } 
    public static interface DataDownloadListener { 
     void dataDownloadedSuccessfully(Object data); 
     void dataDownloadFailed(); 
    } 
} 

GetData getdata = new GetData(); 
getdata.setDataDownloadListener(new DataDownloadListener() 
{ 
    @SuppressWarnings("unchecked") 
    @Override 
    public void dataDownloadedSuccessfully(Object data) { 
    // handler result 
    } 
    @Override 
    public void dataDownloadFailed() { 
    // handler failure (e.g network not available etc.) 
    } 
}); 
getdata.execute(""); 

참고 당신의 활동에서 사용 :

24

당신의 AsyncTask 다음과 같이 수정이 글을 읽고있는 사람들을 위해.

최상의 구현을 위해서는 post을 고려하십시오.

+0

그러나 변수를 GetData 클래스에 전달하는 방법은 무엇입니까? 도와 주셔서 감사합니다. +1 – Denoteone

+0

글쎄, 내가 언급 한 것처럼, 당신은'GetData'의 생성자를 통해 변수를 전달할 수 있고 메소드에서 그것들을 더 사용하기 위해'GetData' 클래스의 필드로 만들 수 있습니다. –

+0

+1 좋은 답변입니다. –

0

처럼 내 메인 클래스에서, 내가이 시간에 생각 호출 이 문제를 해결했을 수도 있습니다. 내가 다른 것을 찾고있을 때, 나는 당신의 질문을 보았습니다.here 링크를 붙여서 다른 사용자에게 도움이 될 수 있습니다.