2 回答

TA貢獻1793條經(jīng)驗 獲得超6個贊
如果您的響應返回一個帶有城市元素數(shù)組的 JSONObject,那么您的請求是正確的,但如上所述,在調(diào)用回調(diào)之前,您不能期望實際得到結果。這是一個使用返回 JSONArray 的 JSONArrayRequest 的示例,但在您從 JSONObject 中提取 City 數(shù)組后,其工作方式與您的幾乎相同。
private ListView mTripList;
public ArrayList<TripItem> tripItems;
private JSONArray unclaimedTrips;
private TripSelectAdapter adapter;
public void getTrips() {
JsonArrayRequest req = new JsonArrayRequest(url, new Response.Listener<JSONArray> () {
@Override
public void onResponse(JSONArray response) {
// Public Array
unclaimedTrips = response;
tripItems = new ArrayList<TripItem>();
// Optional if you want to manipulate the data in some way
if (unclaimedTrips != null) {
for (int i = 0; i < unclaimedTrips.length(); i++) {
try {
JSONObject item = unclaimedTrips.getJSONObject(i);
int tripID = item.getInt("trip_id");
int claimID = item.getInt("claim_id");
String payrollCode = item.getString("payroll_code");
String tripDate = item.getString("trip_date");
String tripPurpose = item.getString("trip_purpose");
TripItem tripItem = new TripItem(tripID, claimID, payrollCode, tripDate, tripPurpose);
tripItems.add(tripItem);
} catch (JSONException e) {
e.printStackTrace();
}
}
refreshData();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
unclaimedTrips = null;
refreshData();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/json");
return headers;
};
};
// add the request object to the queue to be executed
MyApplication.getInstance().addToRequestQueue(req);
}
public void refreshData() {
if (tripItems.isEmpty()) {
mEmptyList.setVisibility(android.view.View.VISIBLE);
} else {
mEmptyList.setVisibility(android.view.View.GONE);
}
adapter = new TripSelectAdapter(this, thisContext, tripItems);
mTripList.setAdapter(adapter);
}

TA貢獻1851條經(jīng)驗 獲得超3個贊
您的問題是您正在嘗試返回尚未填充的內(nèi)容,該調(diào)用是異步的,因此可能需要一些時間才能將日期填充到您的ArrayList<Cities>
中,這就是它為空的原因。
您應該刪除此行return cities;
并記住在您的方法之外創(chuàng)建它final ArrayList<Cities> cities=new ArrayList<>();
,并刪除返回ArrayList<Cities>
到 a void
。
然后,您可以創(chuàng)建一個回調(diào)來通知數(shù)據(jù)已填充到您ArrayList<Cities>
的.RecyclerView
onResponse()
添加回答
舉報