[英]java.lang.ArrayIndexOutOfBoundsException in android
I have an app in android(I'm running it on emulator) that receives location updates and I wanna found out the speed of the device that I track.我在 android 中有一个应用程序(我在模拟器上运行它)接收位置更新,我想知道我跟踪的设备的速度。
I do this by computing the distance between two consecutive location updates and callculating the time that I receive these updates.我通过计算两个连续位置更新之间的距离并计算我收到这些更新的时间来做到这一点。
And finally I wanna find the speed by dividing the distance and time(it's a rough estimation but I don't have an alternative)最后我想通过除以距离和时间来找到速度(这是一个粗略的估计,但我没有其他选择)
And here is my problem:这是我的问题:
I have an array of length 2 in which I put time instances....but I get我有一个长度为 2 的数组,我在其中放置了时间实例....但我得到了
java.lang.ArrayIndexOutOfBoundsException exception at this line: java.lang.ArrayIndexOutOfBoundsException 在这一行出现异常:
time[i]=t;时间[i]=t;
Here is my code:这是我的代码:
public void onLocationChanged(Location loc) {
if (loc != null) {
try{
float[] distance = new float[2];
long [] time=new long[2];
loc.distanceBetween(first_gps_lat, first_gps_lon,
loc.getLatitude(), loc.getLongitude(), distance);
long t=(long)(loc.getTime()*(1e-3));
time[i]=t;
if(time.length==2)
{
var=time[1]-time[0];
time[0]=time[1];
i=1;
}
i++;
if(contor>0)
{
System.out.println("Distance is:" + distance[0] + "!!!!!!");
}
first_gps_lat=loc.getLatitude();
first_gps_lon=loc.getLongitude();
contor++;
}
catch(Exception e)
{
e.printStackTrace();
}
latitude = (int)(first_gps_lat * 1E6);
longitude = (int)(first_gps_lon * 1E6);
}
Does someone know why I get that exception cause I can't figure out..thx有人知道为什么我会得到那个异常,因为我无法弄清楚..thx
EDIT:编辑:
I modified to this but still the same error:我对此进行了修改,但仍然出现相同的错误:
time[i]=t;
i=1;
if(time[1]!=0)
{
var=time[1]-time[0];
time[0]=time[1];
i=1;
}
as first you have an if statement which always will be true首先,您有一个 if 语句,该语句始终为真
long [] time=new long[2];长[]时间=新长[2]; if(time.length==2)
如果(时间。长度==2)
and i is never set back to zero so it will keep increasing everytime the location changes so it will get out of bounds并且 i 永远不会设置回零,因此每次位置更改时它都会不断增加,因此它会超出范围
Look at this snippet:看看这个片段:
if(time.length==2)
{
var=time[1]-time[0];
time[0]=time[1];
i=1;
}
i++;
After this, the value of i
is 2, because time.length == 2
is always true
.在此之后,
i
的值为 2,因为time.length == 2
始终为true
。 Next time the method gets called, the line time[i]=t;
下次调用该方法时,行
time[i]=t;
will trigger the ArrayIndexOutOfBoundsException
.将触发
ArrayIndexOutOfBoundsException
。
Later edit:后期编辑:
Better not bother with an array for just two variables.最好不要只为两个变量烦恼一个数组。
// in your activity
long oldTime, newTime, deltaTime;
oldTime = currentTimeMillis();
// in onLocationChanged()
newTime = currentTimeMillis();
deltaTime = (newTime - oldTime) / 1000; // if you need the value in seconds
oldTime = newTime;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.