我有一个获取 JSON 数组的 AsyncTask。我将如何返回 JSON 数组,如下所示:
JSONArray channels = new Json().execute(foo, bar);package com.example.tvrplayer;
Eclips告诉我我不能这样做,应该是:
AsyncTask<Object, Integer, JSONArray> channels = new Json().execute("http://192.168.2.136:8080/rest/channel/"+ linkid +"/"+ username, "GET");
Json 异步类:
public class Json extends AsyncTask<Object, Integer, JSONArray> {
Json(){
super();
}
@Override
protected JSONArray doInBackground(Object... params) {
// Log.i("JSON",url);
String url = (String) params[0];
String method = (String) params[1];
InputStream is = null;
String result = "";
JSONArray jsonObject = null;
// HTTP
try {
HttpClient httpclient = new DefaultHttpClient(); // for port 80 requests!
if ( method == "GET") {
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} else if (method == "POST") {
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
} catch(Exception e) {
Log.e("JSON - 1 -", e.toString());
return null;
}
// Read response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
// result = result.substring(1,result.length()-1);
// Log.d("JSON result",result);
} catch(Exception e) {
Log.e("JSON - 2 -", e.toString());
return null;
}
// Convert string to object
try {
jsonObject = new JSONArray(result);
} catch(JSONException e) {
Log.e("JSON - 3 -", e.toString());
return null;
}
return jsonObject;
}
@Override
protected void onPostExecute(JSONArray result)
{
super.onPostExecute(result);
final Message msg = new Message();
msg.obj = result;
}
}
这就是我想要完成的:
JSONArray channels = new Json().execute("http://192.168.2.136:8080/rest/channel/"+ linkid +"/"+ username, "GET");
try {
for (int i=0; i < channels.length(); i++) {
JSONObject channel_data = channels.getJSONObject(i);
String channelID = channel_data.getString("ChannelID").toLowerCase();
JSONArray json = new Json().execute("http://192.168.2.136:8080/rest/program/"+ linkid +"/"+ username +"/" + channelID, "GET");