我有以下用于android geofencing的课程:
public class gpsLocationChecker {
List<ArrayList<location>> locations = new ArrayList<ArrayList<location>>();
//public location locations[][] = new location[8][500];
InputStream in;
String[] oblastiGPSArray;
public gpsLocationChecker(InputStream in, String[] oblastiGPSArray){
this.in = in;
this.oblastiGPSArray = oblastiGPSArray;
try {
loadParser();
}catch(Exception e){}
}
public String findPoint(Double Long, Double Lat){
for(int i = 0; i <= locations.size(); i++){
if(PointIsInRegion(Long, Lat, locations.get(i)))
{
return(oblastiGPSArray[i]);
}
}
return "abc";
}
private boolean PointIsInRegion(double x, double y, ArrayList<location> oblast)
{
int crossings = 0;
location point = new location (x, y);
int count = oblast.size();
// for each edge
for (int i=0; i < count; i++)
{
location a = oblast.get(i);
int j = i + 1;
if (j >= count)
{
j = 0;
}
location b = oblast.get(j);
if (RayCrossesSegment(point, a, b))
{
crossings++;
}
}
// odd number of crossings?
return (crossings % 2 == 1);
}
boolean RayCrossesSegment(location point, location a, location b)
{
double px = point.Long;
double py = point.Lat;
double ax = a.Long;
double ay = a.Lat;
double bx = b.Long;
double by = b.Lat;
if (ay > by)
{
ax = b.Long;
ay = b.Lat;
bx = a.Long;
by = a.Lat;
}
// alter longitude to cater for 180 degree crossings
if (px < 0) { px += 360; };
if (ax < 0) { ax += 360; };
if (bx < 0) { bx += 360; };
if (py == ay || py == by) py += 0.00000001;
if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false;
if (px < Math.min(ax, bx)) return true;
double red = (ax != bx) ? ((by - ay) / (bx - ax)) : Float.MAX_VALUE;
double blue = (ax != px) ? ((py - ay) / (px - ax)) : Float.MAX_VALUE;
return (blue >= red);
}
private void loadParser() throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
loadData(parser);
} finally {
in.close();
}
}
private void loadData(XmlPullParser parser) throws XmlPullParserException, IOException {
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT){
int x = 0;
if(eventType == XmlPullParser.START_TAG){
if(parser.getName() == "coordinates"){
String coordinates = parser.nextText();
StringTokenizer st = new StringTokenizer(coordinates, ",", false);
int y = 0;
locations.get(x).add(y, new location(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())));
while(st.hasMoreTokens()){
y++;
locations.get(x).add(y, new location(Double.parseDouble(st.nextToken().substring(2)), Double.parseDouble(st.nextToken())));
}
x++;
}
}
eventType = parser.next();
}
}
}
如果我尝试运行它,它会对此代码if(PointIsInRegion(Long, Lat, locations.get(i)))
抛出indexOutOfBoundException我确信XML正确解析。我无法看到任何错误,但我认为这将是我的2D arraylist(我第一次使用它)。我真的很绝望。你能告诉我我做错了什么吗?
先谢谢
答案 0 :(得分:2)
for(int i = 0; i <= locations.size(); i++){
时 i = locations.size()
将超出范围。
更改为for (int i=0; i<locations.size(); i++) {
。