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.
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
java.lang.ArrayIndexOutOfBoundsException exception at this line:
time[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(Ex开发者_如何学Pythonception 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
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;
}
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
. Next time the method gets called, the line time[i]=t;
will trigger the 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;
as first you have an if statement which always will be true
long [] time=new long[2]; if(time.length==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
精彩评论