외부 클래스를 AsyncTask
으로 확장하면 웹 사이트에서 문자열을 가져와 JSONObject
또는 JSONArray
으로 구문 분석 할 수 있습니다. 현재 결과를 얻으려면 .get()
메서드를 사용하지만 서버가 응답하기를 기다리는 동안 응용 프로그램은 프레임을 삭제합니다. 많은 다른 클래스의 데이터를 얻고 있기 때문에 재사용이 가능합니다. 내 AsyncTask를 클래스 :UI 스레드를 차단하지 않고 AsyncTask의 결과를 얻는 방법?
public class JsonTask extends AsyncTask<String, String, String> {
protected String doInBackground(String...params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
Log.d("Response: ", "> Establishing Connection");
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}}
지금 내가 단순히하여 데이터를 얻고있다 :
String result = new JsonTask().execute(url).get();
@RichArt - 아마도 AsyncTask.execute()는 비동기 작업 인스턴스 자체를 반환하기 때문에 'String'또는 다른 종류의 결과는 반환하지 않기 때문일 수 있습니다. –