0

Hello I want to get Accurate location so that i have used following link

What is the simplest and most robust way to get the user's current location in Android?

below is the code from that site :

      LocationResult locationResult = new LocationResult(){
    @Override
    public void gotLocation(Location location){
        //Got the location!
    }
   };

MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);

Now in LocationResult Class i have modified it and want to show LOCATION's in textview so i have write below code

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LocationResult locationResult = new LocationResult(){
        @Override
        public void gotLocation(Location location){
            TextView txtValue = (TextView)findViewById(R.id.txtValue);
            txtValue.setText("LATITUDE : - "+location.getLatitude()+"\n\n LONGITUDE :- "+location.getLongitude()+"\n\n ALTITUDE :- "+location.getAltitude());
        }
    };
    myLocation = new MyLocation();
    myLocation.getLocation(this, locationResult);

}

but in that i am getting exception like

below is my logcat

 10-04 17:06:35.699: E/AndroidRuntime(5733): FATAL EXCEPTION: Timer-0
 10-04 17:06:35.699: E/AndroidRuntime(5733): java.lang.NullPointerException
 10-04 17:06:35.699: E/AndroidRuntime(5733):    at    com.example.gps_accurate_data.MainActivity$1.gotLocation(MainActivity.java:22)
 10-04 17:06:35.699: E/AndroidRuntime(5733):    at com.example.gps_accurate_data.MyLocation$GetLastLocation.run(MyLocation.java:119)
 10-04 17:06:35.699: E/AndroidRuntime(5733):    at java.util.Timer$TimerImpl.run(Timer.java:284)
Community
  • 1
  • 1
Siddhpura Amit
  • 14,534
  • 16
  • 91
  • 150

2 Answers2

1

If you look at the link you provided, when the device has attempted to get the location, it will run the code;

if(gps_loc!=null){
    locationResult.gotLocation(gps_loc);
    return;
}

if(net_loc!=null){
    locationResult.gotLocation(net_loc);
    return;
}

locationResult.gotLocation(null);

which means it may very well call you with a location set to null if it fails to get a location. You need to check for that.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0

Declare in your activity at the top: TextView txtValue;

Then in your onCreate(): txtValue = (TextView)findViewById(R.id.txtValue);

if(location != null){
    txtValue.setText("LATITUDE : - "+location.getLatitude()+"\n\n LONGITUDE :-    "+location.getLongitude()+"\n\n ALTITUDE :- "+location.getAltitude());
}
Carnal
  • 21,744
  • 6
  • 60
  • 75