[英]ArrayList showing empty even after adding elements
I am populating my ArrayList
after receiving data from my API and filling it in objects stored by the ArrayList
but when I log the size of the ArrayList
it shows up to be empty. I am populating my
ArrayList
after receiving data from my API and filling it in objects stored by the ArrayList
but when I log the size of the ArrayList
it shows up to be empty.
Here is my code:这是我的代码:
public class MainActivity extends AppCompatActivity {
private RequestQueue queue;
private static ArrayList<Team> teams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.homeRecyclerView);
this.teams = new ArrayList<>();
queue = Volley.newRequestQueue(this);
TeamNamesAdapter teamNamesAdapter = new TeamNamesAdapter(teams);
parseJSON();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(teamNamesAdapter);
Log.i("Info",String.valueOf(teams.size()));
}
private void parseJSON(){
String url = "http://192.168.0.174:8080/team";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(Request.Method.GET, url, null, response -> {
try {
for(int i=0;i<response.length();i++){
JSONObject teamDetails = response.getJSONObject(i);
Team team = new Team();
team.setId(Long.parseLong(teamDetails.getString("id")));
team.setTeamName(teamDetails.getString("teamName"));
team.setTotalMatches(Long.parseLong(teamDetails.getString("totalMatches")));
team.setTotalWins(Long.parseLong(teamDetails.getString("totalWins")));
this.teams.add(team);
Log.i("Info","Added team "+team.getTeamName()+" successfully");
}
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> Log.i("ERROR","Couldn't parse JSON"));
queue.add(jsonArrayRequest);
}}
My API is working as I am able to log every team object that is being created but its not stored in list.我的 API 正在工作,因为我能够记录正在创建但未存储在列表中的每个团队 object。
you can remove this.teams = new ArrayList<>();
你可以删除
this.teams = new ArrayList<>();
and add the initialisaiton at the beginning, since it is static, private static ArrayList<Team> teams = new ArrayList<>();
并在开头添加初始化,因为它是 static,
private static ArrayList<Team> teams = new ArrayList<>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.