したがって、アプリケーションのいくつかの部分から呼び出すことができる一方で、(ネットワーク呼び出しを行うため) UI スレッドのハングを回避するために、public static メソッド内に配置した Async タスクがあります。Async タスクは正常に動作し、JSONOBJECT を返します (これを確認するためにコードの一部をログに記録しました)。ただし、問題は public static メソッドを使用しているため、戻り値の型が必要です (場合によっては JSONOBJECT を返す必要があります) が、常に null を返します。 Async タスクによって取得された 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
}
}