android - 如何使用在 Android Studio 的 onResponse 方法中定义的变量的值
问题描述
我所需要的只是保存数据库中的一对列表,以便稍后在代码中使用它们,但是当在 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
数组为空的原因。
推荐阅读
- .htaccess - 将所有 http 重定向到 https,将所有 www 重定向到非 www,并从所有 url 中删除 .html
- php - PHP(Codeigniter 3)会话在Google Cloud Platform中重定向后被破坏,但在Localhost和Cpanel中正常工作
- python - python中向量的大小是(N,1)而不是(N,)
- lua - 如何在lua中将一个表存储到另一个表?
- python - 将 hachoir 库的衍生物安装到 Google Colab 中
- mysql - 在 MySQL 中获取“错误 1452(23000):无法添加或更新子行”
- javascript - 为什么 Google Maps .getCenter() 返回无效坐标?
- javascript - GSAP + AdHelper 模板导致“未定义 lib”
- php - 在 Heroku 上安装 PECL 库
- deep-learning - 使用参数共享计算卷积神经网络中的权重数量