Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, NetworkInfo.getTypeName(), NullpointerException

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();
   }
  });
 }
}
like image 460
user283494 Avatar asked Mar 14 '10 19:03

user283494


2 Answers

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".

like image 129
Mark Byers Avatar answered Oct 20 '22 01:10

Mark Byers


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.

like image 21
Edu Zamora Avatar answered Oct 19 '22 23:10

Edu Zamora