我有一个类,我在其中编写了一个 AsyncTask 从网络获取 Json。
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 对象返回给调用该方法的 Activity。
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
new MyAsyncGetJsonFromUrl(context, params, url).execute();
return jObj;
}
现在的问题是在立即启动 AsyncTask 之后调用new MyAsyncGetJsonFromUrl(context, params, url).execute();
该行return jObj;
并返回 null。所以我想停止执行,直到异步任务完成。并且请不要重复提及这个问题,因为没有其他问题与这种情况完全相同