ClassCastException when getting signalstrength in android

Thursday, July 10, 2014

In my code, I get the type of connection i.e LTE, CDMA or HSPA etc. from the telephonyManager in Android and then accordingly cast it. An example is shown below.

switch(getCellInfoType()) {
(CellInfoLte) ...
(CellInfoCdma) ...

In an area of really bad reception, where the phone continuously jumps between LTE and 3G, I get a ClassCastException. This is due to the fact that once I get the type of connection from the telephonyManager and then try to cast it (at this time it flops) I get the exception as it no longer the same instance.

For example, I get type LTE before entering the switch block, after which it falls to 3G. As I have the variable set to type LTE, I try to cast it to LTE which then throws the ClassCastException. My solution is just to catch the exception in this case and carry on (essentialy discarding this call as being faulty). Is this the cleanest way of dealing with this issue or is it possible to be able to avoid this altogether?