Search code examples
androidmultithreadingthread-safetyjava-threads

How to instantiate a new JSONObject Arraylist which takes the value of the Arraylist returned by a function?


My defined function returns a JSONObejct Arraylist, however, when I instantiate a new Arraylist to the output of the function, it shows an empty Arraylist. How can I fix this issue and why is it showing an empty array list when it is indeed returning an Arraylist in the function?

Here is the code :


protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activty_departures);

      departure_flights = doGetRequest();
}

//my function

private ArrayList<JSONObject> doGetRequest() {
        OkHttpClient client = new OkHttpClient();
        ArrayList<JSONObject> departureObject = new ArrayList<>();
        String url = "http_url";

        Request request = new Request.Builder().url(url).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if(response.isSuccessful()) {

                    try {
                        String jsonData = response.body().string();
                        JSONObject Jobject = new JSONObject(jsonData);
                        JSONArray jarray = Jobject.getJSONArray("Flights");

                        for (int i = 0; i < jarray.length(); i++) {
                            JSONObject object = jarray.getJSONObject(i);
                            String adft = object.getString("Adft");
                            if (adft.equals("D")) {
                                departureObject.add(object);
                            }
                        }
                        

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        return departureObject;

Solution

  • Hitting Api in android not getting immediately return data it depends upon your response. you are to return the list immediately so you received an empty list if you can work inside the onResponse method then your problem is solved.