0

I am trying to make an ArrayList of objects .But the logd at the last is always showing an empty ArrayList.How can I do it.With the present code I tried few things but they didn't work.I guess i have to return the ArrayList but I am confused. This is my code in MainActivity.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<News> newsArrayList = new ArrayList<>();

        RequestQueue requestQueue = Volley.newRequestQueue(this);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, mURL, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray articles = response.getJSONArray("articles");
                    for (int i = 0; i < 10; i++) {
                        JSONObject news = articles.getJSONObject(i);
                        title = news.getString("title");
                        img_url = news.getString("image");
                        desc = news.getString("description");
                        news_url = news.getString("url");
                        newsArrayList.add(new News(title, img_url, desc, news_url));

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "onErrorResponse: Something went Wrong");
            }
        });
        requestQueue.add(jsonObjectRequest);

        Log.d(TAG, "onCreate: " + newsArrayList); 

This is News.java

 public class News {

    private String mTitle;
    private String mImg_url;
    private String mNews_url;
    private String mDesc;

    public News(String title, String img_url, String desc, String news_url) {
        this.mTitle = title;
        this.mImg_url = img_url;
        this.mDesc = desc;
        this.mNews_url = news_url;
    }

    public String getmTitle() {
        return mTitle;
    }

    public String getmImg_url() {
        return mImg_url;
    }

    public String getmNews_url() {
        return mNews_url;
    }

    public String getmDesc() {
        return mDesc;
    }
}

Anonymous
  • 33
  • 7
  • In the moment you print `Log.d`, list is always empty. You add items to the list in an asynchronous way, when `onResponse` is called. – evaristokbza Sep 02 '21 at 08:30
  • Please tell me how should i do it then.. – Anonymous Sep 02 '21 at 16:03
  • At the end of `onResponse` code, if the parsing is correct, your list should be filled and you can use it. Add the `Log.d` just after the `for` loop and you will see its value. – evaristokbza Sep 03 '21 at 07:29

0 Answers0