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".
Related
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
I am making android application to get nearby locations, I display the locations on the map, and if any marker is pressed, another activity will be opened, the second activity shows the info about the place, I want to display the distance between my current location and the marker. I passed the longitude and latitude from the first activity to the details activity; like this :
public void onInfoWindowClick(Marker arg0) {
Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
String reference = mMarkerPlaceLink.get(arg0.getId());
intent.putExtra("reference", reference);
intent.putExtra("mLatitude", mLatitude);
intent.putExtra("mLongitude", mLongitude);
startActivity(intent);
}
in the placeDetailsActivity :
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_details);
Intent i=getIntent();
c_lat=i.getStringExtra("mLatitude");
c_lng=i.getStringExtra("mLongitude");
double d_lat=Double.parseDouble(lat);
double d_lng=Double.parseDouble(lng);
double c_lat1 =Double.parseDouble(c_lat);
double c_lng1=Double.parseDouble(c_lng);
float[] results = new float[1];
Location.distanceBetween(c_lat1, c_lng1, d_lat, d_lng, results);
d=results[0];
I get d_lat and d_lng from :
protected void onPostExecute(HashMap<String,String> hPlaceDetails){
String name = hPlaceDetails.get("name");
String icon = hPlaceDetails.get("icon");
String vicinity = hPlaceDetails.get("vicinity");
lat = hPlaceDetails.get("lat");
lng = hPlaceDetails.get("lng");
String formatted_address = hPlaceDetails.get("formatted_address");
String formatted_phone = hPlaceDetails.get("formatted_phone");
String website = hPlaceDetails.get("website");
String rating = hPlaceDetails.get("rating");
String international_phone_number = hPlaceDetails.get("international_phone_number");
String url = hPlaceDetails.get("url");
when I test my application, it crashes!!
I have an application where I am getting the latitude and longitude coordinates.
I want , when to press a button to start navigating to that position .
Now , I am storing latitude and longitude in database.
So , I want to extract the location first.When I press the button to navigate I open an alertdialog and in 'YES' I do:
public void navigation(final View v){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Do you want to navigate to the saved position?")
.setCancelable(false)
.setPositiveButton("Navigate",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// Action for 'Yes' Button
String query = "SELECT latitude,longitude FROM MEMORIES ";
Cursor c1 = sqlHandler.selectQuery(query);
if (c1 != null && c1.getCount() != 0) {
if (c1.moveToFirst()) {
do {
String mylatitude=c1.getString(c1.getColumnIndex("latitude"));
String mylongitude=c1.getString(c1.getColumnIndex("longitude"));
Double lat=Double.parseDouble(mylatitude);
Double lon=Double.parseDouble(mylongitude);
} while (c1.moveToNext());
}
}
c1.close();
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=" +
gps.getLocation().getLatitude() + "," +
gps.getLocation().getLongitude() + "&daddr=" + mylatitude + "," + mylongitude ));
startActivity(intent);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Navigation");
alert.show();
}
I have the location stored (lat and lon) and i want to start navigating to that position.
How can I do that?
Thanks!
---------------------UPDATE-------------------------------------
If I do sth like:
String mylat="";
String mylon="";
#Override
protected void onCreate(Bundle savedInstanceState) {
...
...
public void navigation(final View v){
....
String mylatitude=c1.getString(c1.getColumnIndex("latitude"));
String mylongitude=c1.getString(c1.getColumnIndex("longitude"));
mylat=mylatitude;//stored coordinates from database
mylon=mylongitude;
String f="45.08" //current location (start points)
String s="23.3";
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=" +
f + "," +
s + "&daddr=" + mylat + "," + mylon ));
startActivity(intent);
The intent starts and I am in the map application where the start points are the "f" and "s" I defined above but the destination points are 0.0 , 0.0 ;
So , I have 2 problems:
1) How to put to destination points my stored locations (mylatitude ,mylongitude (which I copy to mylat,mylon)
2) How to get current location (initial points) because my gps class doesn't work on that.
In the example below ImplLocationService is a class/service within my application that is providing the latitude and longitude coordinates of the current location within the device. The Location class is similar to Android's offering but is slightly different and is providing the destination latitude and longitude coordinates. If you were to pull these values from a database, the approach below is the same.
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=" +
ImplLocationService.getCurrentLocation().getLatitude() + "," +
ImplLocationService.getCurrentLocation().getLongitude() + "&daddr=" +
location.getPoint().latitude + "," + location.getPoint().longitude));
startActivity(intent);
While storing the lat and long store it in this way...
String mylocation=latitude + ":" + longitude;
And while retriving it
String latitude = mylocation.subString(0, myLocation.indexOf(":") - 1 );
String longitude = mylocation.subString(myLocation.indexOf(":"));
and pass it as
j.putExtra("lon", longitude);
j.putExtra("lat", latitude);
one possible way is to store your latitude and longitude values in shared preferences.
-To store values you can use
SharedPreferences sp = getSharedPreferences("MyPrefs", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("mytext", text);
editor.commit();
-and to retrive those values you can use
String value = prefs.getString("MyPrefs, "mytext");
in your code your are storing latitude and longitudes in double do not forget to convert them in toString()...
hope this helps
i have coded an android application that will update GPS coordinates to the exif of a image file.
i think that the image file exif was updated successfully as reading it will give me the GPS coordinates saved.
However, when i open up file explorer to view the image file in details, the GPS coordinate are still showing unknown. If i restart my phone, then the exif will show the updated GPS coordinate. EDIT: if i move the file to another folder, the info will be updated as well. so meaning i must phsycially do something to the image file before it will show.
anyone have any idea why is this so? and how do i solve it so it will update immediate without going to the file explorer to move the file or restart the phone?
Thank in advance!
edit: code added for the two main part
the codes for main class
public class ShowMapActivity extends MapActivity {
ExifInterface exifInterface;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private int Option;
private String selected_img;
float LatLong[] = new float[2];
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.gpsmaploc); // bind the layout to the activity
Bundle extras = getIntent().getExtras();
if(extras !=null) {
selected_img = extras.getString("selected_img");
Option = extras.getInt("Option",0);
}
/*Intent cancelIntent = new Intent(this, A.class);
cancelIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(cncelIntent);*/
// create a map view
RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
//mapView.setStreetView(true);
mapController = mapView.getController();
mapController.setZoom(20); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, new GeoUpdateHandler());
updateExif(selected_img);
}
the method for updating exif
public void updateExif(String file) {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
String address = ConvertPointToLocation(point);
String strLongitude = location.convert(location.getLongitude(), location.FORMAT_SECONDS);
String strLatitude = location.convert(location.getLatitude(), location.FORMAT_SECONDS);
String Text = "Lat=" + strLatitude + " Long=" + strLongitude;
String message = String.format(
"Current Location \n%3$s \nLongitude: %1$s \nLatitude: %2$s \n"+Text,
location.getLongitude(), location.getLatitude(),address
);
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
try {
exifInterface = new ExifInterface(file);
String LATITUDE = degreeDecimal2ExifFormat(location.getLatitude());
String LATITUDE_REF = "N";
String LONGITUDE = degreeDecimal2ExifFormat(location.getLongitude());
String LONGITUDE_REF = "E";
String message2 = String.format(
"Longitude: "+ LONGITUDE + "\nLatitude: " + LATITUDE );
Toast.makeText(getApplicationContext(), message2,
Toast.LENGTH_LONG).show();
exifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE, LATITUDE);
exifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, LATITUDE_REF);
exifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, LONGITUDE);
exifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, LONGITUDE_REF);
exifInterface.saveAttributes();
String exif = "";
float[] LatLong = new float[2];
if(exifInterface.getLatLong(LatLong)){
exif += "\n saved latitude= " + LatLong[0];
exif += "\n saved longitude= " + LatLong[1];
}else{
exif += "Exif tags are not available!";
}
Toast.makeText(getApplicationContext(), exif,
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
this code seem to solve my issue.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
this will refresh the sdcard content.
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...