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();
}
AsyncTask를 사용하면 UI 스레드에서 실행되는 onPostExecute() 메서드를 사용하여 작업에 값을 반환해야합니다. doInBackGround 메서드 만 사용하면 UI 스레드에 없기 때문에 작동하지 않는 것처럼 보입니다. 개발자 가이드 라인은 다음 페이지에서 확인하십시오. http://developer.android.com/reference/android/os/AsyncTask.html –
답변 해 주셔서 감사합니다. 사실 asyncTask가 끝날 때까지 기다려야합니다. XML 파일의 내용에 따라 다른 활동을 시작하기 때문입니다. execute(). get()은 내 주요 활동을 차단할 것이므로 권장하지 않습니다. onpostexecute() 메서드를 사용해야한다는 것을 이해하지만 어떻게 반환 문자열을 다른 클래스로 파싱 할 수 있는지 이해할 수 없습니다. public class finalResult { String result; } 저에 대한 예를 들어 주시겠습니까? 다시 한 번 감사합니다 – SinanAy
AsyncTask에서 활동과 통신하려면 인터페이스가 필요합니다.이 질문은 여러분이 필요로하는 것과 정확히 일치한다고 생각합니다 : http://stackoverflow.com/questions/12575068/how-to-get-the-result -of-on-postexecute-to-main-activity-asynctask-is-a –