SharedPreferences crashes using gps - android

i'm trying to use the sharedpreferences to calculate the distance based on gps location, but whenever the gps changes the app crashes. any suggestion?
public void onLocationChanged(Location location) {
SharedPreferences prefs = this.getSharedPreferences("com.trekker.client", Context.MODE_APPEND);
SharedPreferences.Editor editor = prefs.edit(); String str = "Latitude: "+location.getLatitude()+"Longitude: "+location.getLongitude();
currentLon1 = location.getLongitude();
currentLat1 = location.getLatitude();
if(i==0){
editor.putFloat(LATITUDE1,(float)location.getLatitude());
editor.putFloat(LONGITUDE1, (float) location.getLongitude());
editor.commit();
i++;
}
else{
lat1 = (double)prefs.getFloat(LATITUDE1, 0);
lon1 = (double)prefs.getFloat(LONGITUDE1, 0);
GPS.calculateDistance(lat1,lon1,currentLat1,currentLon1);editor.putFloat(LATITUDE1,(float)location.getLatitude());editor.putFloat(LONGITUDE1, (float) location.getLongitude());
editor.commit();
}

Related

Shared preferences from an intent

I am trying to get the value of my intent saved with shared preferences but struggling. i cant get any values saved. can somebody advise.
I need to take the value from the indent which is launched from the onActivityResult
I could even accept the CharSequence as a string. I need the intent value saved
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
// The user has selected a place. Extract the name and address.
Place place = PlacePicker.getPlace(data, this);
LatLng placeLatLng = place.getLatLng(); // gett lat lng from place
double placeLat = placeLatLng.latitude;
double placeLong = placeLatLng.longitude;
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
final LatLng location = place.getLatLng();
Marker destination = mMap.addMarker(new MarkerOptions().position(new LatLng(placeLat, placeLong)).title("This is your destination"));
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Current Location
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location myLocation = locationManager.getLastKnownLocation(provider);
//Current Location LatLong
final double currentLat = myLocation.getLatitude();
final double currentLng = myLocation.getLongitude();
//Directions From Current Location To Destination
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?" + "saddr=" + currentLat + "," + currentLng + "&daddr=" + placeLat + "," + placeLong));
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
//historyDBHandler.addHistory(history);
startActivity(intent);
}
}
private String getInfo(){
SharedPreferences sharedPreferences = getSharedPreferences("Place Details", Context.MODE_PRIVATE);
String mapInfo = sharedPreferences.getString("map Info", "no data recorded");
return mapInfo;
}
private void saveValues(CharSequence name, CharSequence address){
Double text = Double.valueOf(new String().toString());
SharedPreferences sharedPreferences = getSharedPreferences("Place Details", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("map info", "help" );
editor.commit();
}
You're putting with the key "map info" but getting with the key "map Info".

Options to save data from a map marker to be used in a different activity android studio

I am looking advice on options i have to save data from markers and searches from placepicker on google maps.
Ive looked into shared preferences and tried the code out but not working.
I need to take address data from a place picker search and save it so that a history activity can generate a list.
is there any option that place picker saves searches?
im using android studio
This is an example of my place picker
Place place = PlacePicker.getPlace(data, this);
LatLng placeLatLng = place.getLatLng(); // gett lat lng from place
double placeLat = placeLatLng.latitude;
double placeLong = placeLatLng.longitude;
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
Marker destination = mMap.addMarker(new MarkerOptions().position(new LatLng(placeLat, placeLong)).title("This is your destination"));
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Current Location
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location myLocation = locationManager.getLastKnownLocation(provider);
//Current Location LatLong
final double currentLat = myLocation.getLatitude();
final double currentLng = myLocation.getLongitude();
List<CharSequence> listItems = new ArrayList<>();
//Directions From Current Location To Destination
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?" + "saddr=" + currentLat + "," + currentLng + "&daddr=" + placeLat + "," + placeLong));
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
listItems.add(name);
listItems.add(address);
startActivity(intent);
}
}
public void saveInfo(View v){
SharedPreferences sharedPreferences = getSharedPreferences("Place Deatils", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
}
get location address using Geocoder and store the information in SharedPreferences
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latt,lang, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String area = addresses.get(0).getSubLocality();
String dist= addresses.get(0).getSubAdminArea();
String city = addresses.get(0).getLocality();
mapMarker.setTitle(area+","+dist+","+city);
} catch (IOException e) {
e.printStackTrace();
}
check this SharedPreferences

android studio store speed and calculate distance

i have a requestLocationUpdates=> in every 5s, the location will be updated. And i wanna calculate the distance in every 5s and then store it into an array. Also, i wanna store the location.getSpeed into an array too, so that i can use the speed saved in array to draw a graph in the next interface.
here are my codes:
private void updateWithNewLocation(Location location) {
String where = "";
if (location != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
float speed = location.getSpeed();
long time = location.getTime();
String timeString = getTimeString(time);
where = "Lng: " + lng +
"\nLat: " + lat +
"\nSpeed: " + speed +
"\nTime: " + timeString +
"\nProvider: " + "gps";
showMarkerMe(lat, lng);
cameraFocusOnMe(lat, lng);
trackToMe(lat, lng);
}else{
where = "No location found.";
}
txt.setText(where);
}
About storing data you have different options. You could use a database, where you oput your data, read it and be able to read it again the next time you use your app. If you want the data only to be persistent in the current app lifecycle, I recommend using an ArrayList of custom Objects. Short example of ArrayList<LocationObject> usage:
public class LocationObject {
private double lng;
private double lat;
private float speed;
private long time;
public LocationObject(long time, double lng, double lat, float speed) {
this.time = time;
this.lat = lat;
this.lng = lng;
this.speed = speed;
}
//put getters & setters here, press `Alt` and `Insert`, choose the getters and setters
}
In your running Activity, initialize an ArrayList globally (not inside a method, but inside your Activity.class:
private ArrayList<LocationObject> locationList;
//in onCreate:
locationList = new ArrayList<LocationObject>();
//whenever you retrieve a location, create a LocationObject and store it into the List:
LocationObject currentLocation = new LocationObject(time, lng, lat, speed);
locationList.add(currentLocation);
Now, if you want to get the last 2 locations, you simply access them in the list:
LocationObject lastLocation = locationList.get(locationList.size() - 2);
LocationObject currentLocation = locationList.get(locationList.size() - 1);
//to get the latitude, don't forget to create the getters&setters in your LocationObject.class!
double lastLat = lastLocation.getLat();
Edit: To store only the last value, just assign the values to a globally declared variable:
private Location oldLocation;
private float[] results;
private ArrayList<float> speedList;
//in oncreate:
speedList = new ArrayList<Float>();
private void updateWithNewLocation(Location location) {
String where = "";
results = new float[100]; //[100] means there can be 100 entries - decrease or increase the number depending on your output
if (location != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
float speed = location.getSpeed();
long time = location.getTime();
String timeString = getTimeString(time);
speedList.add(speed);
if(oldLocation != null){
Location.distanceBetween(oldLocation.getLatitude(), oldLocation.getLongitude(), lat, lng, results);
}
oldLocation = location;

How i save my current location?

I create a simple application for show me the current location ( Lat , Lon ) when i move.How i save my current location when i want?
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
}
Use SharedPreferences.
To save the location, use:
getPreferences(MODE_PRIVATE).edit().putDouble("lng", lng).putDouble("lat", lat).commit();
To read the location, use:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
double lng = prefs.getDouble("lng", -1);
double lat = prefs.getDouble("lat", -1);

Location changed notification android

I am just testing out the onLocationChanged method in Android , I have implemented a way that when I click a button the app returns a String with the new lat and lng values. But now I am trying to show the results automatically every time the location changes. This is what I have so far to do so:
location manager
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
int minTime = 30000;
LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
MyLocationListener myLocListener = new MyLocationListener();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(false);
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, minTime, 1, myLocListener );
onlocationchanged
public void onLocationChanged(Location loc) {
if(loc != null){
lat1 = loc.getLatitude();
lng1 = loc.getLongitude();
currentlocation = "Location changed to lat: " + lat + "" + "lng: " + lng1 ;
Context context = getApplicationContext();
CharSequence text = currentlocation;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
I have set the requestlocationupdates method to request and update every 60000 millseconds
My problem is that the application never toasts the lat and lng values when the location changes. I have tested the app with the emulator and tried telneting the lat and lng values. And I have also drove around in my car to see if the values change.
Try:
currentlocation = "Location changed to lat: " + String.valueOf(lat1) + "" + "lng: " + String.valueOf(lng1) ;
and for test you can just use:
requestLocationUpdates(LocationManager.GPS_PROVIDER...

Categories

Resources