我所要做的就是保存数据库中的一对列表,以供稍后在代码中使用,但是当在onResponse方法之外调用列表时,列表始终显示为空。我在Android Studio和数据库中都是新手。我使用了Volley库,这是代码的一部分的“提取”,这使我对某些打印(阵列是否为空)有问题:
public class Fragmento extends Fragment {
ArrayList<String> codes = new ArrayList<String>();
ArrayList<String> names = new ArrayList<String>();
ArrayList<ArrayList<String>> thing= new ArrayList<ArrayList<String>>();;
RequestQueue requestQueue;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
load();
System.out.println(thing); //ARRAY IS EMPTY
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragmento, container, false);
}
private void load(){
JsonArrayRequest jsonArrayRequest= new JsonArrayRequest("the url here",new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
codes.add(jsonObject.getString("codigo"));
names.add(jsonObject.getString("nombre"));
} catch (JSONException e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
thing.add(codes);
thing.add(names);
System.out.println(thing);//ARRAY IS FULL
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),error.getMessage(), Toast.LENGTH_LONG).show();
}
});
System.out.println(thing);//ARRAY IS EMPTY
requestQueue=Volley.newRequestQueue(getActivity());
requestQueue.add(jsonArrayRequest);
}
}
由于在load()
函数中,您正在后台使用JsonArrayRequest
调用API,因此System.out.println(thing)
中的onCreate()
会在从服务器获取响应之前进行调用。这就是thing
数组为空的原因。