所以我有一个异步任务,我已经将它放在一个公共静态方法中,以避免挂起 UI 线程(因为它进行网络调用),同时仍然能够从我的应用程序的几个部分调用它。Async 任务成功运行并返回一个 JSONOBJECT(我已经记录了部分代码以确认这一点)。但是问题是因为我使用公共静态方法,它应该有一个返回类型(在可能的情况下应该返回 JSONOBJECT)但它总是返回 null ..我怎样才能重新编写我的代码才能返回我的异步任务获取的 JSONOBJECT。代码如下。
public class JSONmethod {
static InputStream is = null;
static String res = "";
static JSONObject jArray = null;
public static JSONObject getJSONfromURL(final String url){
new AsyncTask<String, Void, JSONObject>() {
@Override
protected JSONObject doInBackground(String... params) {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
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();
res=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
Log.i("Result BG ", res);
try{
jArray = new JSONObject(res);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray; //at this point the JSONOBJECT has been fetched
}
}.execute();
return jArray; //Always null
}
}