结对作业之地铁查询系统5
建立SQLite数据库
java
Copy code
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "subway.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE stations (_id INTEGER PRIMARY KEY, name TEXT NOT NULL, line_id INTEGER NOT NULL);");
db.execSQL("CREATE TABLE lines (_id INTEGER PRIMARY KEY, name TEXT NOT NULL, color TEXT NOT NULL);");
db.execSQL("CREATE TABLE station_lines (_id INTEGER PRIMARY KEY, station_id INTEGER NOT NULL, line_id INTEGER NOT NULL, FOREIGN KEY (station_id) REFERENCES stations (_id), FOREIGN KEY (line_id) REFERENCES lines (_id));");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS stations;");
db.execSQL("DROP TABLE IF EXISTS lines;");
db.execSQL("DROP TABLE IF EXISTS station_lines;");
onCreate(db);
}
}
查询路径
java
Copy code
public class PathFinder {
private static final int INFINITY = Integer.MAX_VALUE;
private Graph graph;
private int[] distTo;
private boolean[] marked;
private Edge[] edgeTo;
private PriorityQueue<Station> pq;
public PathFinder(Graph graph) {
this.graph = graph;
}
public void findPath(Station start, Station end) {
distTo = new int[graph.getNumVertices()];
marked = new boolean[graph.getNumVertices()];
edgeTo = new Edge[graph.getNumVertices()];
pq = new PriorityQueue<>(graph.getNumVertices());
for (int v = 0; v < graph.getNumVertices(); v++) {
distTo[v] = INFINITY;
}
distTo[start.getId()] = 0;
pq.add(start);
while (!pq.isEmpty()) {
Station v = pq.poll();
if (v == end) {
break;
}
for (Edge e : graph.getAdjacentEdges(v)) {
Station w = e.getOther(v);
if (distTo[v.getId()] + e.getWeight() < distTo[w.getId()]) {
distTo[w.getId()] = distTo[v.getId()] + e.getWeight();
edgeTo[w.getId()] = e;
if (pq.contains(w)) {
pq.remove(w);
}
pq.add(w);
}
}
}
}
public Iterable<Edge> getPath() {
List<Edge> path = new ArrayList<>();
for (Edge e = edgeTo[graph.getVertexIndex(graph.getEndStation())]; e != null; e = edgeTo[graph.getVertexIndex(e.getOther(graph.getVertex(e)))]) {
path.add(e);
}
Collections.reverse(path);
return path;
}
}
使用百度地图API查询路径
java
Copy code
public class BaiduMapPathFinder {
private static final String AK = "your_ak";
private static final String ROUTE_URL = "http://api.map.baidu.com/directionlite/v1/transit?origin=%s&destination=%s&ak=%s";
private static final int TIMEOUT = 10000;
public static String getRoute(String origin,

浙公网安备 33010602011771号