value of integer in for loop do not changed android - android

I'm developing an Android app which is using Google Places API.
Once I get all the places result, I want to sort it according to the algorithm.
Which is, the places result will only being put into the Hash Map if the algorithm is >= 0.
But the problem now is, when I run it, the algorithm result in the for loop did not change during the looping.
My algorithm is:
balance = user_hour-visi-duration.
balance = 240-60-20 = 160
Let's say the balance is 160, it will remain 160 until the for loop ended.
I wanted each time of the looping, the value of balance will decreased untill negative value.
FYI, balance variable is not a local variable.
Does anybody know how to solve this?
Here is the part of the code.
// loop through each place
for (Place p : nearPlaces.results) {
balance = user_hour - duration - visit;
HashMap<String, String> map = new HashMap<String, String>();
//////////////////////////////////////////////////////////////////
googlePlaces = new GooglePlaces();
try {
placeDetails = googlePlaces.getPlaceDetails(p.reference);
} catch (Exception e) {
e.printStackTrace();
}
if(placeDetails != null){
String statuss = placeDetails.status;
// check place deatils status
// Check for all possible status
if(statuss.equals("OK")){
lat = gps.getLatitude();
lang = gps.getLongitude();
double endlat = placeDetails.result.geometry.location.lat;
double endlong = placeDetails.result.geometry.location.lng;
Location locationA = new Location("point A");
locationA.setLatitude(lat);
locationA.setLongitude(lang);
Location locationB = new Location("point B");
locationB.setLatitude(endlat);
locationB.setLongitude(endlong);
double distance = locationA.distanceTo(locationB)/1000;
Double dist = distance;
Integer dist2 = dist.intValue();
//p.distance = String.valueOf(dist2);
p.distance = String.valueOf(balance);
dist3 = p.distance;
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(MainActivity.this, "Near Places",
"Sorry no place found.",
false);
}
}
///////////////////////////////////////////////////////////////
if (balance > 0){
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
map.put(KEY_DISTANCE, p.distance);
// adding HashMap to ArrayList
placesListItems.add(map);
}
else {
//
}
}//end for loop

What exactly are you trying to do here?
You have balance = user_hour - duration - visit; on the first line after your for loop. I cannot see where user_hour, duration or visit is declared, but I'm assuming it's outside the loop. This means it will always be the same value for each Place in nearPlaces.results. If this code is genuinely how you want it, you might as well declare it before the loop as you are pointlessly re-calculating it for every Place.
You also never do anything with balance except to print it out or set another value to it, so it's tricky to work out what you're expecting to happen.

Related

How to parse json into android to compare users location to nearest 10 locations?

Im getting the server response for store locations and its basically a master array with dictionaries:
[ masterArray :
{name = main,
lat = 15.948
long= 88.853
},
{name = 5th Street,
lat = 15.294
long= 88.743
},
{name = Cannes Blvd,
lat = 15.235
long= 88.765
},
]
I need to loop through each store, get the lat/long, compare it to users location, create a new array with just the top 5 nearest locations.
Ive got this so far:
try {
//Get master array of locations
JSONArray jsonArray = new JSONArray(Arrays.asList(contentAsString));
//Loop through each dictionary in array
for (int i = 0; i < jsonArray.length; i++) {
//Get the lat&long for
JSONObject sys = jsonArray.getJSONObject("master");
name = sys.getString("name");
latitude = sys.getString("lat");
longitude = sys.getString("long");
//Create location object
//Send to Location.distanceTo() method
//Create new array with distance field added to the original values
}
//Sort and get nearest 5 locations
//Create cards for top 5 locations only
//better use Mirror API
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
What Im stuck in is creating the location object and how to hook that up to the distanceTo method which currently is empty:
//Get distances
public float distanceTo (Location dest) {
//Compare distance passed to user location
//return distance float
return 1;
}
Any help will be much appreciated.

Best Practice to find nearby based on lat/lon android?

I have 16000 Locations in my Sql Lite DB.
And I am fetching all into cursor and setting each into LOCATION object and I am using distaneTo() method of LOCATION class.
Is there any best way to do it to find nearest Location based on user's location.
My Code::::
Location userLocation = new Location("Point A");
userLocation.setLatitude(latitude);
userLocation.setLongitude(longitude);
Location stopLocation = new Location("Point B");
List<FavouriteStop> allFavourites = new ArrayList<FavouriteStop>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(
"Select * from tbl_stop order by routeName desc", null);
FavouriteStop stop = new FavouriteStop();
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
if (c.getString(c.getColumnIndex("stopId")) != null) {
// Setting Stop Location for Distance
stopLocation.setLatitude(c.getDouble(c
.getColumnIndex("lat")));
stopLocation.setLongitude(c.getDouble(c
.getColumnIndex("lon")));
float distance = userLocation.distanceTo(stopLocation);
if (distance < radius) {
if (allStopsHash.containsKey(c.getString(c
.getColumnIndex("routeName")))) {
// Contains
} else {
// Not Contain
stop.setFirstElement(true);
allStopsHash.put(
c.getString(c.getColumnIndex("routeName")),
c.getString(c.getColumnIndex("routeName")));
}
stop.settag(c.getString(c.getColumnIndex("tag")));
stop.settitle(c.getString(c.getColumnIndex("title")));
stop.setlat(c.getDouble(c.getColumnIndex("lat")));
stop.setlon(c.getDouble(c.getColumnIndex("lon")));
stop.setstopId(c.getString(c.getColumnIndex("stopId")));
stop.setDirection(c.getString(c
.getColumnIndex("towards")));
stop.setRouteName(c.getString(c
.getColumnIndex("routeName")));
stop.setDistance((distance / 1000));
allFavourites.add(stop);
// }
}// Distance Radius Over
}// If StopId != Null Over
} while (c.moveToNext());
}
db.close();
SQLite can't do queries sorted by distance based on coordinates. Iterating through the points is the right solution in this case. However, you can improve your implementation by caching the column indexes. Instead of calling multiple times getColumnIndex("lat") for example you can have something like
int latIndex = getColumnIndex("lat");
and than always use latIndex. I've never done tests to check the performance improvement but it's certainly the better way of doing it.

Break out multiple coordinates into multiple latlng googlemap v2

I have a huge list in an XML tag like so:
<coor> -123.3858,41.34119,0
-123.3856,41.34109,0
-123.3852,41.34121,0
-123.3848,41.34139,0</coor>
and need it like this:
new LatLng(-123.3858,41.34119),
new LatLng(-123.3856,41.34109),
new LatLng(-123.3852,41.34121),
new LatLng(-123.3848,41.34139),
to work with google maps v2 android.
I've done a string replace on the coordinates and am getting the correct results like so:
String ll = "),new LatLng(";
coor = coor.replaceAll(",0", ll);
replacing the ,0 for the new LatLng(... I am not figuring out how to change the large string of latlng text into latlng locations to put into my polygon:
PolygonOptions perimeteres = new PolygonOptions().add(coor);
Is there way to do this? Or do I need to separate each out and make them individual latlng?
EDIT::::
String[] splitData = coor.split(",0");
for (String eachSplit : splitData) {
if (!eachSplit.endsWith(",0")) {
//Log.e("EACH",eachSplit);
Log.v("e","new LatLon("+eachSplit+");");
}
}
This is getting me a little closer...
You are going completely in the wrong direction, this
String ll = "),new LatLng(";
coor = coor.replaceAll(",0", ll);
is not the same as
new LatLng(-123.3858,41.34119)
the first gives you a string which does nothing for you, the second is an object which is what you need.
Edit
you need to remove the 0 from the coordinates then you do a string split on the , so you have an array of latitudes and longitudes.
then create a List<LatLng> which is what you need to create a polygon of points
and loop through your points
for(int j=0;j<locationAry.length;j++){
if(j%2 == 0){
lon = Float.parseFloat(locationAry[j+1]);
lat = Float.parseFloat(locationAry[j]);
}
}

How to add locations and distances to a custom layout android

I am making an android app that will list specific places that are not on google places. I have all the latitude and longitudes and place names and they will not be changing. I can display them in my custom list and it works fine the problem is I want to sort them all by distance from your(the users) location and display the distance next to them.
I have tried lots of different ways but have become a bit stuck. I would like to say that I am new to programming and sort of stumbling my way through this app, If anyone could help it would be really appreciated.
So the question im asking is how can/should I sort locations by distance so I can add them to my custom list.
// create array to hold place names to be looped through later
String[] placenames = { "place1", "place2",
"place3", "place4" };
// // create arrays to hold all the latitudes and longitudes
double[] latArray = new double[] { 51.39649, 51.659775, 51.585433,
51.659775 };
double[] lngArray = new double[] { 0.836523, 0.539901, 0.555385,
0.539901, };
// hard code my location for test purposes only
Location MyLocation = new Location("My location");
MyLocation.setLatitude(51.659775);
MyLocation.setLongitude(0.539901);
for (int i = 0; i < placenames.length;) {
// Place location object
Location PlaceName = new Location(placenames[i]);
PlaceName.setLatitude(latArray[i]);
PlaceName.setLongitude(lngArray[i]);
i++;
// calculate distance in meters
float distanceInMeters = PlaceName.distanceTo(MyLocation);
// convert to double
double DistanceInMiles = distanceInMeters * 0.000621371;
dimint = (int) DistanceInMiles;
// format numbers to two decimal places
DecimalFormat df = new DecimalFormat("#.##");
dim = df.format(DistanceInMiles);
//make treemap and then sortedmap to sort places by distance
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
SortedMap<Integer, String> treemapsorted = new TreeMap<Integer,String>();
treemap.put(dimint, PlaceName.getProvider());
treemapsorted = treemap.subMap(0, 5);
// Toast for test purpose to see if sort is working
Toast tst = Toast.makeText(this, treemapsorted.entrySet()
.toString(), Toast.LENGTH_SHORT);
tst.show();
CustomList place_data[] = new CustomList[] {
// This is the problem part
new CustomList(R.drawable.picture1, treemapsorted.get(dimint)),
};
CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.listview_item_row, place_data);
listView1 = (ListView) findViewById(R.id.listView1);
listView1.setAdapter(adapter);
;
}
I just reviewed your code and found lots of problems:
Use i++ in your for loop statement instead of in the loop body, like this:
for (int i = 0; i < placenames.length; i++) {
}
You calculate the distance in miles, cast this to int (I would use Math.round() here) and then create a string with DecimalFormat which you don't use.
You create a TreeMap in every loop iteration. Move the creation in front of the loop and add items to it in the loop body.
TreeMap is not the right class for this task. I tested your code and the Map contained only 3 items after the loop. The reason is, that a TreeMap contains key value pairs, where the key has to be unique. Adding an element with a key (distance in your case), which is already in the map, results in overwriting that element. So instead of a TreeMap I recommend using an ArrayList. You need to create a class with all the variables you need, like distance and place name. This class needs to implement the interface Comparable<Class>. You will then have to implement the method public int compareTo(T other) in which you compare the distance with the distance of the other object. Then you can sort the ArrayList using Collections.sort(arrayList). In the for loop body you should add items to that ArrayList, then sort it, then iterate over the ArrayList items and add them to your ListView.

Converting a string to an int for an Android Geopoint

I'm getting latitude and longitude as strings from a Google Places URL. Now I'd like to place a pin on a map using the obtained coordinates. Something is goofy because I'm trying to parse the strings into integers for the GeoPoint, and the results show as 0,0 so the pin is placed off the coast of Africa. Here's my code:
int lati5Int, longi5Int;
String latiString = in.getStringExtra(TAG_GEOMETRY_LOCATION_LAT);
String longiString = in.getStringExtra(TAG_GEOMETRY_LOCATION_LNG);
TextView getLatiStringtv.setText(latiString);
TextView getLongiStringtv.setText(longiString);
try {
lati5Int = Integer.parseInt(getLatiStringtv.getText().toString());
longi5Int = Integer.parseInt(getLongiStringtv.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
// shows that the ints are zeros
doubleLatiTV.setText(Integer.toString(lati5Int));
doubleLongiTV.setText(Integer.toString(longi5Int));
//--- GeoPoint---
newPoint = new GeoPoint(lati5Int,longi5Int);
mapController.animateTo(newPoint);
mapController.setZoom(17);
//--- Place pin ----
marker = getResources().getDrawable(R.drawable.malls);
OverlayItem overlaypoint = new OverlayItem(newPoint, "Boing", "Whattsup");
CustomPinpoint customPin = new CustomPinpoint(marker, SMIMap.this);
customPin.insertPinpoint(overlaypoint);
overlayList.add(customPin);
I think the error is in the parsing of the integers:
lati5Int = Integer.parseInt(getLatiStringtv.getText().toString());
longi5Int = Integer.parseInt(getLongiStringtv.getText().toString());
I think the parsing sees the decimal point in the coordinates and freaks out. So how can I parse the coordinate strings into integers so that the GeoPoint will see them as correctly formatted coordinates like: 30.487263, -97.970799
GeoPoint doesn't want to see them as 30.487263, -97.970799. It wants them as the integers 30487263, -97970799. So like A.A said, parse as double first, multiply by E6, then cast to int.
So maybe something like:
lati5Int = Double.parseDouble(getLatiStringtv.getText().toString());
latiE6 = (int) (lati5Int*1000000);

Categories

Resources