Question

I wanted to calculate the distance the user has walked no matter how little during an activity (such as running) using GPS. Even if GPS is inaccurate, i want a function that can calculate accurate distance.

In my code below, when I comment out my onLocationChanged code, my app did not crash. but the two TextView and Toast did not display the current location. When I include my onLocationChanged code, my app on my phone crashes a while after. I could not figure out the error.

Could someone tell me whether or not the way I am using Location.distanceBetween is correct? I felt something is wrong but do not know what.

updated Java code

public class MainActivity extends Activity{
    protected LocationManager locationManager;
    EditText userNumberInput;
    EditText userTextInput;
    TextView distanceText;
    TextView latitude;
    TextView longitude;
    double lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4;
    long dist;
    float[] result;
    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        distanceText=(TextView)findViewById(R.id.Distance);
        latitude=(TextView)findViewById(R.id.currentLat);
        longitude=(TextView)findViewById(R.id.currentLon);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, myLocationListener); 
        Log.d("GPS Enabled", "GPS Enabled");  
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = locationManager.getBestProvider(criteria, true);
        Location location=locationManager.getLastKnownLocation(provider);

        //Display current location in Toast
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_LONG).show();

        //Display current location in textview  
        latitude.setText("Current Latitude: " + String.valueOf(location.getLatitude())); 
        longitude.setText("Current Longitude: " + String.valueOf(location.getLongitude()));
        lat1 = location.getLatitude();
        lon1 = location.getLongitude();
        lat3 = 123.0;
        lon3 = 234.0;
        lat4 = 123.0;
        lon4 = 224.0;
        float[] results = new float[1]; 
        Location.distanceBetween(lat3, lon3, lat4, lon4, results);
        System.out.println("Distance is: " + results[0]);
    }

    private CharSequence ToString(double latitude2) {
        // TODO Auto-generated method stub
        return null;
    }

    LocationListener myLocationListener = new LocationListener() 
    {
        public void onLocationChanged(Location loc2) 
        {

        }
    }

    public void onProviderDisabled(String provider)
    {
        Toast.makeText(MainActivity.this,
                "GPS is disabled",
                Toast.LENGTH_LONG).show();
    }
    public void onProviderEnabled(String provider)
    {
        Toast.makeText(MainActivity.this,
                "GPS is enabled",
                Toast.LENGTH_LONG).show();
    }
    public void onStatusChanged(String provider, int status,
            Bundle extras)
    {
        Toast.makeText(MainActivity.this,
                "GPS status changed",
                Toast.LENGTH_LONG).show();
    }

    };

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(myLocationListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, myLocationListener);

    }
}

the LogCat

01-29 15:37:24.070: I/Process(20836): Sending signal. PID: 20836 SIG: 9
01-29 15:37:38.305: D/GPS Enabled(24434): GPS Enabled
01-29 15:37:38.305: D/AndroidRuntime(24434): Shutting down VM
01-29 15:37:38.305: W/dalvikvm(24434): threadid=1: thread exiting with uncaught exception (group=0x40fe32a0)
01-29 15:37:38.305: E/AndroidRuntime(24434): FATAL EXCEPTION: main
01-29 15:37:38.305: E/AndroidRuntime(24434): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.validationapp/com.example.validationapp.MainActivity}: java.lang.NullPointerException
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.os.Looper.loop(Looper.java:137)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.main(ActivityThread.java:4898)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at java.lang.reflect.Method.invokeNative(Native Method)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at java.lang.reflect.Method.invoke(Method.java:511)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at dalvik.system.NativeStart.main(Native Method)
01-29 15:37:38.305: E/AndroidRuntime(24434): Caused by: java.lang.NullPointerException
01-29 15:37:38.305: E/AndroidRuntime(24434):    at com.example.validationapp.MainActivity.onCreate(MainActivity.java:57)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.Activity.performCreate(Activity.java:5206)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
01-29 15:37:38.305: E/AndroidRuntime(24434):    ... 11 more
01-29 15:38:51.680: D/GPS Enabled(28843): GPS Enabled
01-29 15:38:51.685: D/AndroidRuntime(28843): Shutting down VM
01-29 15:38:51.685: W/dalvikvm(28843): threadid=1: thread exiting with uncaught exception (group=0x40fe32a0)
01-29 15:38:51.685: E/AndroidRuntime(28843): FATAL EXCEPTION: main
01-29 15:38:51.685: E/AndroidRuntime(28843): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.validationapp/com.example.validationapp.MainActivity}: java.lang.NullPointerException
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.os.Looper.loop(Looper.java:137)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.main(ActivityThread.java:4898)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at java.lang.reflect.Method.invokeNative(Native Method)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at java.lang.reflect.Method.invoke(Method.java:511)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at dalvik.system.NativeStart.main(Native Method)
01-29 15:38:51.685: E/AndroidRuntime(28843): Caused by: java.lang.NullPointerException
01-29 15:38:51.685: E/AndroidRuntime(28843):    at com.example.validationapp.MainActivity.onCreate(MainActivity.java:57)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.Activity.performCreate(Activity.java:5206)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
01-29 15:38:51.685: E/AndroidRuntime(28843):    ... 11 more

i run again but it did not crash or display any output. the log cat is

01-29 16:22:12.795: D/GPS Enabled(28011): GPS Enabled
01-29 16:22:12.800: I/System.out(28011): Distance is: 607178.94
01-29 16:22:12.820: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.820: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.820: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.915: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.915: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.920: D/SensorManager(28011): registerListener :: handle = 0  name= LSM330DLC 3-axis Accelerometer delay= 200000 Listener= android.view.OrientationEventListener$SensorEventListenerImpl@41c3a408
01-29 16:22:12.960: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.960: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0

whenever i type a letter onto my EditText the logcat keeps increasing by

01-29 16:23:42.500: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[0] is 64
01-29 16:23:42.500: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[1] is 67
01-29 16:23:42.500: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[2] is 67
01-29 16:23:42.505: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:23:42.505: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:23:42.520: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[0] is 64
01-29 16:23:42.520: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[0] is 64
01-29 16:23:42.520: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[1] is 67

this type of code. each letter i type the more it increase so i can't paste it all here

Was it helpful?

Solution

you can set your Location Manager like

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
Log.d("GPS Enabled", "GPS Enabled"); 
provider = locationManager.getBestProvider(criteria, true);    
criteria.setAccuracy(Criteria.ACCURACY_FINE);

Now, you can display Latitude and Longitude like this way:

 latitude.setText(String.valueOf(location.getLatitude()));
 longitude.setText(String.valueOf(location.getLongitude())); 

Now, find Distance between two point like below:

float[] results = new float[1];
Location.distanceBetween(
                des_pos.latitude,des_pos.longitude,
                cur_pos.latitude, cur_pos.longitude, results);

            System.out.println("Distance is: " + results[0]);

Try this

Update: Go to this More about Location.distanceBetween(..)

Update2:

You just want to remove updates on your Activity Pause():

    @Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}

and, also doing continue into your Activity Resume():

@Override
protected void onResume() {
    super.onResume();
     locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

}

OTHER TIPS

You can set accuracy in Criteria object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top