Search code examples
androidandroid-gps

How to use isProviderEnabled so it isn't highlighted in yellow with warning?


I am trying to check if GPS is switched on. I want to peform this check before any other code runs. I have tried using many code examples, but every time and every where I use isProviderEnabled it highlights in yellow and warns of a potential NullPointerException. How can I remove this warning, and where should the code be placed?

final LocationManager manager = (LocationManager) 
          getSystemService(Context.LOCATION_SERVICE);
  if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
     /* some code   */
  }

screenshot of error and highlighting


Solution

  • before using LocationManager check if it's non-null wrap the code block like this

    final LocationManager manager = (LocationManager) 
              getSystemService(Context.LOCATION_SERVICE);
      if(manager != null){
         if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
          /* some code   */
      }
    }