First of all I'm a complete noob to android. Going step by step on my first app and facing some problems.
I can get my location in terms of Lat and Lon and now i have to save it to file and able to read the file to compare location in future. Could anybody please help me out on this can be done.
Following is my INCORRECT CODE
public void saveCurrentLocation(Location location){
SharedPreferences prefs = this.getSharedPreferences("com.example.mylocation", Context.MODE_PRIVATE);
String currentLat = "com.example.mylocation.location";
String now = prefs.getString(currentLat, location.getLatitude());
}
Error shown is that location.getLatitude is a double and cannot be saved to string (quite obvious but not sure how to change it)
Thanks
location.getLatitude() + "";
In Java, the + operator is overloaded to concatenate Strings. If you add "" to anything, it will be automatically cast to String.
If you want to store the result of location.getLatitude() in your sharedpreferences try converting the double to a String:
String.valueOf(location.getLatitude())
Related
I am working on an application that sends an e-mail with several information. Among the information is a link to the location of the user to Google Maps. A sample of the link would be:
http://www.google.com.ph/maps/place/14°39'3.8952"N121°2'57.4116"E/#14.651082,121.049281,17z
The code looks like this:
"Google Maps Link: http://www.google.com.ph/maps/place/" +
degToDMS(location.getLatitude()) + "\"N" +
degToDMS(location.getLongitude()) + "\"E/#" +
location.getLatitude() + "," + location.getLongitude() + ",17z");
I converted the degrees longitude and latitude to DMS using a formula I found online and it seemed to be returning good data. However, when I go check the email, the link looks like:
http://www.google.com.ph/maps/place/14°39'3.8952"N121°2'57.4116"E/#14.651082,121.049281,17z
and the hyperlink ends at the first double quote (") right before the N. This is actually a bit irritating and troubling because it doesn't link the entire link properly and it is cut.
How can I escape a double quote in a link? Or is there a better way to link to Google Maps?
I used URLEncode, thanks to for3st for the lead, as such:
final String urlRaw = degToDMS(location.getLatitude()) + "\"N" +
degToDMS(location.getLongitude()) + "\"E/#" +
location.getLatitude() + "," + location.getLongitude() + ",17z";
String encodedURL = "";
try {
encodedURL = URLEncoder.encode(urlRaw, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
where urlRaw is the "problematic' part of your url (where characters don't get escaped properly or something). You DON'T put in the http://.... because it will appear as such http%3A%2F%2Fwww.google.com.ph and yeah you don't want that.
Hence, I only escaped the latter part of my url, the one that starts with the DMS coordinates.
Once I have my encodedURL variable, I simply concat it to the rest of the starting URL as such:
String link = "Google Maps Link: http://www.google.com.ph/maps/place/" + encodedURL;
and not it works.
I get this exception from time to time, when I get a new location coordinate from the GPS, and I want to format it.
This is my code:
DecimalFormat decimalFormat = new DecimalFormat("0.00000");
location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude())));
location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude())));
Why does this happen? The latitude and longitude that I get back from the location are both Doubles. I format it transforming it into the needed format (5 decimals after point) and then when I try to make a double back, it crashes. Why does this happen? And why not everytime, just sometimes?
Example on what crashed:
Fatal Exception: java.lang.NumberFormatException
Invalid double: "52,36959"
This is where I use it:
Log.i("","enteredd latitude is:" + location.getLatitude());
try{
DecimalFormat decimalFormat = new DecimalFormat("0.00000");
location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude()).replace(",", ".")));
location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude()).replace(",", ".")));
}catch (Exception e){
Log.e("","enteredd error deimal formating" + e.getMessage());
}
Log.i("","enteredd latitude is:" + location.getLatitude());
And the same thing for:
location = LocationServices.FusedLocationApi.getLastLocation(PSLocationCenter.getInstance().mLocationClient);
Question: Will it fix it if I do it like this?
location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude()).replace(",", ".")));
You are putting a double value into a decimal format, then parsing it back to double and using the very same value that you have gotten from the variable location to set the values for location. There is an exceeding amount of poor logic in this.
location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude())));
location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude())));
location.getLatitude is the latitude, you do not need to set it.
You need to set a decimal separator:
DecimalFormat decimalFormat = new DecimalFormat("0.00000");
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
decimalFormat.setDecimalFormatSymbols(dfs);
From here: (android) decimalformat, uses comma in place of fullstop while formatting with "#.##"
Also:
Get location.
double latitude = location.getLatitude();
double longitude = location.getLongitude();
For the purposes of your app, you do not need to change this.
Just pass the values to the server that you need:
String lat = decimalFormat(latitude);
String long = decimalFormat(longitude);
I am having trouble storing a double in the phone's memory. What are my other options if this isn't possible. Basically what the code is aiming to do using sharedpreferences is take the stored value of "Alcohol" spending and then add whatever the input is in the editText to it and then store that new value for the next time. Running total of spending on alcohol
**Can someone please help with this issue and be detailed where x y & z should go in the project.
The user selects from a spinner, which works.
public void addInput(){
double dblCostInput = Double.valueOf(inputBox.getText().toString());
String strCategories= spinnerCategories.getSelectedItem().toString();
if(strCategories.equals("Alcohol"))
{
alcoholSpend = alcoholSpend + dblCostInput;
inputBox.setText("");
nextInput();
inputBox.setText("Your Spending on"+strCategories+" is: " +d.format(alcoholSpend));
}
getSharedPreferences("MY_PREFERENCE", MODE_PRIVATE).edit().putString("double", "0.28").commit();
and then to retrieve the double, simply use Double.parseDouble:
Double.parseDouble(getSharedPreferences("MY_PREFERENCE", MODE_PRIVATE).getString("double", "0.28"));
Try below code for setting/putting & getting double with sharedpreferences :
////////////////////////////////////Setter/////////////////////////
Editor putDouble(final Editor edit, final String key, final double value) {
return edit.putLong(key, Double.doubleToRawLongBits(value));
}
//////////////////////////////Getter//////////////////////////////
double getDouble(final SharedPreferences prefs, final String key, final double defaultValue) {
return Double.longBitsToDouble(prefs.getLong(key, Double.doubleToLongBits(defaultValue)));
}
I am developing an app where I need to calculate the distance from the current position and some other locations. I am using the GPS to access the users current location and the other locations coordinates are stored in a database. The problem occurs in the following snippet:
#Override
public void onLocationChanged(Location arg0) {
Log.v("LOCATION LAT", String.valueOf(arg0.getLatitude()));
currentLocation = arg0; //currentLocation is a global class variable
}
The problem is when I feed the DDMS with coordinates such as:
Latitude: 62.639579
Longitude: 17.909689 and log these values I get Latitude: 62.0 and Longitude 17.0 .
If I create a location object and set the lat and lng values myself it works. Like this:
#Override
public void onLocationChanged(Location arg0) {
Location current = new Location("Current location");
current.setLatitude(62.639579);
current.setLongitude(17.909689);
Log.v("Current LAT", "" + current.getLatitude());
}
EDIT SOLVED:
Found the problem. I was feeding the the DDMS with faulty formatting. Apparently this should be delimited with a comma sign, not a dot...
Have you used the permissions specified in this post? Else it kicks back to using cell tower triangulation.
Other question
Found the problem. I was feeding the the DDMS with faulty formatting. Apparently the coordinates should be delimited with a comma sign, not a dot...
you can do something like as below. Create a location variable in that you have to assign location change var
#Override
public void onLocationChanged(Location arg0) {
Location current = new Location("Current location");
current=arg0;
Log.v("Current LAT", "" + current.getLatitude());
}
My app has a number of numeric user input fields which need sanity checks before proceeding to the next intent.
I read viewText fields, convert them to double and then do the (numeric) tests but odd things happen and I find that while the code runs on my HTC in debug, it falls over if I publish then download the published version. My code is sumarised as;
String sFy;
double mFy=0;D
sFy=(txtFy.getText().toString());
mFy=Double.parseDouble(sFy);
if sFy is null the .parsedouble crashes. If I use;
sFy=(txtFy.getText().toString());
mFy=getDouble(sFy);
private double getDouble(String string){
double temp=0.0;
try {
temp = Double.parseDouble(string.trim());
} catch(NumberFormatException nfe) {
System.out.println("getDouble, Could not parse " + nfe);
}
return temp;
}
it works, even if sFy is empty.
Can anyone tell my why, or suggest a 'correct' method?
Maybe like that :
String sFy;
double mFy=0;
sFy = txtFy.getText();
if ((sFy != ""){
mFy=Double.parseDouble(sFy);
}
Or maybe I haven't really understood your problem...
Your getDouble is returning 0.0 in case there is NumberFormatException.
Do you see debugger coming to System.out.println("getDouble, Could not parse " + nfe);