【发布时间】:2018-01-14 22:55:51
【问题描述】:
我正在开发一个在线广播应用演示。我需要从互联网上获取一些数据,例如电台名称和口号,我看了一些关于如何使用 volley 解析 JSON 文件并从互联网上获取数据的教程,但我尝试了不同的方法,但似乎没有任何效果,这是一个简化的代码
代码
public class MainActivity extends AppCompatActivity {
TextView textView;
RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestQueue = Volley.newRequestQueue(getApplicationContext());
textView =(TextView) findViewById(R.id.textView);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://api.myjson.com/bins/cd6dh", null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("1");
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject station = jsonArray.getJSONObject(i);
String stationname = station.getString("motto");
textView.append(stationname);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("volley", "error");
}
});
requestQueue.add(jsonObjectRequest);
}
JSON 网址 https://api.myjson.com/bins/cd6dh
当我运行这段代码时,我的文本仍然保持不变
【问题讨论】:
-
i <= jsonArray.length()在索引数组时会抛出越界异常。也许这就是它不起作用的原因? -
你也不应该使用数字作为对象键...直接使用数组的索引
标签: android json android-volley android-json