Home » Android » IllegalArgumentException when instantiating HttpClient in Android

IllegalArgumentException when instantiating HttpClient in Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

In the google play console, I can see crash reports from users who complain because my application crashes just after starting. The cause seems to be an exception thrown when instantiating HttpClient. What am I doing wrong?

Here is an extract from the stack trace :

java.lang.IllegalArgumentException: androidApplicationContext must be not null!
at org.apache.http.impl.client.naf.gba.connector.GbaServiceConnectorSynchronizedSingleton.instance(GbaServiceConnectorSynchronizedSingleton.java:76)
at org.apache.http.impl.client.naf.gba.shared.KeeperManager.init(KeeperManager.java:68)
at org.apache.http.impl.client.naf.auth.NafHttpAuthStrategyDefault.initSharedResources(NafHttpAuthStrategyDefault.java:119)
at org.apache.http.impl.client.naf.auth.NafHttpAuthStrategyDefault.(NafHttpAuthStrategyDefault.java:95)
at org.apache.http.impl.client.AbstractHttpClient.(AbstractHttpClient.java:168)
at org.apache.http.impl.client.DefaultHttpClient.(DefaultHttpClient.java:113)
How to&Answers:

The solutions

  1. Use HttpURLConnection instead of HttpClient. According to the Android developer’s blog, it is the best choice: http://android-developers.blogspot.fr/2011/09/androids-http-clients.html.
  2. Create an instance of HttpClient in the main thread of your application, as soon as possible, for instance in its onCreate method.

The cause

Some android devices, like the T-Mobile MyTouch Q, use a custom implementation of the Apache HttpClient library. On such devices, creating the first HttpClient of your application not in the main thread will result in an exception being thrown :

java.lang.IllegalArgumentException: androidApplicationContext must be not null!

In my specific case, it was thrown in GbaServiceConnectorSynchronizedSingleton.java, line 76, because of an analytics library.

How to reproduce

Here is a link to a test case allowing to reproduce the issue:
https://gist.github.com/Bastoche/6133227