views:

476

answers:

4

I have an activity which shows some List entries. When I click on a list item my app checks which connection type is available ("WIF" or "MOBILE"), through NetworkInfo.getTypeName(). As soon as I call this method I get a NullpointerException. Why?

I tested this on the emulator, cause my phone is currently not available (it's broken...). I assume this is the problem? This is the only explanation that I have, if that's not the case I have no idea why this would be null.

Here's some code snippet:

public class VideoList extends ListActivity{
 ...
 public void onCreate(Bundle bundle){
  final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  ...
  listview.setOnItemClickListener(new OnItemClickListener(){
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ...
    NetworkInfo ni = cm.getActiveNetworkInfo();
    String connex = ni.getTypeName(); //Nullpointer exception here
    if(connex.equals("WIFI")doSomething();
   }
  });
 }
}
+1  A: 

The call getActiveNetworkInfo() can return null if there is no active network and you need to check for that. Here's the source code from here.

/**
 * Return NetworkInfo for the active (i.e., connected) network interface.
 * It is assumed that at most one network is active at a time. If more
 * than one is active, it is indeterminate which will be returned.
 * @return the info for the active network, or {@code null} if none is active
 */
public NetworkInfo getActiveNetworkInfo() {
    enforceAccessPermission();
    for (NetworkStateTracker t : mNetTrackers) {
        NetworkInfo info = t.getNetworkInfo();
        if (info.isConnected()) {
            return info;
        }
    }
    return null;
}

Note in particular the javadoc: "return the info for the active network, or null if none is active".

Mark Byers
+2  A: 

I understand that you have connection and the emulator is able to use it but then the call to getActiveNetworkInfo() returns you null anyway, and that is why you are puzzled.

Well, your suspicions were right: getActiveNetworkInfo() does not work on the emulator and always returns null.

Edu Zamora
A: 

I found that if you press F8 to turn 3G on in the emulator, cm.getActiveNetworkInfo() then returns a non-null usable NetworkInfo handle.

bwin
A: 

Instead of

if(connex.equals("WIFI") doSomething();

try

if("WIFI".equals(connex)) doSomething();
Seymour Cakes

related questions