如何创建位置向量?

How do I create a vector of Location?

我有一个应用程序可以从 google 服务获取定期位置更新。那工作正常。 现在,我想将每个位置存储在位置向量中:

Vector vectorLocations = new Vector();

onLocationChanged 我这样做是为了添加新位置:

@Override
public void onLocationChanged(Location location) {

    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
    latitud.setText(String.valueOf(location.getLatitude()));
    longitud.setText(String.valueOf(location.getLongitude()));
    tiempo.setText(mLastUpdateTime);
    velocidad.setText(String.valueOf(location.getSpeed()));
    altura.setText(String.valueOf(location.getAltitude()));
    vectorLocations.addElement(location); 
    ntextView.setText(String.valueOf(vectorLocations.lastIndexOf(location)));

}

但是现在我想获取例如位置 3,所以我这样做:

Location positionthree = vectorLocations.elementAt(3);

但我收到类型不兼容的错误:

最好使用 ArrayList。

声明:

ArrayList<Location> locations = new ArrayList<>();        

添加元素:

locations.add(location);

要访问位置的元素:

Location positionThree = locations.get(3);        

但请记住,函数 .get() 中的索引 3 实际上指的是位置 4,因为索引从 0 开始。

如果错误是找到 Object 而不是 Location,您可以将对象强制转换为如下位置:

Location positionthree = (Location) vectorLocations.elementAt(3);

或者更简单的方法是创建 ArrayListLocation 变量并访问它们。您可以执行以下操作:

ArrayList<Location> allLocations = new ArrayList<>();
// On location change
allLocations.add(location);

// When you want to access them
Location positionThree = allLocations.get(3);

希望对您有所帮助!

您需要将 elementAt() 返回的对象转换为如下所示的位置类型

 Location positionthree = (Location) vectorLocations.elementAt(3);