One of the functions in my app sends data over the internet. Before attempting to send the data, I check whether a connection exists:
private boolean isConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo.State val1 = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
NetworkInfo.State val2 = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
return NetworkInfo.State.CONNECTED.equals(val1) || NetworkInfo.State.CONNECTED.equals(val2);
}
This worked perfectly fine on emulator and a couple of real devices I tested on. Then I received an error report from the client, which on investigation turned out to be a NullPointerException
on getState
line for TYPE_MOBILE
.
Apparently, connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
returned null
on the device that didn't have 3G (a WiFi-only tablet). Although I did test on a Nexus 7 emulator, I didn't get this error.
Hence, what I'm interested in is creating an AVD that explicitly does not have 3G (i.e. an AVD for a WiFi-only device) so that I could investigate/test such scenarios. I haven't found anything in the emulator options, but maybe I'm just looking in a wrong place. Is this even possible?
I don't believe there is a simple solution to this. In the mean time, I adopted my code to look like this:
private boolean isConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info1 = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo info2 = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo.State val1 = (info1 == null ? null : info1.getState());
NetworkInfo.State val2 = (info2 == null ? null : info2.getState());
return (info1 != null && NetworkInfo.State.CONNECTED.equals(val1)) || (info2 != null && NetworkInfo.State.CONNECTED.equals(val2));
}
This takes care of null
values when an interface is not present.