Java convert location coordinates into double for long and lat - java

I've been making an mobile android application on android studio and I've got locations saved on the database. I need to convert these long and lats into a double so that it can be used in a google maps fragment.
At the moment it is getting the string from the database like this:
Cursor res = dbHelper3.getEvent(journey, message);
if (res.getCount() == 0) {
showMessageData("Error", "No data");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append(res.getString(1));
}
but theres an issue with converting it into a double as both long and lat are saved as one big string. For example it will print:
"52.301293 0.185935"
When I try this
String location = buffer.toString();
locationText.setText(buffer.toString().trim());
float f = Float.parseFloat(location);
it gives an error:
This cannot be converted into a double as its two separate numbers Is there a way of somehow separating these into two double numbers or do I have to redesign the way my database gets the location ?

You are trying to convert a string containing space into double, which will ultimately crash app.
You need to split your string ''location'' to two strings by space as:
String[] splited = location.split("\\s+");
Then you can covert it to double as below
double latitude = Double.parseDouble(splited[0]);
double longitude = Double.parseDouble(splited[1]);

You need to keep the latitude and longitude information separately like that:
String location = "52.301293 0.185935";
String[] afterSplitLoc = location.split(" ");
After that convert them to Double like that :
double latitude = Double.parseDouble(afterSplitLoc[0]);
double longitude = Double.parseDouble(afterSplitLoc[1]);
And than use on map. For example add a marker:
private GoogleMap googleMap((MapView)rootView.findViewById(R.id.YOURMAPID)).getMap();
googleMap.addMarker(new MarkerOptions().position(new LatLng( latitude, -longitude)).title("Marker"));

IMO, unless you have special reason, you should save the latitude and longitude in separate columns, as it will make future update operation easier.
You can use split() method to separate the two values:
String location = "52.301293 0.185935";
String[] latlng = location.split(" ");
System.out.println("Lat = " +latlng[0]+" Longitude = "+latlng[1]);
//You will get sth like "Lat = 52.301293 Longitude = 0.185935"

Just use something like this:
String location = buffer.toString().trim();
String[] latLon = location.split(" ");
double lat = Double.parseDouble(latLon[0]);
double lon = Double.parseDouble(latLon[1]);

thanks kshetline,
worked perfect
String string = buffer.toString();
String[] parts = string.split(" ");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
locationText.setText(part1 + "\n" + part2);
float longNum = Float.parseFloat(part1);
float latNum = Float.parseFloat(part2);
locationText.setText(longNum + "\n" + latNum);
final LatLng eventLocation1 = new LatLng(longNum, latNum);

Related

How to convert string with $ sing in it to int

I have a string "$1,076.00" and I want to convert them in to int,
I capture some value $1,076.00 and saved in string called originalAmount,
and tried int edited = Integer.parseInt(originalAmount); and it gave me error java.lang.NumberFormatException: For input string: "$1,076.00"
can anyone help?
You need to remove the undesired part ($ sign) and then parse the string to double carefully since the decimal part is a locale dependent
String pay = "$1,076.00";
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse(pay.replace("$", ""));
double result = number.doubleValue();
System.out.println(result);
string sourceString = "$1,076.00";
sourceString.substring(1, sourceString.length() - 1)
int foo = Integer.parseInt(sourceString);
Try this:
String amount = "$1,076,.00";
String formatted = amount.replace("$", ""); // remove "$" sign
formatted = formatted.replace(",", ""); // remove "," signs from number
double amountDouble = Double.parseDouble(formatted); // convert to double
int amountInt = (int)amountDouble; // convert double value to int
System.out.println(amountInt); // prints out 1076
String originalAmount="$1076.00";
String amount = originalAmount.replace($,"");
int edited = Integer.parseInt(amount);
Thanks everyone yr answers help me a lot
I have come up with
originalAmount = originalAmount.substring(1);
if (originalAmount.contains("$")) {
originalAmount = originalAmount.replace("$", "");
}
newOriginalAmt = Double.parseDouble(originalAmount);
System.out.println(newOriginalAmt);
pls let me know yr thoughts

Convert string to float: "8.9km" to float

I'm getting the distance in string like "8.9km". I need to convert it to float.
So if the string is "8.9km", the corresponding float will be 8.9
How to achieve this in Java?
Note: The value can change to miles/meters also, since it is retrieved from Google Maps
You can try the following code,
String dis = "8.9km";
Float distance = Float.valueof(dis.substring(0,dis.indexOf("km")));
float d = distance.floatValue();
You can do
String distance = "8.9km";
float distanceInFloat = Float.parseFloat(distance.substring(0,distance.indexOf("km")));
System.out.println(distanceInFloat);
Output :
8.9
Use following code:
String s="8.9km";
s=s.replace("km", "");
float f=Float.parseFloat(s);
System.out.println(f);
Output:
8.9
Hope it helps.
try the following for removing all non-digits(excluding '.') from a string
String distance = "7.9km";
float floatValue = Float.parseFloat(distance.replaceAll("[^\\d.]",""));
System.out.println(floatValue);
String str = "8.9km";
str = (str.replace("km", ""); //remove the km
float f = Float.parseFloat(str); //convert the string to a float
The float f will now have a value of 8.9
System.out.println(f);
Output:
8.9
Try this:
public float parse(String string, String suffix) { // suffix can be m, km etc.
if (!string.endsWith(suffix)) {
throw new IllegalArgumentException();
}
string = string.subString(0, string.length() - suffix.length()); // get rid of the suffix we have at the end
return Float.parseFloat(string); // parse the float from what we have left
}
If the float is invalid, or the string doesn't end in "km", a NumberFormatException or IllegalArgumentException will be thrown, respectively.
Try this.. i hope it will help
String km = "8.9km";
float kmInFloat=Float.parseFloat(km.replaceAll("km",""));
System.out.println(kmInFloat);
Output :
8.9

Decomposing strings in Android Application

I am trying to write an Android Application in Java for an Android phone. The Android application reads serial data strings via Bluetooth using SPP profile. These strings are sent by another Bluetooth device. These strings are in the following format:
"Acc Data:x_adc,y_adc,z_adc!"
Each string begins with:
"Acc Data:
and ends with
"!"
The x_adc, y_adc and z_adc are values and have a length of 5 digits.
These strings are sent at regular intervals. Right now I am able to use InputStream to accept these strings using a string buffer. I'm also able to display the complete strings in a scrollable TextView which displays each string beneath the other.
What I want to do is to decompose the x_adc, y_adc and z_adc values from the strings and display these values in a 3 separate TextViews. The TextViews which need to display the adc values have to refresh after a new string has been sent to the Android smartphone. I tried to use the Pattern class and split() to decompose the strings but failed to understand them and use them in the application.
Could someone help me with this problem?
You could use substring() to clean the extra data, and then split():
String[] values = indata.substring(9, 26).split(",");
String x_adc = values[0];
...
Try:
private TextView tv1;
private TextView tv2;
private TextView tv3;
update("Acc Data:x_adc,y_adc,z_adc!");
public void update(String data) {
String values[] = data.replace("Acc Data:", "").replace("!", "").split(",");
String v1 = "";
String v2 = "";
String v3 = "";
if(values != null && values.length == 3) {
v1 = values[0];
v2 = values[1];
v3 = values[2];
}
tv1.setText(v1);
tv2.setText(v2);
tv3.setText(v3);
}
Alternate way of getting the values:
String values[] = data.substring(data.indexOf(':') + 1, data.indexOf('!')).split(",");
Just have a lood at the String functions substring(beginIndex, endIndex) to suppress the static part of the string and split(",") to get the 3 values.
This code will handles instances where > 3 tokens are included in the String.
public static void main(String[] args) {
String value = "Acc Data:x_adc,y_adc,z_adc!";
String trimmed = value.substring(value.indexOf(":")+1, value.length()-1);
String[] tokens = trimmed.split(",");
for(String token: tokens){
System.out.println(token);
}
}

How to split XML String?

I have this xml node. I want to split the coordinate to latitude and longitude using java.
<MAP>1234:3.12345,119.12345</MAP>
I want to split the coordinate or at least can get the coordinate with this format (lat,long). Thanks all.
Have you tried with regex ?
final Pattern regex = Pattern.compile("<MAP>((.*):(.*),(.*))</MAP>", Pattern.DOTALL);
final Matcher matcher = regex.matcher(whatyouwanttoparselatlongwiththeaboveformat);
if (matcher.find()) {
System.out.print(matcher.group(2) + " : (lat,lon) = ");
float latitude = Float.valueOf(matcher.group(3));
float longitude = Float.valueOf(matcher.group(4));
System.out.println(latitude + "," + longitude);
}
Then you can deal with latitude and longitude as you wish.

How can I convert double to string in Java ME

How can I convert a double into a String in Java for Mobile phones?
Note that this does not work:
double lat = 22.456464;
String strLat = String.valueOf(lat);
Neither does this:
String str = Double.toString(double).
I'd suggest you try
double lat = 22.456464;
String strLat = "" + lat;
There is typo in your code:
String str = Double.toString(double).
It should work this way:
String str = Double.toString(lat);
Double class CLDC 1.1 contains the method:
public static String toString(double d)
Older or more limited API may not have the method or Double class.

Categories

Resources