![](/img/trans.png)
[英]Android - java.lang.ArrayIndexOutOfBoundsException
[英]java.lang.ArrayIndexOutOfBoundsException in android
我在 android 中有一个应用程序(我在模拟器上运行它)接收位置更新,我想知道我跟踪的设备的速度。
我通过计算两个连续位置更新之间的距离并计算我收到这些更新的时间来做到这一点。
最后我想通过除以距离和时间来找到速度(这是一个粗略的估计,但我没有其他选择)
这是我的问题:
我有一个长度为 2 的数组,我在其中放置了时间实例....但我得到了
java.lang.ArrayIndexOutOfBoundsException 在这一行出现异常:
时间[i]=t;
这是我的代码:
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);
}
有人知道为什么我会得到那个异常,因为我无法弄清楚..thx
编辑:
我对此进行了修改,但仍然出现相同的错误:
time[i]=t;
i=1;
if(time[1]!=0)
{
var=time[1]-time[0];
time[0]=time[1];
i=1;
}
首先,您有一个 if 语句,该语句始终为真
长[]时间=新长[2]; 如果(时间。长度==2)
并且 i 永远不会设置回零,因此每次位置更改时它都会不断增加,因此它会超出范围
看看这个片段:
if(time.length==2)
{
var=time[1]-time[0];
time[0]=time[1];
i=1;
}
i++;
在此之后, i
的值为 2,因为time.length == 2
始终为true
。 下次调用该方法时,行time[i]=t;
将触发ArrayIndexOutOfBoundsException
。
后期编辑:
最好不要只为两个变量烦恼一个数组。
// 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.