以下是我的代码。它在模拟器上运行良好。但是当我在我的 android 设备上运行它时,它在下面标记的行处以 java.lang.ClassCastException: java.lang.String 崩溃。我找不到选角出错的地方。任何帮助将不胜感激!:)
public static MatrixCursor getRespAsCursor(String query) {
String url = (String)(API_URL + "?api_key=" + API_KEY + "&" + query);
System.out.println(url);
String resp = (String)getAPIResp(url);
JSONObject reply;
MatrixCursor emptyCursor = new MatrixCursor(new String[0]);
try {
reply = (JSONObject) new JSONTokener(resp).nextValue();//CRASHES HERE
String statusCode = (String)reply.getString("statusCode");
if(!statusCode.equals("200")) {
return emptyCursor;
}
int count = Integer.parseInt(reply.getString("count"));
if(count < 1) {
return emptyCursor;
}
JSONArray data = reply.getJSONArray("data");
//Get keys in String[] format
Iterator<String> keys = data.optJSONObject(0).keys();
List<String> copy = new ArrayList<String>();
//Add "_id" as adapters need it for traversal
copy.add("_id");
//copy rest of the keys
while (keys.hasNext())
copy.add(keys.next());
String[] sKeys = new String[copy.size()];
copy.toArray(sKeys);
int len = data.length();
//Create Cursor with JSON keys as columns
MatrixCursor resultCursor = new MatrixCursor(sKeys, len);
//Add rows to Cursor
for(int i = 0; i < len; i++) {
JSONObject d = data.optJSONObject(i);
List<Object> values = new ArrayList<Object>();
for(String key: copy) {
if(key.equals("_id")) {
values.add(Integer.toString(i));
}
else {
values.add(d.opt(key));
}
}
resultCursor.addRow(values);
}
return resultCursor;
}
catch(JSONException e) {
return emptyCursor;
}
}