33

Here it takes so much time to get data from json. When deleted and again installed it will get json within 1 min and when i again click button for json it takes so much time and still data is not getting in listview

Here is my exception code

E/JSONDemo: IOExceptiojava.net.SocketTimeoutException
  at java.net.PlainSocketImpl.read(PlainSocketImpl.java:493)
  at java.net.PlainSocketImpl.-wrap0(PlainSocketImpl.java)
  at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:242)
  at okio.Okio$2.read(Okio.java:140)
  at okio.AsyncTimeout$2.read(AsyncTimeout.java:238)
  at okio.RealBufferedSource.indexOf(RealBufferedSource.java:325)
  at okio.RealBufferedSource.indexOf(RealBufferedSource.java:314)
  at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:210)
  at okhttp3.internal.http.Http1xStream.readResponse(Http1xStream.java:184)
  at okhttp3.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:125)
  at okhttp3.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:775)
  at okhttp3.internal.http.HttpEngine.access$200(HttpEngine.java:86)
  at okhttp3.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:760)
  at okhttp3.internal.http.HttpEngine.readResponse(HttpEngine.java:613)
  at okhttp3.RealCall.getResponse(RealCall.java:244)
  at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
  at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
  at okhttp3.RealCall.access$100(RealCall.java:30)
  at okhttp3.RealCall$AsyncCall.execute(RealCall.java:127)
  at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
  at java.lang.Thread.run(Thread.java:818)

here is a json code in java file:

progress = ProgressDialog.show(MainActivity.this, "dialog title", "dialog message", true);
Toast.makeText(MainActivity.this, "ok", Toast.LENGTH_LONG).show();

    if (isNetworkAvailable()) {

        String url = "ConstantValue.URL";
        RequestBody formBody = new FormBody.Builder()
                .add(employeeId, value)
                .build();

        try {
            post(url, formBody, new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("JSONDemo", "IOException", e);
                }

                @Override
                public void onResponse(final Call call, final Response response) throws IOException {
                    String JSON = response.body().string();
                     Log.e("res", " " + JSON);
                     try {
                         JSONObject jsonObj = new JSONObject(JSON);
                         JSONArray resultarr = jsonObj.getJSONArray("result");
                         final JSONArray resultarr1 = jsonObj.getJSONArray("result1");

                         if (resultarr1.length() == 0) {
                             showAlertDialog("API", "Data Unavailable");
                         } else {

                             for (int i = 0; i < resultarr1.length(); i++) {

                                 Employee emp = new Employee();
                                 JSONObject result1obj = resultarr1.getJSONObject(i);
                                 String result1Id = result1obj.getString("ID");
                                 String result1Name = result1obj.getString("NAME");
                                 String result1Value = result1obj.getString("VALUE");
                                 Log.e("result", " " + result1Name);
                                 Log.e("result", " " + result1Value);
                                 Log.e("result", " " + result1Id);
                                 emp.setValue(result1Value);
                                 emp.setName(result1Name);
                                 emp.setId(result1Id);

                                 arr.add(emp);

                             }
                         }

                         runOnUiThread(new Runnable() {
                             @Override
                             public void run() {

                                 // you can access all the UI componenet
                                 if (progress.isShowing()) 
                                     progress.dismiss();
                                 cu.notifyDataSetChanged();
                             }
                         });
                     } catch (Exception e) {
                         Log.e("JSONDemo", "onResponse", e);
                         showAlertDialog("API","Something went wrong");
                     }

                 }
             });

         } catch (Exception e) {
             Log.e("JSONDemo", "Post Exception", e);
         }

     } else {
         Toast.makeText(MainActivity.this, "Internet not available", Toast.LENGTH_LONG).show();
     }
}

Other codes:

private final OkHttpClient client = new OkHttpClient();


Call post(String url, RequestBody formBody, Callback callback) throws IOException {

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

    client.setConnectTimeout(30, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    client.setWriteTimeout(30, TimeUnit.SECONDS);

    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
Abhi
  • 385
  • 1
  • 4
  • 13

2 Answers2

56

IOException java.net.SocketTimeoutException occurs in the following conditions:

  1. Server is slow and default timeout is less. so just put timeout value according to you.
  2. Server is working fine but timeout value is for less time. So change the timeout value, like below code snippet.
OkHttpClient client = new OkHttpClient();

client.setConnectTimeout(30, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);

If you are using OkHttp 3 then you must do it using the builder.

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(30, TimeUnit.SECONDS); 
builder.readTimeout(30, TimeUnit.SECONDS); 
builder.writeTimeout(30, TimeUnit.SECONDS); 
client = builder.build();
Ryan M
  • 18,333
  • 31
  • 67
  • 74
DroidNinja
  • 997
  • 1
  • 8
  • 9
  • i had edited but here I am not getting client.setConnectTimeout(30, TimeUnit.SECONDS);client.setReadTimeout(30, TimeUnit.SECONDS);client.setWriteTimeout(30, TimeUnit.SECONDS); – Abhi Oct 21 '16 at 08:17
  • 4
    @Abhi If you are using okhttp3 then you must do it using the builder. OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(30, TimeUnit.SECONDS); builder.readTimeout(30, TimeUnit.SECONDS); builder.writeTimeout(30, TimeUnit.SECONDS); client = builder.build(); – Cognoscis Nov 24 '16 at 08:38
  • @Cognoscis I think you should submit an answer with that info/code. – ban-geoengineering Jul 19 '17 at 10:28
  • Is it wrong to do it like this? `OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .build();` – Kevin F. Sep 10 '18 at 12:54
  • Before set timeout I get "java.net.SocketTimeoutException: timeout" about 500 times. After I set var okHttpClient = OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) - now I get java.net.SocketTimeoutException: timeout 15 times. How I can fix this? To not fire java.net.SocketTimeoutException ? – Alexei Feb 20 '19 at 13:12
  • 1
    this answer will set more timeout but not fix the crash, you should handle the exception where it happens and notify the UI with a retry button – Gastón Saillén Nov 13 '19 at 22:04
  • Not working for me. Added timeout, but still getting timeout error. But, if I request thru a browser in my phone, it goes thru fine. I think OkHttpClient has an issue. – GeneCode Feb 25 '22 at 11:26
6

Only adding this won't solve your problem:

OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)

If you are using Kotlin + Retrofit + Coroutines then just use try and catch for network operations like,

viewModelScope.launch(Dispatchers.IO) {
        try {
            val userListResponseModel = apiEndPointsInterface.usersList()
            returnusersList(userListResponseModel)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

Where, Exception is type of kotlin and not of java.lang

This will handle every exception like,

  1. HttpException
  2. SocketTimeoutException
  3. FATAL EXCEPTION: DefaultDispatcher etc

Here is my usersList() function

@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel
Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82