添加从JSon对象解码的数据后,ArrayList仍然为空



我在Android Studio中有这样的java代码,当创建新的Majors并打印m.getName((时。它们会被打印出来,数据会从Json对象中正确解码,但在将数据添加到ArrayList majorsArrayList后,它仍然是空的,并且没有添加数据。

在这里,我检查了ArrayList(在onCreate((中(,结果是:ArrayList[]

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView=(RecyclerView) findViewById(R.id.recyclerViewMajors);
getmajors("Al-Kafaat University","Faculty of Pedagogy","faculty","en");
System.out.println("ARRAYLIST"+majorsArrayList);
recycler_majorAdapter recyclerMajorAdapter=new recycler_majorAdapter(this,majorsArrayList);
recyclerView.setAdapter(recyclerMajorAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
System.out.println("ARRAYLIST"+majorsArrayList);}

下面是函数getmajors((

private void getmajors(String uni, String faculty, String dest, String lang)
{
StringRequest stringRequest=new StringRequest(Request.Method.GET, "https://...", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONArray opp =new JSONArray(response);
for (int i = 0; i< opp.length(); i++)
{
JSONObject pollObject= opp.getJSONObject(i);
String major=pollObject.getString("maj");
String university=pollObject.getString("univ");
int id=pollObject.getInt("id");
Majors m=new Majors(major,university, id);
System.out.println(m.getName());
System.out.println(m.getUniversity());
System.out.println(m.getId());
majorsArrayList.add(m);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}

修复,只是在onCreate((中添加了两行:

recycler_majorAdapter recyclerMajorAdapter=new recycler_majorAdapter(this,majorsArrayList);
recyclerView.setAdapter(recyclerMajorAdapter);

到for循环后的getmajors((函数。

相关内容

  • 没有找到相关文章

最新更新