【发布时间】:2020-06-19 19:55:51
【问题描述】:
我正在尝试从远程服务器返回值,将其添加到 ArrayList 并将其显示在 Android Studio 的抽屉中,但我收到了 null。 volley 中的名字和姓氏包含来自我的远程服务器的名字,但名称 ArrayList 返回 null
GetName.java
public List<String> getDriverName(Context contenxt){
String COMPLETE_URL = TRANSACTION_DETAIL_URL + Preferences.getDefaults("email", contenxt);
Log.i("url", COMPLETE_URL);
name = new ArrayList<String>();
StringRequest stringRequest = new StringRequest(Request.Method.GET, COMPLETE_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("info", response.toString());
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("success");
if (jsonArray.length() > 0){
for (int i=0; i <= jsonArray.length()-1; i++){
JSONObject productJson = jsonArray.getJSONObject(i);
first_name =productJson.getString("firstName");
last_name = productJson.getString("lastName");
name.add(first_name);
name.add(last_name);
Log.d(null, "onResponse: " + last_name);
}
}else{
first_name = "";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
first_name = ""; }
});
int socketTimeout = 10000;
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
RequestQueue requestQueue = Volley.newRequestQueue(contenxt);
requestQueue.add(stringRequest);
return name;
}
仪表板活动
NameAndEmail nameAndEmail = new NameAndEmail();
Log.d(null, "result: " + nameAndEmail.getDriverName(getApplicationContext()));
结果
D/: result: []
W/art: Before Android 4.1, method int
android.support.v7.widget.DropDownListView.lookForSelectablePosition(int,
boolean) would have incorrectly overridden the package-private method in
android.widget.ListView
I/info: {"success":[{"firstName":"usfdh","lastName":"hseheh"}]}
D/: onResponse: hseheh
【问题讨论】:
-
Empty 和 null 不是一回事。考虑到打印日志消息的顺序,您似乎遇到了异步问题,您的方法在数据到达之前返回
标签: java android android-studio arraylist android-volley