poortechworker
poortechworker

Reputation: 669

Json receiving issue while using OkHttp

I am using OkHttp for retrieving data from json data from an api. I have written the following code:

OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(forecastUrl).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                // TODO: manage failure
                // try again
                doInBackground(params);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String jsonData = response.body().string();
                    nowDataList.clear();
                    hourlyDataList.clear();
                    dailyDataList.clear();
                    try {
                        nowDataList.add(getNowData(jsonData));
                        for (int i = 0; i < 24; i++) {
                            hourlyDataList.add(getHourlyData(jsonData, i));
                        }
                        for (int i = 0; i < 8; i++) {
                            dailyDataList.add(getDailyData(jsonData, i));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    // if response is not successful try again
                    doInBackground(params);
                }
            }

Now the above code receives full data in good internet speeds (WiFi/LTE). However I sometimes don't get complete json data on slow internet speed (mostly on 2G/3G)

I have tried the following solution as well: Android JSON receive issue. Although it is not based on OkHttp, I modified it for my code, but no profit.

Please help me figure out the issue and thanks in advance.

Upvotes: 1

Views: 812

Answers (2)

poortechworker
poortechworker

Reputation: 669

onResponse does not wait to get the whole response and if your response is quite big/ or you are not having a good internet connection, then it may be a problem.

I used this and it is working for me.

// get the full response
response = client.newCall(request).execute();

and then continue with your code. Hope it helps.

Upvotes: 1

Alexander R.
Alexander R.

Reputation: 1756

For slow connection try to change default timeouts:

client.setConnectTimeout(15, TimeUnit.SECONDS);
client.setReadTimeout(15, TimeUnit.SECONDS);

Upvotes: 0

Related Questions