2

I am making a program in android where i get the gps coordinates when the location changes. I need to save the previous latitude and longitude whenever the location changes. Then i will be able to calculate the distance later. Can anyone help me how to save the current coordinates and the previous coordinates programmatically. Thanks. Here is my code. Ignore the buttons and timer i have to store the previous coordinates when the location changes.

package com.example.higher.myosmand;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends Activity {

private LocationManager locationManager;
private LocationListener locationListener;
private Location currentLocation;
private TextView latlon;
private TextView distance;
ArrayList<String> list = new ArrayList<>();
ListView listView;
private TextView listText;
private float results[] = new float[2];
double lat;
double lon;
double currentLat;
double currentLon;
double accuracy;
double speed;
double altitude;
double time;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    latlon = (TextView) findViewById(R.id.latlon);
    distance = (TextView) findViewById(R.id.distanceText);
    listView = (ListView)findViewById(R.id.listView);
    listText = (TextView)findViewById(R.id.listText);

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location loc) {
            //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
            lat = loc.getLatitude();
            lon = loc.getLongitude();
            accuracy = loc.getAccuracy();
            speed = loc.getSpeed();
            altitude = loc.getAltitude();
            time = loc.getTime();
            /*currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            currentLat = currentLocation.getLatitude();
            currentLon = currentLocation.getLongitude();*/
            listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));

            list.add("latitude: " + lat + " longitude: " + lon);
            //list.add("speed: " + speed + " accuracy: " + accuracy);
            distance.setText("size: " + list.size());
        }

        @Override
        public void onProviderDisabled(String arg0) {
            //TODO auto generated method stub
        }

        @Override
        public void onProviderEnabled(String arg0) {
            //TODO auto generated method stub
        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            //TODO auto generated method stub
        }
    };
}

public void setMyTimer(){

    Timer myTimer = new Timer();
    TimerTask myTask = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));
                    list.add("latitude: " + lat + " longitude: " + lon);

                    //distance.setText("Current Location:\n Latitude: " + currentLat +" Longitude: " + currentLon);
                }
            });
        }
    };
    myTimer.schedule(myTask, 5000, 5000);
}

public void startButton(View view) {
    //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    latlon.setText("latitude: " + lat + " \nlongitude: " + lon + " \naccuracy: " + accuracy +
            "\nspeed: " + speed + "\naltitude: " + altitude + "\ntime: " + time);
}

public void endButton(View view) {
    //locationManager.removeUpdates(locationListener);

    //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

}

public void resetButton(View view) {
    list.clear();
}

@Override
protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

AIK
  • 498
  • 2
  • 6
  • 20
  • 1
    Please provide some more information about your goals. The answer to this question will require some knowledge of your program, its structure, and the context of its execution. – OYRM May 22 '15 at 15:31
  • what i have to do is to get the coordinates whenever the location changes and as the device will be inside a car i have to calculate the distance between these points in real time. – AIK May 22 '15 at 15:53

3 Answers3

1

Use this code inside your onLocationChanged method. It stores your previous location coordinates into prev variable:

private LatLng prev;
private int flag=0;

 @Override
        public void onLocationChanged(Location location) {
                LatLng current = new LatLng(location.getLatitude(), location.getLongitude());
            if(flag==0)  
            {
                prev=current;
                flag=1;
            }
    //Do whatever you want here
            prev=current;
            current = null;
}
charoup
  • 31
  • 1
  • 9
  • can u please show the latitude and longitude separately because you made an object and i have put my latitude and longitude separately so that i can calculate distance later. i have put my code see it please – AIK May 23 '15 at 09:11
  • i found your code easier and got hint from it. It worked thanks. – AIK May 29 '15 at 15:39
1

Use SharedPreferences for simple key-value storage.

// saving
PreferenceManager.getDefaultSharedPreferences(context).edit()
    .putLong("current_latitude", latitude)
    .putLong("current_longitude", longitude)
    .apply();

// loading
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
long latitude = prefs.getLong("current_latitude", 0);
long longitude = prefs.getLong("current_longitude", 0);
Pavel Synek
  • 1,191
  • 8
  • 13
  • Thanks for the tip. i'll read about shared preferences and apply it in my code and will this work inside the onLocationChanged method? – AIK May 22 '15 at 19:50
1

In an attempt to simplify embloo's answer, you can just save your current location to your previous location variable before updating to the current location in the onLocationChanged method. Like this:

@Override
public void onLocationChanged(Location location) {
    mPreviousLocation = mCurrentLocation;
    mCurrentLocation = location;

    // update values or UI below here 
}
MethodMan
  • 409
  • 5
  • 8