我的json看起来像这样:
{"type":"FeatureCollection","metadata":{"generated":1428783374000,"url":"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-04-04&endtime=2015-04-05","title":"USGS Earthquakes","status":200,"api":"1.0.17","count":328},"features":[{"type":"Feature","properties":{"mag":1.3,"place":"8km SSE of Talmage, California","time":1428191575500,"updated":1428359465102,"tz":-420,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/nc72426686","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=nc72426686&format=geojson","felt":null,"cdi":null,"mmi":null,"alert":null,"status":"reviewed","tsunami":0,"sig":26,"net":"nc","code":"72426686","ids":",nc72426686,","sources":",nc,","types":",cap,general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,tectonic-summary,","nst":12,"dmin":0.08508,"rms":0.06,"gap":154,"magType":"md","type":"earthquake","title":"M 1.3 - 8km SSE of Talmage, California"},"geometry":{"type":"Point","coordinates":[-123.1233333,39.0688333,7.27]},"id":"nc72426686"},
我的主要活动代码如下所示:
public class MainActivity extends ActionBarActivity {
private static final String LOG_TAG ="JSON STRING";
TextView httpData;
HttpClient client;
JSONObject json;
final static String URL = "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-04-04&endtime=2015-04-05";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpData = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("features");
}
public JSONObject lastEvent(String event) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if ( status == 200 ) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}
else {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
try {
json = lastEvent("title");
return json.getString(params[0]);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result ) {
httpData.setText(result);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我的activity_main.xml如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<ScrollView android:layout_height="fill_parent" android:layout_width="fill_parent">
<TextView android:text="Loading Data" android:id="@+id/tvHttp" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
我正在努力获得&#39; title&#39;从JSONArray的第一个元素,但我得到一个空白的文本视图屏幕。我对Java和Android有点新手,所以如果我更容易使用不同的格式(例如XML),我也可以尝试。任何见解或提示都非常感谢。
答案 0 :(得分:1)
好的,假设我们有你发布的JSON
{"type":"FeatureCollection","metadata":{"generated":1428783374000,"url":"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2015-04-04&endtime=2015-04-05","title":"USGS Earthquakes","status":200,"api":"1.0.17","count":328},"features":[{"type":"Feature","properties":{"mag":1.3,"place":"8km SSE of Talmage, California","time":1428191575500,"updated":1428359465102,"tz":-420,"url":"http://earthquake.usgs.gov/earthquakes/eventpage/nc72426686","detail":"http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=nc72426686&format=geojson","felt":null,"cdi":null,"mmi":null,"alert":null,"status":"reviewed","tsunami":0,"sig":26,"net":"nc","code":"72426686","ids":",nc72426686,","sources":",nc,","types":",cap,general-link,geoserve,nearby-cities,origin,phase-data,scitech-link,tectonic-summary,","nst":12,"dmin":0.08508,"rms":0.06,"gap":154,"magType":"md","type":"earthquake","title":"M 1.3 - 8km SSE of Talmage, California"},"geometry":{"type":"Point","coordinates":[-123.1233333,39.0688333,7.27]},"id":"nc72426686"},
这是一个object
。我们想要进入键features
中的数组,并且我们希望在该数组的第一个元素(它是一个对象)中使用标题键。
查看您的lastEvent
功能。您传递一个名为event
的字符串。但这从未使用过。
public String lastEvent(String event) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if ( status == 200 ) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
// data now contains the json object I posted above
// So we fetch it
JSONObject timeline = new JSONObject(data);
// We want the features array
JSONArray features = timeline.getJSONArray("features");
// The first element
JSONObject first = timeline.getJSONObject(0);
// The titles attribute. I assume lastEvent("titles")
// is the way you call this function
String last = first.getString(event);
return last;
}
else {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
注意我更改了lastEvent的返回类型,因为我们从对象中获取了一个String。第一个参数event
现在是我们想要得到的字段,我认为这是你的意图,因为你在AsyncTask中称之为。
另外,检查你的Logcat!可能会抛出JSONException
,您捕获并打印其消息并返回null。返回null,稍后调用httpData.setText(null)
将导致空TextView
修改:您的doInBackground
功能也不需要再次调用getString()
lastEvent
的返回值。
我不知道你的AsyncTask
需要多么通用。但是我写的代码可能会帮助你达到你想要的目标。