我希望在一个活动中能够从一个 json 站点,这个SITE获取一些数据,并且能够在 LogCat 和 TextView 中打印只有那些具有“long_name”的城市,我真的很困惑,甚至不知道我是否解释得当,这是我的活动:
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
public class JSonActivity extends Activity {
TextView tvJSON;
HttpClient klient;
JSONObject json;
final static String adres = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=Empire%20State%20Building&";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);
tvJSON = (TextView) findViewById(R.id.tvJSON);
klient = new DefaultHttpClient();
new Gradovete().execute("long_name");
}
public JSONObject getStuff(String town) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(adres);
HttpGet hg = new HttpGet(url.toString());
HttpResponse hr = klient.execute(hg);
int status = hr.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity he = hr.getEntity();
String data = EntityUtils.toString(he);
JSONArray timeline = new JSONArray(data);
JSONObject grads = timeline.getJSONObject(4);
return grads;
} else {
Toast.makeText(JSonActivity.this, "error", Toast.LENGTH_SHORT).show();
return null;
}
}
public class Gradovete extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
String result = null;
try {
json = getStuff("long_name");
return json.getString(params[1]);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
//JSONObject json1 = new JSONObject(result);
//JSONArray jsona = new JSONArray(result);
tvJSON.setText(result);
Log.v("BLAH", result);
}
}
}
编辑:现在,当我进入它在 LogCat 中打印的活动时,它会打印所有内容,而不仅仅是那些带有“long_name”的名称。而对于 TextView 它根本不打印......