나는 그물에서 Json을 얻기 위해 AsyncTask를 작성한 클래스가 있습니다. 비동기 작업이 완료 될 때까지 비동기 작업이 완료 될 때까지 UI 스레드의 실행을 중지하는 방법 안드로이드에서 AsyncTask에 들어있는 값
public class MyAsyncGetJsonFromUrl extends AsyncTask<Void, Void, JSONObject> {
Context context_;
String url_;
List<NameValuePair> params_;
public MyAsyncGetJsonFromUrl(Context context_, List<NameValuePair> params_, String url_) {
this.context_ = context;
this.params_ = params_;
this.url_ = url_;
}
@Override
protected JSONObject doInBackground(Void... params) {
JSONObject jObj_ = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_);
httpPost.setEntity(new UrlEncodedFormEntity(params_));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is_ = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is_.close();
String json_ = sb.toString();
Log.e("JSON", json);
jObj_ = new JSONObject(json_);
} catch (Exception e) {
e.printStackTrace();
}
return jObj_;
}
protected void onPostExecute(JSONObject jObj_) {
jObj = jObj_;
}
}
또한이 클래스의 메소드를 호출 활동이 JSON 개체를 반환하는 방법이있다.
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
new MyAsyncGetJsonFromUrl(context, params, url).execute();
return jObj;
}
이제 문제는 즉시 라인 return jObj;
가 호출되고 널 (null)이 리턴 AsyncTask를 new MyAsyncGetJsonFromUrl(context, params, url).execute();
를 시작한 후입니다. 그래서 비동기 작업이 완료 될 때까지 실행을 멈추고 싶습니다. 그리고 다른 질문이이 시나리오와 완전히 동일하지 않으므로이 질문을 중복으로 언급하지 마십시오.
이 답변을 주셔서 감사합니다. –
.get() 메소드를 사용해 주셔서 감사합니다.하지만 UI가 정지됩니다. 이처럼 becuse를 사용하는 다른 방법도 있습니다. 작동하지만 UI가 동결되어 pls를 도와줍니다. – CoronaPintu