我对 Android 开发比较陌生,正在编写我的第一个基于 REST 的应用程序。我选择使用Android Asynchronous HTTP Client让事情变得更简单一些。我目前正在浏览该链接上的主要“推荐用法”部分,基本上只是创建一个基本的静态 HTTP 客户端。我正在遵循给出的代码,但将其更改为引用不同的 API。这是有问题的代码:
public void getFactualResults() throws JSONException {
FactualRestClient.get("q=Coffee,Los Angeles", null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue = venues.get(0);
String venueName = firstVenue.getString("name");
// Do something with the response
System.out.println(venueName);
}
});
}
该String venueName = firstVenue.getString("name");
行当前在 Eclipse 中引发错误:“类型不匹配:无法从 Object 转换为 JSONObject”。为什么会出现这个错误?我搜索了其他线程,这些线程导致我尝试使用getJSONObject(0)
而不是,get(0)
但这导致了进一步的错误,并且 Eclipse 建议使用 try/catch。我没有更改教程中的任何代码,除了变量名和 URL。有什么想法/提示/建议吗?
非常感谢。
编辑:
这是 onSuccess 方法,经过修改以包含建议的 try/catch 块。Eclipse 现在在此处显示 firstVenue 的“局部变量可能尚未初始化”:venueName = firstVenue.getString("name");
和此处的场地名称:System.out.println(venueName);
即使我在仍然收到相同的错误String venueName;
后直接初始化。JSONObject firstVenue;
解决这些问题的任何帮助将不胜感激!
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue;
try {
firstVenue = venues.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);
}