1
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    t= (TextView)findViewById(R.id.textView);
    s.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String locationProvider = LocationManager.NETWORK_PROVIDER;
            Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
            double lat = lastKnownLocation.getLatitude();
            double lon = lastKnownLocation.getLongitude();
           t.setText(""+lat+""+lon);
        }
    });

This is my code and I'm trying to get approximate location of user. But i don't know why i'm getting null object reference exception. Is this the right way of doing? can anyone help me with getting user location with network? Should I add request location updates method to get last known location?

irudaya rajasekar
  • 924
  • 1
  • 8
  • 16
  • Take a look at the answer to this question, it has everything you need: [Error invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference](http://stackoverflow.com/questions/32290045/error-invoke-virtual-method-double-android-location-location-getlatitude-on) – Daniel Nugent Sep 06 '15 at 07:35
  • I think you have not added permission in manifest file check that out, would you like to get the address of the person along with location? – penta Sep 06 '15 at 08:24
  • @penta I have added fine location and coarse location permissions in the manifest. Even if i use network provider the program is not returning the location unless the gps is switched on. I don't get it why it requests to switch on the gps when i use network provider. – irudaya rajasekar Sep 06 '15 at 08:28
  • ummmm...can you paste logcat ? or just debug at line double lat = lastKnownLocation.getLatitude(); double lon = lastKnownLocation.getLongitude(); and see the value – penta Sep 06 '15 at 08:30
  • Check this answer out http://stackoverflow.com/questions/15634294/get-accurate-current-location-from-network-provider maybe best solution for you – penta Sep 06 '15 at 08:32
  • check this also if it helps http://javapapers.com/android/android-location-using-gps-network-provider/ – penta Sep 06 '15 at 08:36
  • @penta Ialso tried referring that link from javapapers.com. But couldn't make it work. any other ideas. – irudaya rajasekar Sep 06 '15 at 08:39
  • are you using Android Studio ? if yes when u get the error in android console, press the blue link, it will exactly tell you where the app is crashing, then tell me which line it is, and if possible plz put logcat – penta Sep 06 '15 at 08:43
  • @penta can you help me with switching on gps automatically without redirecting the user to the settings page? – irudaya rajasekar Sep 06 '15 at 09:05
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/88917/discussion-between-penta-and-irudaya-rajasekar). – penta Sep 06 '15 at 09:09

0 Answers0