2015-01-29 3 views
0

나는 이것에 대한 몇 가지 제목을 검색했지만 적절한 방법으로 내가하고 싶은 것을 얻을 수 없었다. GET url을 사용하여 서버에 연결하고 return xml 파일을 다른 활동에서 사용할 수있는 문자열로 읽어야합니다. 디버깅 할 때 내 코드가 잘 작동하지만 올바른 문자열 반환을 얻을 수 없습니다.android에서 asynctask에서 문자열 가져 오기

protected JSONArray doInBackground(String... params) { 
    URL url; 
    HttpURLConnection urlConnection = null; 
    JSONArray response = new JSONArray(); 

    try { 
     url = new URL(params[0]); 
     urlConnection = (HttpURLConnection) url.openConnection(); 
     int responseCode = urlConnection.getResponseCode(); 

     if(responseCode == HttpStatus.SC_OK){ 
      String responseString = readStream(urlConnection.getInputStream()); 
      Log.v("CatalogClient", responseString); 
      response = new JSONArray(responseString); 
     }else{ 
      Log.v("CatalogClient", "Response code:"+ responseCode); 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     if(urlConnection != null) 
      urlConnection.disconnect(); 
    } 

    return response; 
} 

private String readStream(InputStream in) { 
    BufferedReader reader = null; 
    StringBuffer response = new StringBuffer(); 
    try { 
     reader = new BufferedReader(new InputStreamReader(in)); 
     String line = ""; 
     while ((line = reader.readLine()) != null) { 
      response.append(line); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (reader != null) { 
      try { 
       reader.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    return response.toString(); 
} 
+0

AsyncTask를 사용하면 UI 스레드에서 실행되는 onPostExecute() 메서드를 사용하여 작업에 값을 반환해야합니다. doInBackGround 메서드 만 사용하면 UI 스레드에 없기 때문에 작동하지 않는 것처럼 보입니다. 개발자 가이드 라인은 다음 페이지에서 확인하십시오. http://developer.android.com/reference/android/os/AsyncTask.html –

+0

답변 해 주셔서 감사합니다. 사실 asyncTask가 끝날 때까지 기다려야합니다. XML 파일의 내용에 따라 다른 활동을 시작하기 때문입니다. execute(). get()은 내 주요 활동을 차단할 것이므로 권장하지 않습니다. onpostexecute() 메서드를 사용해야한다는 것을 이해하지만 어떻게 반환 문자열을 다른 클래스로 파싱 할 수 있는지 이해할 수 없습니다. public class finalResult { String result; } 저에 대한 예를 들어 주시겠습니까? 다시 한 번 감사합니다 – SinanAy

+0

AsyncTask에서 활동과 통신하려면 인터페이스가 필요합니다.이 질문은 여러분이 필요로하는 것과 정확히 일치한다고 생각합니다 : http://stackoverflow.com/questions/12575068/how-to-get-the-result -of-on-postexecute-to-main-activity-asynctask-is-a –

답변

-1

public class MainActivity extends ActionBarActivity { 

Helper parser = new Helper(); 
Document doc; 
NodeList nl; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    callUrl(); 

} 

private void callUrl() { 

    new NetworkRequest(new CallbackInterface() { 

     @Override 
     public void onRequestSuccess(String result) { 
      doc = parser.getDocumentElement(result); 
      nl = doc.getElementsByTagName("item"); 

      for (int i = 0; i < nl.getLength(); i++) { 


       String id = parser.getValue(element, "id"); 
       String name = parser.getValue(element, "name"); 
       String cost = parser.getValue(element, "cost"); 
       String description = parser.getValue(element, "description"); 

       Log.i("Values", id + name + cost + description); 
      } 

     } 
    }, "").execute(); 
} 
} 

이 NetworkRequest 클래스를

public class Helper { 

public Document getDocumentElement(String xml) { 

    Document doc = null; 

    try { 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 
     InputSource is = new InputSource(); 
     is.setCharacterStream(new StringReader(xml)); 
     doc = db.parse(is); 
    } catch (SAXException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (ParserConfigurationException e) { 
     e.printStackTrace(); 
    } 

    return doc; 

} 

public String getValue(Element item, String str) { 
    NodeList n = item.getElementsByTagName(str); 
    return this.getElementValue(n.item(0)); 
} 

public final String getElementValue(Node elem) { 
    Node child; 
    if (elem != null) { 
     if (elem.hasChildNodes()) { 
      for (child = elem.getFirstChild(); child != null; child = child 
        .getNextSibling()) { 
       if (child.getNodeType() == Node.TEXT_NODE) { 
        return child.getNodeValue(); 
       } 
      } 
     } 
    } 
    return ""; 
} 
} 

만들기 datas를 구문 분석하는 도우미 클래스를 작성하십시오

public class NetworkRequest extends AsyncTask<Void, Void, String> { 

private String url = "http://api.androidhive.info/pizza/?format=xml"; 
private CallbackInterface callBack; 
private String result; 

public interface CallbackInterface { 
    public void onRequestSuccess(String result); 
} 

public NetworkRequest(CallbackInterface callBack, String url) { 
    this.url += url; 
    this.callBack = callBack; 
} 

@Override 
protected String doInBackground(Void... params) { 

    try { 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 
     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     result = EntityUtils.toString(httpEntity); 
     return result; 

    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
     return null; 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return null; 
    } 
} 

@Override 
protected void onPostExecute(String result) { 
    super.onPostExecute(result); 
    callBack.onRequestSuccess(result); 
} 
}