App crashing on android 11 : java.lang.ExceptionInInitializerError

The same following code runs flawlessly in all android versions except in android 11. In android 11 or API 30, our app is crashing and doesn’t even open at all. We are using request network API to perform GET, POST operations in our app.

Here is a log :

--------- beginning of crash
2021-07-12 02:03:52.995 3158-3158/com.oryx.drives E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.oryx.drives, PID: 3158
    java.lang.ExceptionInInitializerError
        at okhttp3.internal.tls.CertificateChainCleaner$Companion.get(CertificateChainCleaner.kt:42)
        at okhttp3.OkHttpClient$Builder.sslSocketFactory(OkHttpClient.kt:718)
        at com.oryx.drives.RequestNetworkController.getClient(RequestNetworkController.java:77)
        at com.oryx.drives.RequestNetworkController.execute(RequestNetworkController.java:154)
        at com.oryx.drives.RequestNetwork.startRequestNetwork(RequestNetwork.java:45)
        at com.oryx.drives.MainActivity$15$1.run(MainActivity.java:277)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.IllegalStateException: Expected Android API level 21+ but was 30
        at okhttp3.internal.platform.AndroidPlatform$Companion.buildIfSupported(AndroidPlatform.kt:370)
        at okhttp3.internal.platform.Platform$Companion.findPlatform(Platform.kt:204)
        at okhttp3.internal.platform.Platform$Companion.access$findPlatform(Platform.kt:178)
        at okhttp3.internal.platform.Platform.<clinit>(Platform.kt:179)
        at okhttp3.internal.tls.CertificateChainCleaner$Companion.get(CertificateChainCleaner.kt:42) 
        at okhttp3.OkHttpClient$Builder.sslSocketFactory(OkHttpClient.kt:718) 
        at com.oryx.drives.RequestNetworkController.getClient(RequestNetworkController.java:77) 
        at com.oryx.drives.RequestNetworkController.execute(RequestNetworkController.java:154) 
        at com.oryx.drives.RequestNetwork.startRequestNetwork(RequestNetwork.java:45) 
        at com.oryx.drives.MainActivity$15$1.run(MainActivity.java:277) 
        at android.os.Handler.handleCallback(Handler.java:938) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:223) 
        at android.app.ActivityThread.main(ActivityThread.java:7656) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
2021-07-12 02:03:53.421 3158-3158/com.oryx.drives I/Process: Sending signal. PID: 3158 SIG: 9

MainActivity.java :

package com.oryx.drives;

import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.dynamiclinks.FirebaseDynamicLinks;
import com.google.firebase.dynamiclinks.PendingDynamicLinkData;

import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private Timer _timer = new Timer();

    private String typeace = "";
    private String fontError = "";
    private String error = "";

    private LinearLayout linear1;
    private ImageView imageview1;
    private LinearLayout linear3;
    private LinearLayout linear4;
    private TextView textview3;
    private ImageView imageview2;
    private TextView textview2;

    private TimerTask timer;
    private Intent login = new Intent();
    private RequestNetwork rq;
    private RequestNetwork.RequestListener _rq_request_listener;
    private FirebaseAuth auth;
    private OnCompleteListener<Void> auth_updateEmailListener;
    private OnCompleteListener<Void> auth_updatePasswordListener;
    private OnCompleteListener<Void> auth_emailVerificationSentListener;
    private OnCompleteListener<Void> auth_deleteUserListener;
    private OnCompleteListener<Void> auth_updateProfileListener;
    private OnCompleteListener<AuthResult> auth_phoneAuthListener;
    private OnCompleteListener<AuthResult> auth_googleSignInListener;
    private OnCompleteListener<AuthResult> _auth_create_user_listener;
    private OnCompleteListener<AuthResult> _auth_sign_in_listener;
    private OnCompleteListener<Void> _auth_reset_password_listener;
    private ObjectAnimator anim = new ObjectAnimator();
    private AlertDialog.Builder d;
    private Intent i;



        @Override
        protected void onCreate (Bundle _savedInstanceState){
        super.onCreate(_savedInstanceState);
        setContentView(R.layout.main);
        com.google.firebase.FirebaseApp.initializeApp(this);

        initialize(_savedInstanceState);
        try{
            initializeLogic();
        }
        catch (Exception e){

            d.setMessage(e.getMessage());
            d.setIcon(R.drawable.warning);
            d.setPositiveButton("Report", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface _dialog, int _which) {
                    i.setClass(getApplicationContext(), FeedbackActivity.class);
                    i.putExtra("error", getIntent().getStringExtra(e.getMessage()));
                    startActivity(i);
                }
            }); d.setCancelable(false);
            d.create().show();
        }
        getDynamicLinkFromFirebase();


        // checking if the uri is null or not.

    }

        private void getDynamicLinkFromFirebase () {
        FirebaseDynamicLinks.getInstance()
                .getDynamicLink(getIntent())
                .addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
                    @Override
                    public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
                        // Get deep link from result (may be null if no link is found)
                        Uri deepLink = null;
                        if (pendingDynamicLinkData != null) {
                            deepLink = pendingDynamicLinkData.getLink();
                        }


                        // Handle the deep link. For example, open the linked
                        // content, or apply promotional credit to the user's
                        // account.
                        // ...

                        // ...
                    }
                })

                .addOnFailureListener(this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {

                    }
                });
    }

        private void initialize (Bundle _savedInstanceState){

        linear1 = (LinearLayout) findViewById(R.id.linear1);
        imageview1 = (ImageView) findViewById(R.id.imageview1);
        linear3 = (LinearLayout) findViewById(R.id.linear3);
        linear4 = (LinearLayout) findViewById(R.id.linear4);
        textview3 = (TextView) findViewById(R.id.textview3);
        imageview2 = (ImageView) findViewById(R.id.imageview2);
        textview2 = (TextView) findViewById(R.id.textview2);
        rq = new RequestNetwork(this);
        auth = FirebaseAuth.getInstance();

        _rq_request_listener = new RequestNetwork.RequestListener() {
            @Override
            public void onResponse(String tag, String response) {
                final String _tag = tag;
                final String _message = response;

                if ((FirebaseAuth.getInstance().getCurrentUser() != null)) {
                    login.setClass(getApplicationContext(), HomeActivity.class);
                    login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(login);
                    finish();
                } else {
                    login.setClass(getApplicationContext(), AppintroActivity.class);
                    login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(login);
                    finish();
                }
            }

            @Override
            public void onErrorResponse(String _param1, String _param2) {
                final String _tag = _param1;
                final String _message = _param2;
                linear3.setVisibility(View.GONE);
                linear4.setVisibility(View.VISIBLE);
            }
        };

        auth_updateEmailListener = new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> _param1) {
                final boolean _success = _param1.isSuccessful();
                final String _errorMessage = _param1.getException() != null ? _param1.getException().getMessage() : "";

            }
        };

        auth_updatePasswordListener = new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> _param1) {
                final boolean _success = _param1.isSuccessful();
                final String _errorMessage = _param1.getException() != null ? _param1.getException().getMessage() : "";

            }
        };

        auth_emailVerificationSentListener = new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> _param1) {
                final boolean _success = _param1.isSuccessful();
                final String _errorMessage = _param1.getException() != null ? _param1.getException().getMessage() : "";

            }
        };

        auth_deleteUserListener = new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> _param1) {
                final boolean _success = _param1.isSuccessful();
                final String _errorMessage = _param1.getException() != null ? _param1.getException().getMessage() : "";

            }
        };

        auth_phoneAuthListener = new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(Task<AuthResult> task) {
                final boolean _success = task.isSuccessful();
                final String _errorMessage = task.getException() != null ? task.getException().getMessage() : "";

            }
        };

        auth_updateProfileListener = new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> _param1) {
                final boolean _success = _param1.isSuccessful();
                final String _errorMessage = _param1.getException() != null ? _param1.getException().getMessage() : "";

            }
        };

        auth_googleSignInListener = new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(Task<AuthResult> task) {
                final boolean _success = task.isSuccessful();
                final String _errorMessage = task.getException() != null ? task.getException().getMessage() : "";

            }
        };

        _auth_create_user_listener = new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(Task<AuthResult> _param1) {
                final boolean _success = _param1.isSuccessful();
                final String _errorMessage = _param1.getException() != null ? _param1.getException().getMessage() : "";

            }
        };

        _auth_sign_in_listener = new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(Task<AuthResult> _param1) {
                final boolean _success = _param1.isSuccessful();
                final String _errorMessage = _param1.getException() != null ? _param1.getException().getMessage() : "";

            }
        };

        _auth_reset_password_listener = new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> _param1) {
                final boolean _success = _param1.isSuccessful();

            }
        };
    }
        private void initializeLogic () {
        anim.setTarget(imageview1);
        anim.setPropertyName("translationY");
        anim.setFloatValues((float) (-500), (float) (0));
        anim.setDuration((int) (1500));
        anim.setInterpolator(new BounceInterpolator());
        anim.start();
        timer = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        rq.startRequestNetwork(RequestNetworkController.GET, "https://www.google.com", "A", _rq_request_listener);
                    }
                });
            }
        };
        _timer.schedule(timer, (int) (500));
        linear4.setVisibility(View.INVISIBLE);
    }

        @Override
        protected void onActivityResult ( int _requestCode, int _resultCode, Intent _data){

        super.onActivityResult(_requestCode, _resultCode, _data);

        switch (_requestCode) {

            default:
                break;
        }
    }

        @Deprecated
        public void showMessage (String _s){
        Toast.makeText(getApplicationContext(), _s, Toast.LENGTH_SHORT).show();
    }

        @Deprecated
        public int getLocationX (View _v){
        int _location[] = new int[2];
        _v.getLocationInWindow(_location);
        return _location[0];
    }

        @Deprecated
        public int getLocationY (View _v){
        int _location[] = new int[2];
        _v.getLocationInWindow(_location);
        return _location[1];
    }

        @Deprecated
        public int getRandom ( int _min, int _max){
        Random random = new Random();
        return random.nextInt(_max - _min + 1) + _min;
    }

        @Deprecated
        public ArrayList<Double> getCheckedItemPositionsToArray (ListView _list){
        ArrayList<Double> _result = new ArrayList<Double>();
        SparseBooleanArray _arr = _list.getCheckedItemPositions();
        for (int _iIdx = 0; _iIdx < _arr.size(); _iIdx++) {
            if (_arr.valueAt(_iIdx))
                _result.add((double) _arr.keyAt(_iIdx));
        }
        return _result;
    }

        @Deprecated
        public float getDip ( int _input){
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, _input, getResources().getDisplayMetrics());
    }

        @Deprecated
        public int getDisplayWidthPixels () {
        return getResources().getDisplayMetrics().widthPixels;
    }

        @Deprecated
        public int getDisplayHeightPixels () {
        return getResources().getDisplayMetrics().heightPixels;
    }


}


RequestNetwork.java :

package com.oryx.drives;

import android.app.Activity;

import java.util.HashMap;

public class RequestNetwork {
private HashMap<String, Object> params = new HashMap<>();
private HashMap<String, Object> headers = new HashMap<>();

private final Activity activity;

private int requestType = 0;

public RequestNetwork(Activity activity) {
this.activity = activity;
}

public void setHeaders(HashMap<String, Object> headers) {
this.headers = headers;
}

public void setParams(HashMap<String, Object> params, int requestType) {
this.params = params;
this.requestType = requestType;
}

public HashMap<String, Object> getParams() {
return params;
}

public HashMap<String, Object> getHeaders() {
return headers;
}

public Activity getActivity() {
return activity;
}

public int getRequestType() {
return requestType;
}

public void startRequestNetwork(String method, String url, String tag, RequestListener requestListener) {
RequestNetworkController.getInstance().execute(this, method, url, tag, requestListener);
}

public interface RequestListener {
void onResponse(String tag, String response);
void onErrorResponse(String tag, String message);
}
}

RequestNetworkController.java :

package com.oryx.drives;

import com.google.gson.Gson;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RequestNetworkController {
public static final String GET      = "GET";
public static final String POST     = "POST";
public static final String PUT      = "PUT";
public static final String DELETE   = "DELETE";

public static final int REQUEST_PARAM = 0;
public static final int REQUEST_BODY  = 1;

private static final int SOCKET_TIMEOUT = 15000;
private static final int READ_TIMEOUT   = 25000;

protected OkHttpClient client;

private static RequestNetworkController mInstance;

public static synchronized RequestNetworkController getInstance() {
if(mInstance == null) {
mInstance = new RequestNetworkController();
}
return mInstance;
}

private OkHttpClient getClient() {
if (client == null) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();

try {
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws CertificateException {
}

@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws CertificateException {
}

@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};

final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.connectTimeout(SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
builder.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
builder.writeTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
}

client = builder.build();
}

return client;
}

public void execute(final RequestNetwork requestNetwork, String method, String url, final String tag, final RequestNetwork.RequestListener requestListener) {
Request.Builder reqBuilder = new Request.Builder();
Headers.Builder headerBuilder = new Headers.Builder();

if(requestNetwork.getHeaders().size() > 0) {
HashMap<String, Object> headers = requestNetwork.getHeaders();

for(HashMap.Entry<String, Object> header : headers.entrySet()) {
headerBuilder.add(header.getKey(), String.valueOf(header.getValue()));
}
}

try {
if (requestNetwork.getRequestType() == REQUEST_PARAM) {
if (method.equals(GET)) {
HttpUrl.Builder httpBuilder;

try {
httpBuilder = HttpUrl.parse(url).newBuilder();
} catch (NullPointerException ne) {
throw new NullPointerException("unexpected url: " + url);
}

if (requestNetwork.getParams().size() > 0) {
HashMap<String, Object> params = requestNetwork.getParams();

for (HashMap.Entry<String, Object> param : params.entrySet()) {
httpBuilder.addQueryParameter(param.getKey(), String.valueOf(param.getValue()));
}
}

reqBuilder.url(httpBuilder.build()).headers(headerBuilder.build()).get();
} else {
FormBody.Builder formBuilder = new FormBody.Builder();
if (requestNetwork.getParams().size() > 0) {
HashMap<String, Object> params = requestNetwork.getParams();

for (HashMap.Entry<String, Object> param : params.entrySet()) {
formBuilder.add(param.getKey(), String.valueOf(param.getValue()));
}
}

RequestBody reqBody = formBuilder.build();

reqBuilder.url(url).headers(headerBuilder.build()).method(method, reqBody);
}
} else {
RequestBody reqBody = RequestBody.create(okhttp3.MediaType.parse("application/json"), new Gson().toJson(requestNetwork.getParams()));

if (method.equals(GET)) {
reqBuilder.url(url).headers(headerBuilder.build()).get();
} else {
reqBuilder.url(url).headers(headerBuilder.build()).method(method, reqBody);
}
}

Request req = reqBuilder.build();

getClient().newCall(req).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
requestNetwork.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
requestListener.onErrorResponse(tag, e.getMessage());
}
});
}

@Override
public void onResponse(Call call, final Response response) throws IOException {
final String responseBody = response.body().string().trim();
requestNetwork.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
requestListener.onResponse(tag, responseBody);
}
});
}
});
} catch (Exception e) {
requestListener.onErrorResponse(tag, e.getMessage());
}
}
}

Please help us to solve this error. Thanks in advance:)

Answer

thats a bug in OkHttp library, upgrade it to at least 4.9.0 version (preferably newest one)