我想在Android中創建此應用程序,我從JSON格式的foursquare API獲取數據,並且需要解析它以將其呈現在另一個意圖中。 我正在使用Android的排球庫來獲取JSON,但問題是JsonObjectRequest的onResponse()函數沒有返回參數。因此,我無法從onResponse之外的url獲取JSON對象。 我之前沒有和凌雲一起工作過,因此對它不瞭解太多,任何幫助都不勝感激。這是我試圖使其工作的代碼。如何從內部類中獲取對象
編輯:我面臨的主要問題是,我不能在這種情況下爲JsonObjectRequest的onResponse方法中的myPlaces賦值全局變量。或者準確的說,裏面賦值的變量沒什麼意思之外,從而在最後一行
Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();
當我嘗試訪問myPlaces [2]它給了我一個空指針異常
。
謝謝。
public void onClick(View v) {
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlString, null, new com.android.volley.Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject meta = response.getJSONObject("meta");
String status = meta.getString("code");
Toast.makeText(MainActivity.this, status, Toast.LENGTH_SHORT).show();
if(status.equals("200"))
{
JSONObject responseJson = response.getJSONObject("response");
JSONArray venues = responseJson.getJSONArray("venues");
Places[] tempPlaces = new Places[venues.length()];
for (int i = 0 ; i < venues.length(); i++)
{
Places place = new Places();
JSONObject venueObject = venues.getJSONObject(i);
place.setName(venueObject.getString("name"));
JSONObject locatVenue = venueObject.getJSONObject("location");
place.setLat(locatVenue.getDouble("lat"));
place.setLon(locatVenue.getDouble("lng"));
tempPlaces[i] = place;
}
Toast.makeText(MainActivity.this, tempPlaces[2].getName(), Toast.LENGTH_LONG).show();
myPlaces = tempPlaces;
}
else
{
Toast.makeText(MainActivity.this, "No response from API", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "There is some error here", Toast.LENGTH_LONG).show();
}
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "There has been some error", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();
[在外部類java中使用內部類對象]可能的重複(http://stackoverflow.com/questions/18292824/using-inner-class-object-in-outer-class-java) – pczeus