android - 避免sqlite数据库中重复的游标函数
问题描述
我有一个 sqlite 数据库,其中包含运输站,我在数据库中复制了一些站,因为它们位于不同的行中,所以我使用了光标:
@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
float[] results = new float[1];
Database db = new Database(Stations.this);
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("unable to create database");
}
try {
db.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
Cursor c = db.query("Stations", null, null, null, null, null, null);
if (c.moveToFirst()) {
do {
Location.distanceBetween(latitude, longitude, c.getDouble(4), c.getDouble(3), results);
if (results[0] < 1000) {
googleMap.addMarker(new MarkerOptions().position(new LatLng(c.getDouble(4), c.getDouble(3))).title(c.getString(1) + " " + c.getString(2)));
Toast.makeText(this, "nearby station "+ " " + c.getString(2) + "\n", Toast.LENGTH_SHORT).show();
}
}
while (c.moveToNext());
}
if (googleMap != null) {
LatLng googleLocation = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(googleLocation));
}
}
这将显示站点,但如果该站点在数据库中被提及两次,则会出现重复,我该如何处理这个问题并且不显示已经看到的站点,因为知道 2 个站点具有不同的 id 但名称相同?
解决方案
您可以NOT EXISTS
在查询中使用:
select s.* from stations s
where not exists (
select 1 from stations
where station_name = s.station_name and station_id < s.station_id
)
代替:
Cursor c = db.query("Stations", null, null, null, null, null, null);
和:
String sql = "select s.* from stations s where not exists (select 1 from stations where station_name = s.station_name and station_id < s.station_id)";
Cursor c = db.rawQuery(sql, null);
推荐阅读
- mysql - #1146 表 'db.tablename' 不存在
- pandas - 在类中交换值
- android - Android bottomNavigationView 按主题设置样式
- ruby - Chef : 在节点上将 jenkins 代理作为后台进程运行
- swift - 进程一直停留在被中断的地方,使用“thread return -x”返回表达式求值前的状态
- javascript - 如何在jquery的每个循环中包装All
- r - 根据其他两个变量在数据框中创建一个新变量
- angularjs - 单元测试 - AngularJS1 和 Jasmine
- pascal - 线性方程,不兼容的类型 BOOLEAN/LONGINT
- python - Paho 连接问题 - Mosquitto:与代理通信时发生网络协议错误