http://inspirontrance.com/app.phpから JSON 配列を解析しようとしていますが、うまくいきません。私のコードに問題がある可能性があるか、URL が defaultHttpClient がサポートしていない別の URL にリダイレクトされているだけだと思います。
私のコードを見て、
Android 解析アクティビティ クラス
public class AndroidJSONParsingActivity extends ListActivity {
private static String url = "http://www.inspirontrance.com/app";
private static final String TAG_UPLOADS = "uploads";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_DATE = "date";
private static final String TAG_UPLOAD_NO = "0";
JSONArray uploads = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> uploads_list = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
uploads = json.getJSONArray(TAG_UPLOADS);
for (int i = 0; i < uploads.length(); i++) {
JSONObject c = uploads.getJSONObject(i);
JSONObject upload_no = c.getJSONObject(TAG_UPLOAD_NO);
String name = upload_no.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
uploads_list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, uploads_list,
R.layout.list_item, new String[] { TAG_NAME },
new int[] { R.id.name });
setListAdapter(adapter);
}
}
JSON パーサー クラス
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}