diff options
author | Christopher Baines <cbaines8@gmail.com> | 2012-03-14 01:01:14 +0000 |
---|---|---|
committer | Christopher Baines <cbaines8@gmail.com> | 2012-03-14 01:01:14 +0000 |
commit | 5bac2465e7ee4e136ebec0b65f8e52ef8b4df232 (patch) | |
tree | 1ccd78f3152c19de6c7f14861b1a7d2d7ae92efa /src/net | |
parent | 93c8cd480ea46d49dd7ad1ba9515443797a4a8c1 (diff) | |
parent | 19e189ef9ed67f382fea00e48f997ce8e979f030 (diff) | |
download | southamptonuniversitymap-5bac2465e7ee4e136ebec0b65f8e52ef8b4df232.tar southamptonuniversitymap-5bac2465e7ee4e136ebec0b65f8e52ef8b4df232.tar.gz |
Merge branch 'dev'
Diffstat (limited to 'src/net')
19 files changed, 945 insertions, 822 deletions
diff --git a/src/net/cbaines/suma/Building.java b/src/net/cbaines/suma/Building.java index 84c9b6c..38c8265 100644 --- a/src/net/cbaines/suma/Building.java +++ b/src/net/cbaines/suma/Building.java @@ -59,6 +59,6 @@ public class Building extends POI { } public String toString() { - return name + " (" + id + ")"; + return name; } } diff --git a/src/net/cbaines/suma/BuildingNumOverlay.java b/src/net/cbaines/suma/BuildingNumOverlay.java index f11a166..8ec5ec4 100644 --- a/src/net/cbaines/suma/BuildingNumOverlay.java +++ b/src/net/cbaines/suma/BuildingNumOverlay.java @@ -94,33 +94,24 @@ public class BuildingNumOverlay extends Overlay implements Preferences, OnShared } /** - * Draw a marker on each of our items. populate() must have been called - * first.<br/> + * Draw a marker on each of our items. populate() must have been called first.<br/> * <br/> - * The marker will be drawn twice for each Item in the Overlay--once in the - * shadow phase, skewed and darkened, then again in the non-shadow phase. - * The bottom-center of the marker will be aligned with the geographical - * coordinates of the Item.<br/> + * The marker will be drawn twice for each Item in the Overlay--once in the shadow phase, skewed and darkened, then again in + * the non-shadow phase. The bottom-center of the marker will be aligned with the geographical coordinates of the Item.<br/> * <br/> - * The order of drawing may be changed by overriding the getIndexToDraw(int) - * method. An item may provide an alternate marker via its - * OverlayItem.getMarker(int) method. If that method returns null, the - * default marker is used.<br/> + * The order of drawing may be changed by overriding the getIndexToDraw(int) method. An item may provide an alternate marker + * via its OverlayItem.getMarker(int) method. If that method returns null, the default marker is used.<br/> * <br/> - * The focused item is always drawn last, which puts it visually on top of - * the other items.<br/> + * The focused item is always drawn last, which puts it visually on top of the other items.<br/> * * @param canvas - * the Canvas upon which to draw. Note that this may already have - * a transformation applied, so be sure to leave it the way you - * found it + * the Canvas upon which to draw. Note that this may already have a transformation applied, so be sure to leave it + * the way you found it * @param mapView - * the MapView that requested the draw. Use - * MapView.getProjection() to convert between on-screen pixels - * and latitude/longitude pairs + * the MapView that requested the draw. Use MapView.getProjection() to convert between on-screen pixels and + * latitude/longitude pairs * @param shadow - * if true, draw the shadow layer. If false, draw the overlay - * contents. + * if true, draw the shadow layer. If false, draw the overlay contents. */ @Override public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) { @@ -144,8 +135,7 @@ public class BuildingNumOverlay extends Overlay implements Preferences, OnShared final SharedPreferences favouritesPrefs = context.getSharedPreferences(FAVOURITES_PREFERENCES, 0); /* - * Draw in backward cycle, so the items with the least index are on the - * front. + * Draw in backward cycle, so the items with the least index are on the front. */ for (Iterator<Building> buildingIter = buildings.iterator(); buildingIter.hasNext();) { final Building building = buildingIter.next(); @@ -219,8 +209,7 @@ public class BuildingNumOverlay extends Overlay implements Preferences, OnShared if (showIdentifiers) { str += " (" + building.id + ")"; } - context.makeToast(str, context.getResources().getString(R.string.map_activity_toast_help_message), - Toast.LENGTH_SHORT); + context.makeToast(str, context.getResources().getString(R.string.map_activity_toast_help_message), Toast.LENGTH_SHORT); return true; } @@ -230,7 +219,7 @@ public class BuildingNumOverlay extends Overlay implements Preferences, OnShared public boolean onDoubleTap(final MotionEvent event, final MapView mapView) { if (!this.isEnabled()) return false; - + Building building = getSelectedItem(event, mapView); if (building == null) { @@ -256,6 +245,14 @@ public class BuildingNumOverlay extends Overlay implements Preferences, OnShared if (!this.isEnabled()) return false; + int pointerCount = event.getPointerCount(); + if (pointerCount > 1) { + Log.v(TAG, "Detected a zoom " + pointerCount); + return false; + } else { + Log.v(TAG, "Zoom not detected " + pointerCount); + } + final Building building = getSelectedItem(event, mapView); if (building == null) { @@ -265,19 +262,27 @@ public class BuildingNumOverlay extends Overlay implements Preferences, OnShared Log.v(TAG, "building Pressed " + building.id); final SharedPreferences favouritesPrefs = context.getSharedPreferences(FAVOURITES_PREFERENCES, 0); + // final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); if (favouritesPrefs.getBoolean(building.id, false)) { favouritesPrefs.edit().remove(building.id).commit(); - context.makeToast(building.id + " removed from favourites", Toast.LENGTH_SHORT); + // if (sharedPrefs.getBoolean(SHOW_IDENTIFIERS, SHOW_IDENTIFIERS_ENABLED_BY_DEFAULT)) { + context.makeToast(building.name + " removed from favourites", "(" + building.id + ")", Toast.LENGTH_SHORT); + // } else { + // context.makeToast(building.name + " removed from favourites", Toast.LENGTH_SHORT); + // } } else { - context.makeToast(building.id + " made a favourite", Toast.LENGTH_SHORT); + // if (sharedPrefs.getBoolean(SHOW_IDENTIFIERS, SHOW_IDENTIFIERS_ENABLED_BY_DEFAULT)) { + context.makeToast(building.name + " added to favourites", "(" + building.id + ")", Toast.LENGTH_SHORT); + // } else { + // context.makeToast(building.name + " added to favourites", Toast.LENGTH_SHORT); + // } favouritesPrefs.edit().putBoolean(building.id, true).commit(); } - Collections.sort(buildings, - new POIFavouriteComparator(context.getSharedPreferences(FAVOURITES_PREFERENCES, 0))); + Collections.sort(buildings, new POIFavouriteComparator(context.getSharedPreferences(FAVOURITES_PREFERENCES, 0))); mapView.invalidate(); @@ -310,8 +315,7 @@ public class BuildingNumOverlay extends Overlay implements Preferences, OnShared public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.i(TAG, "Got a favourites change in the BuildingNumOverlay for key " + key); - Collections - .sort(buildings, new POIFavouriteComparator(context.getSharedPreferences(FAVOURITES_PREFERENCES, 0))); + Collections.sort(buildings, new POIFavouriteComparator(context.getSharedPreferences(FAVOURITES_PREFERENCES, 0))); } } diff --git a/src/net/cbaines/suma/Bus.java b/src/net/cbaines/suma/Bus.java index 865384f..9894e6b 100644 --- a/src/net/cbaines/suma/Bus.java +++ b/src/net/cbaines/suma/Bus.java @@ -115,7 +115,7 @@ public class Bus { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + gid; + result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @@ -128,7 +128,10 @@ public class Bus { if (getClass() != obj.getClass()) return false; Bus other = (Bus) obj; - if (id != other.id) + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) return false; return true; } diff --git a/src/net/cbaines/suma/BusStop.java b/src/net/cbaines/suma/BusStop.java index 85f6d01..3bfd9a4 100644 --- a/src/net/cbaines/suma/BusStop.java +++ b/src/net/cbaines/suma/BusStop.java @@ -71,6 +71,6 @@ public class BusStop extends POI { } public String toString() { - return description + " (" + id + ")"; + return description; } } diff --git a/src/net/cbaines/suma/BusStopActivity.java b/src/net/cbaines/suma/BusStopActivity.java index b80d5b4..e28086a 100644 --- a/src/net/cbaines/suma/BusStopActivity.java +++ b/src/net/cbaines/suma/BusStopActivity.java @@ -308,7 +308,7 @@ public class BusStopActivity extends ToastHelperActivity implements OnCheckedCha return timetable; } - private class GetTimetableTask extends AsyncTask<String, Integer, Timetable> { + private class GetTimetableTask extends AsyncTask<String, Integer, Timetable> { String errorMessage; protected void onPreExecute() { @@ -337,7 +337,8 @@ public class BusStopActivity extends ToastHelperActivity implements OnCheckedCha errorMessage = "Error parsing bus times"; e.printStackTrace(); } catch (Exception e) { - Log.e(TAG, e.getMessage(), e.getCause()); + Log.e(TAG, "Exception in new timetable " + e.getMessage(), e.getCause()); + e.printStackTrace(); } return newTimetable; diff --git a/src/net/cbaines/suma/BusStopOverlay.java b/src/net/cbaines/suma/BusStopOverlay.java index 778b306..b8377cf 100644 --- a/src/net/cbaines/suma/BusStopOverlay.java +++ b/src/net/cbaines/suma/BusStopOverlay.java @@ -110,8 +110,7 @@ public class BusStopOverlay extends Overlay implements RouteColorConstants, Pref final SharedPreferences favouritesPreferences = context.getSharedPreferences(FAVOURITES_PREFERENCES, 0); /* - * Draw in backward cycle, so the items with the least index are on the - * front. + * Draw in backward cycle, so the items with the least index are on the front. */ for (int stopNum = 0; stopNum < busStops.size(); stopNum++) { @@ -184,9 +183,9 @@ public class BusStopOverlay extends Overlay implements RouteColorConstants, Pref Log.e(TAG, "Unknown route code"); } - canvas.drawRect(rectLeft, mCurScreenCoords.y - + ((yOfsetPerMarker * makersPlaced) - (45 * scale)), rectRight, mCurScreenCoords.y - + (yOfsetPerMarker * makersPlaced) - ((45 * scale) - markerYSize), paint); + canvas.drawRect(rectLeft, mCurScreenCoords.y + ((yOfsetPerMarker * makersPlaced) - (45 * scale)), + rectRight, mCurScreenCoords.y + (yOfsetPerMarker * makersPlaced) - ((45 * scale) - markerYSize), + paint); makersPlaced++; } @@ -210,8 +209,7 @@ public class BusStopOverlay extends Overlay implements RouteColorConstants, Pref if (showIdentifiers) { str += " (" + busStop.id + ")"; } - context.makeToast(str, context.getResources().getString(R.string.map_activity_toast_help_message), - Toast.LENGTH_SHORT); + context.makeToast(str, context.getResources().getString(R.string.map_activity_toast_help_message), Toast.LENGTH_SHORT); return true; } @@ -250,21 +248,28 @@ public class BusStopOverlay extends Overlay implements RouteColorConstants, Pref } else { Log.i(TAG, "Pressed " + busStop.id); - SharedPreferences favouritesPreferences = context.getSharedPreferences(FAVOURITES_PREFERENCES, 0); + final SharedPreferences favouritesPreferences = context.getSharedPreferences(FAVOURITES_PREFERENCES, 0); + final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); if (favouritesPreferences.getBoolean(busStop.id, false)) { favouritesPreferences.edit().remove(busStop.id).commit(); - context.makeToast(busStop.id + " removed from favourites", Toast.LENGTH_SHORT); - + if (sharedPrefs.getBoolean(SHOW_IDENTIFIERS, SHOW_IDENTIFIERS_ENABLED_BY_DEFAULT)) { + context.makeToast(busStop.description + " removed from favourites", "(" + busStop.id + ")", + Toast.LENGTH_SHORT); + } else { + context.makeToast(busStop.description + " removed from favourites", Toast.LENGTH_SHORT); + } } else { - context.makeToast(busStop.id + " made a favourite", Toast.LENGTH_SHORT); - + if (sharedPrefs.getBoolean(SHOW_IDENTIFIERS, SHOW_IDENTIFIERS_ENABLED_BY_DEFAULT)) { + context.makeToast(busStop.description + " added to favourites", "(" + busStop.id + ")", Toast.LENGTH_SHORT); + } else { + context.makeToast(busStop.description + " added to favourites", Toast.LENGTH_SHORT); + } favouritesPreferences.edit().putBoolean(busStop.id, true).commit(); } - Collections.sort(busStops, - new POIFavouriteComparator(context.getSharedPreferences(FAVOURITES_PREFERENCES, 0))); + Collections.sort(busStops, new POIFavouriteComparator(context.getSharedPreferences(FAVOURITES_PREFERENCES, 0))); mapView.invalidate(); diff --git a/src/net/cbaines/suma/BusStopSpecificStopView.java b/src/net/cbaines/suma/BusStopSpecificStopView.java index b7a16cb..eade3fe 100644 --- a/src/net/cbaines/suma/BusStopSpecificStopView.java +++ b/src/net/cbaines/suma/BusStopSpecificStopView.java @@ -149,7 +149,8 @@ public class BusStopSpecificStopView extends LinearLayout implements OnClickList busDao.refresh(stop.bus); busRouteDao.refresh(stop.bus.route); - Log.i("StopView", "Bus route " + stop.bus.route + " Uni-Link " + stop.bus.route.uniLink + " Bus ID " + stop.bus.id); + Log.i("StopView", "Bus route " + stop.bus.route + " Uni-Link " + stop.bus.route.uniLink + " Bus ID " + + stop.bus.id); if (stop.bus.id != null && stop.bus.route.uniLink) { Uri uri = Uri.parse("http://id.southampton.ac.uk/bus/" + stop.bus.id); diff --git a/src/net/cbaines/suma/DataManager.java b/src/net/cbaines/suma/DataManager.java index 08425a7..8b04928 100644 --- a/src/net/cbaines/suma/DataManager.java +++ b/src/net/cbaines/suma/DataManager.java @@ -75,6 +75,56 @@ public class DataManager { private static Dao<Bus, Integer> busDao; private static Dao<BusStop, String> busStopDao; + static void createDatabase(final Context context) throws SQLException, IOException { + Log.i(TAG, "Begining loading databases"); + + DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class); + + Dao<Building, String> buildingDao; + + buildingDao = helper.getBuildingDao(); + + long buildingCount = buildingDao.countOf(); + Log.i(TAG, "Building count " + buildingCount); + if (buildingCount < 260) { + + loadBuildings(context); + Log.i(TAG, "Loaded building database"); + + } + + Dao<BusStop, String> busStopDao = helper.getBusStopDao(); + Dao<BusRoute, Integer> busRouteDao = helper.getBusRouteDao(); + Dao<RouteStop, Integer> routeStopsDao = helper.getRouteStopsDao(); + + long busStopCount = busStopDao.countOf(); + long busRouteCount = busRouteDao.countOf(); + long routeStopsCount = routeStopsDao.countOf(); + + Log.i(TAG, "BusStop count " + busStopCount); + Log.i(TAG, "BusRoute count " + busRouteCount); + Log.i(TAG, "RouteStops count " + routeStopsCount); + if (busStopCount < 217 || busRouteCount < 5 || routeStopsCount < 327) { + + loadBusData(context, true); + Log.i(TAG, "Loaded bus stop database"); + + } + + Dao<Site, String> siteDao = helper.getSiteDao(); + + long siteCount = siteDao.countOf(); + Log.i(TAG, "Sites count " + siteCount); + if (siteCount < 21) { + + loadSiteData(context); + + } + + Log.i(TAG, "Finished loading databases"); + + } + public static void loadBuildings(Context context) throws SQLException, IOException { DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class); Dao<Building, String> buildingDao = helper.getBuildingDao(); @@ -407,9 +457,10 @@ public class DataManager { GeoPoint point = null; if (dataBits[2].length() > 1 && dataBits[3].length() > 1) { - point = Util.csLatLongToGeoPoint(dataBits[2], dataBits[3]); + point = Util.csLatLongToGeoPoint(dataBits[3], dataBits[2]); } else { - point = new GeoPoint(0, 0); + Log.e(TAG, "Missing point for site " + dataBits[1]); + throw new RuntimeException(); } Polygon poly = Util.csPolygonToPolygon(strLine.split("\"")[1]); @@ -438,10 +489,10 @@ public class DataManager { Dao<RouteStop, Integer> routeStopsDao = null; if (routeStopsDao == null) routeStopsDao = helper.getRouteStopsDao(); - if (busDao == null) - busDao = helper.getBusDao(); if (busStopDao == null) busStopDao = helper.getBusStopDao(); + if (busDao == null) + busDao = helper.getBusDao(); String time = stopObj.getString("time"); @@ -554,7 +605,8 @@ public class DataManager { List<RouteStop> routeStops = routeStopsDao.query(routeStopsPreparedQuery); if (routeStops.size() > 0) { - // Log.i(TAG, "Found " + routeStops.size() + " stops matching the destStop " + destStop + " on route " + + // Log.i(TAG, "Found " + routeStops.size() + + // " stops matching the destStop " + destStop + " on route " + // route.code); } else { Log.w(TAG, "Found " + routeStops.size() + " stops matching the destStop " + destStop + " on route " + route.code); @@ -643,6 +695,7 @@ public class DataManager { if (route != null) { busRoutes.add(route); } else { + Log.e(TAG, "Route not found " + key.substring(key.length() - 3, key.length()) + " " + key); throw new RuntimeException("Route not found " + key.substring(key.length() - 3, key.length()) + " " + key); } } @@ -655,12 +708,14 @@ public class DataManager { JSONObject stopObj = stopsArray.getJSONObject(stopNum); if (!keepNonUniLink && !stopObj.getString("name").startsWith("U")) { - // Log.v(TAG, "Skipping non uni-link stop " + stopObj.getString("name")); + // Log.v(TAG, "Skipping non uni-link stop " + + // stopObj.getString("name")); continue; } if (!keepUniLink && stopObj.getString("name").startsWith("U")) { - // Log.v(TAG, "Skipping uni-link stop " + stopObj.getString("name")); + // Log.v(TAG, "Skipping uni-link stop " + + // stopObj.getString("name")); continue; } @@ -751,7 +806,8 @@ public class DataManager { continue; } - // Log.v(TAG, "Found stop for a unidentified " + stop.bus.toString() + " at " + stop.busStop.id + " at " + // Log.v(TAG, "Found stop for a unidentified " + + // stop.bus.toString() + " at " + stop.busStop.id + " at " // + stop.arivalTime); timetable.add(stop); diff --git a/src/net/cbaines/suma/DatabaseHelper.java b/src/net/cbaines/suma/DatabaseHelper.java index 17ef720..d039518 100644 --- a/src/net/cbaines/suma/DatabaseHelper.java +++ b/src/net/cbaines/suma/DatabaseHelper.java @@ -19,11 +19,6 @@ package net.cbaines.suma; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.sql.SQLException; import android.content.Context; @@ -35,12 +30,7 @@ import com.j256.ormlite.dao.Dao; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; -public class DatabaseHelper extends OrmLiteSqliteOpenHelper { - - private static final String DATABASE_PATH = "/data/data/net.cbaines.suma/databases/"; - private static final String DATABASE_NAME = "data.db"; - - private static final int DATABASE_VERSION = 41; +public class DatabaseHelper extends OrmLiteSqliteOpenHelper implements Preferences { private static final String TAG = "DatabaseHelper"; @@ -52,24 +42,25 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private Dao<Site, String> siteDao = null; private Dao<Bus, Integer> busDao = null; - private Context context; + volatile boolean doneUpgrade = false; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config); Log.i(TAG, "Database Helper created"); - this.context = context; } @Override public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { - Log.i(DatabaseHelper.class.getName(), "onCreate"); + Log.i(TAG, "onCreate"); + TableUtils.createTable(connectionSource, Building.class); TableUtils.createTable(connectionSource, BusStop.class); TableUtils.createTable(connectionSource, BusRoute.class); TableUtils.createTable(connectionSource, RouteStop.class); TableUtils.createTable(connectionSource, Site.class); TableUtils.createTable(connectionSource, Bus.class); + } catch (SQLException e) { Log.e(DatabaseHelper.class.getName(), "Can't create database", e); throw new RuntimeException(e); @@ -78,13 +69,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { @Override public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) { - try { - Log.i(DatabaseHelper.class.getName(), "onUpgrade"); - copyDataBase(); - } catch (IOException e) { - e.printStackTrace(); - } + Log.i(TAG, "onUpgrade"); } @@ -153,90 +139,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { * * @return true if it exists, false if it doesn't */ - public boolean checkDataBase() { - Log.i(TAG, "Check database"); - - /* - * SQLiteDatabase checkDB = null; - * - * try { String myPath = DATABASE_PATH + DATABASE_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, - * SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { - * - * // database does't exist yet. - * - * } - * - * if (checkDB != null) { - * - * checkDB.close(); - * - * } - * - * Log.i(TAG, "Finished checking database"); return checkDB != null ? true : false; - */ - - File dbFile = new File(DATABASE_PATH + DATABASE_NAME); - return dbFile.exists(); - } - - /** - * Copies your database from your local assets-folder to the just created empty database in the system folder, from where it - * can be accessed and handled. This is done by transfering bytestream. - * */ - public void copyDataBase() throws IOException { - Log.i(TAG, "Begining copy database"); - - InputStream myInput = context.getAssets().open(DATABASE_NAME); - - // Path to the just created empty db - String outFileName = DATABASE_PATH + DATABASE_NAME; - - File database = new File(outFileName); - if (database.exists()) { - database.delete(); - } - - // Open the empty db as the output stream - OutputStream myOutput = new FileOutputStream(outFileName); - - // transfer bytes from the inputfile to the outputfile - byte[] buffer = new byte[1024]; - int length; - while ((length = myInput.read(buffer)) > 0) { - myOutput.write(buffer, 0, length); - } - - // Close the streams - myOutput.flush(); - myOutput.close(); - myInput.close(); - - // getWritableDatabase().close(); - - Log.i(TAG, "Finished copying db"); - - } - - /** - * Creates a empty database on the system and rewrites it with your own database. - * */ - public void createDataBase() throws IOException { - - boolean dbExist = checkDataBase(); - - if (dbExist) { - // do nothing - database already exist - } else { - - try { - Log.i(TAG, "Copy database"); - copyDataBase(); - } catch (IOException e) { - throw new Error("Error copying database"); - } - } - - } /** * Close the database connections and clear any cached DAOs. diff --git a/src/net/cbaines/suma/FavouritesDialog.java b/src/net/cbaines/suma/FavouritesDialog.java new file mode 100644 index 0000000..0884b63 --- /dev/null +++ b/src/net/cbaines/suma/FavouritesDialog.java @@ -0,0 +1,11 @@ +package net.cbaines.suma; + +import android.content.Context; + +public class FavouritesDialog extends POIDialog implements Preferences { + + public FavouritesDialog(Context context) { + super(context); + } + +} diff --git a/src/net/cbaines/suma/FindActivity.java b/src/net/cbaines/suma/FindActivity.java deleted file mode 100644 index 669249c..0000000 --- a/src/net/cbaines/suma/FindActivity.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * Southampton University Map App - * Copyright (C) 2011 Christopher Baines - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package net.cbaines.suma; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.osmdroid.util.GeoPoint; - -import android.content.Context; -import android.content.Intent; -import android.location.Location; -import android.location.LocationListener; -import android.location.LocationManager; -import android.net.Uri; -import android.os.Bundle; -import android.text.Editable; -import android.text.TextWatcher; -import android.util.Log; -import android.view.Gravity; -import android.view.View; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.AdapterView.OnItemLongClickListener; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.ProgressBar; - -import com.j256.ormlite.android.apptools.OrmLiteBaseActivity; -import com.j256.ormlite.dao.Dao; -import com.j256.ormlite.stmt.PreparedQuery; -import com.j256.ormlite.stmt.QueryBuilder; - -public class FindActivity extends OrmLiteBaseActivity<DatabaseHelper> implements Runnable, TextWatcher, - OnItemClickListener, LocationListener, OnItemLongClickListener { - - final static String TAG = "FindActivity"; - - private EditText searchBar; - private ListView listItems; - private ProgressBar progBar; - private LinearLayout findContentLayout; - - private String searchTerm = ""; - - private Dao<Building, String> buildingDao; - private Dao<BusStop, String> busStopDao; - private Dao<Site, String> siteDao; - - private POIArrayAdapter adapter; - - private GeoPoint userLocation; - - private Thread searchThread; - - ArrayList<POI> getNearestPOIs(int distance) { - Log.i(TAG, "Getting nearest POI's"); - ArrayList<POI> nearestPOIs = new ArrayList<POI>(); - for (Iterator<Building> buildingDaoIter = buildingDao.iterator(); buildingDaoIter.hasNext();) { - POI poi = buildingDaoIter.next(); - int dist = poi.point.distanceTo(userLocation); - if (dist < distance) { - poi.distTo = dist; - nearestPOIs.add(poi); - } - } - - for (Iterator<BusStop> busStopDaoIter = busStopDao.iterator(); busStopDaoIter.hasNext();) { - POI poi = busStopDaoIter.next(); - int dist = poi.point.distanceTo(userLocation); - if (dist < distance) { - poi.distTo = dist; - nearestPOIs.add(poi); - } - } - - Collections.sort(nearestPOIs, new POIDistanceComparator(userLocation, true)); - - Log.i(TAG, "Got " + nearestPOIs.size() + " nearest POI's"); - return nearestPOIs; - } - - // Search thread - public void run() { - POIArrayAdapter tempAdaptor; - GeoPoint thisUserLocation = userLocation; - - Log.i(TAG, "Search thread started"); - String thisSearchTerm = searchTerm; - - ArrayList<POI> foundPOIsArray = null; - - Log.i(TAG, "Search term length " + thisSearchTerm.length() + " userLocation == null " - + (thisUserLocation == null)); - if (thisSearchTerm.length() == 0 && thisUserLocation != null) { - foundPOIsArray = getNearestPOIs(200); - - } - - if (foundPOIsArray != null && foundPOIsArray.size() != 0) { - - tempAdaptor = new POIArrayAdapter(this, foundPOIsArray); - } else { - - try { - - foundPOIsArray = new ArrayList<POI>(); - - if (thisSearchTerm.length() == 0) { - for (Building building : buildingDao) { - foundPOIsArray.add(building); - } - - if (!thisSearchTerm.equals(searchTerm)) - return; - - for (BusStop busStop : busStopDao) { - foundPOIsArray.add(busStop); - } - - if (!thisSearchTerm.equals(searchTerm)) - return; - - for (Site site : siteDao) { - foundPOIsArray.add(site); - } - - } else { - - QueryBuilder<Building, String> buildingQueryBuilder = buildingDao.queryBuilder(); - buildingQueryBuilder.where().like(Building.ID_FIELD_NAME, "%" + thisSearchTerm + "%").or() - .like(Building.NAME_FIELD_NAME, "%" + thisSearchTerm + "%"); - PreparedQuery<Building> buildingPreparedQuery = buildingQueryBuilder.prepare(); - List<Building> buildings = buildingDao.query(buildingPreparedQuery); - for (Building building : buildings) { - foundPOIsArray.add(building); - } - buildings = null; - - if (!thisSearchTerm.equals(searchTerm)) - return; - - if (thisSearchTerm.contains("site")) { - for (Site site : siteDao) { - foundPOIsArray.add(site); - } - } else { - QueryBuilder<Site, String> siteQueryBuilder = siteDao.queryBuilder(); - siteQueryBuilder.where().like(Site.ID_FIELD_NAME, "%" + thisSearchTerm + "%").or() - .like(Site.NAME_FIELD_NAME, "%" + thisSearchTerm + "%"); - PreparedQuery<Site> sitePreparedQuery = siteQueryBuilder.prepare(); - List<Site> sites = siteDao.query(sitePreparedQuery); - for (Site site : sites) { - foundPOIsArray.add(site); - } - sites = null; - } - - if (!thisSearchTerm.equals(searchTerm)) - return; - - // if (thisSearchTerm.contains("bus")) { - // for (BusStop busStop : busStopDao) { - // foundPOIsArray.add(busStop); - // } - // } else { - QueryBuilder<BusStop, String> busStopQueryBuilder = busStopDao.queryBuilder(); - busStopQueryBuilder.where().like(BusStop.ID_FIELD_NAME, "%" + thisSearchTerm + "%").or() - .like(BusStop.DESCRIPTION_FIELD_NAME, "%" + thisSearchTerm + "%"); - PreparedQuery<BusStop> busStopPreparedQuery = busStopQueryBuilder.prepare(); - List<BusStop> busStops = busStopDao.query(busStopPreparedQuery); - for (BusStop busStop : busStops) { - foundPOIsArray.add(busStop); - } - busStops = null; - // } - - if (!thisSearchTerm.equals(searchTerm)) - return; - - Log.i(TAG, "Found " + foundPOIsArray.size() + " pois"); - - if (thisUserLocation != null) { - Collections.sort(foundPOIsArray, new POIDistanceComparator(userLocation)); - } else { - Collections.sort(foundPOIsArray, new StringDistanceComparator(thisSearchTerm)); - } - - } - - if (!thisSearchTerm.equals(searchTerm)) - return; - - tempAdaptor = new POIArrayAdapter(this, foundPOIsArray); - - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return; - } - } - - if (thisSearchTerm.equals(searchTerm)) { - Log.i(TAG, "Search terms still equal, starting post"); - adapter = tempAdaptor; - listItems.post(new Runnable() { - public void run() { - listItems.setAdapter(adapter); - if (progBar.getVisibility() != View.GONE) { - progBar.setVisibility(View.GONE); - findContentLayout.setGravity(Gravity.TOP); - } - } - }); - } else { - Log.i(TAG, "Search terms no longer equal, exiting"); - } - } - - /** Called when the activity is first created. */ - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.find_activity); - - searchBar = (EditText) findViewById(R.id.searchBar); - searchBar.addTextChangedListener(this); - - listItems = (ListView) findViewById(R.id.findListItems); - listItems.setOnItemClickListener(this); - listItems.setOnItemLongClickListener(this); - - progBar = (ProgressBar) findViewById(R.id.findLoadBar); - findContentLayout = (LinearLayout) findViewById(R.id.findContentLayout); - - try { - buildingDao = getHelper().getBuildingDao(); - busStopDao = getHelper().getBusStopDao(); - siteDao = getHelper().getSiteDao(); - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - // Acquire a reference to the system Location Manager - LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); - Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); - if (lastKnownLocation != null) { - userLocation = Util.locationToGeoPoint(lastKnownLocation); - } else { - lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); - if (lastKnownLocation != null) { - userLocation = Util.locationToGeoPoint(lastKnownLocation); - - } - } - // Register the listener with the Location Manager to receive location - // updates - locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, this); - try { - locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, this); - } catch (Exception e) { - // Ignore anything that goes wrong here... - } - - searchThread = new Thread(this); - searchThread.start(); - - } - - public void afterTextChanged(Editable s) { - searchTerm = s.toString(); - Log.i(TAG, "Text changed " + searchTerm + " starting search thread"); - new Thread(this).start(); - } - - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - public void onTextChanged(CharSequence s, int start, int before, int count) { - } - - public void onItemClick(AdapterView<?> parent, View view, int position, long id) { - Log.i(TAG, "OnItemClick pos " + position + " id " + id); - - POI poi = adapter.getPOIItem(position); - - Uri uri = Uri.parse("geo:" + Util.E6IntToDouble(poi.point.getLatitudeE6()) + "," - + Util.E6IntToDouble(poi.point.getLongitudeE6()) + "?z=18"); - - Log.i(TAG, "Starting a activity for " + uri); - - Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri); - startActivity(mapIntent); - } - - public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { - - POI poi = adapter.getPOIItem(position); - - Log.i(TAG, "Long Click Event ID: " + poi.id); - Uri uri = null; - - if (poi.type.equals(POI.BUS_STOP)) { - Log.i(TAG, "Its a bus stop"); - - BusStop busStop = (BusStop) poi; - - uri = Uri.parse("http://id.southampton.ac.uk/bus-stop/" + busStop.id); - - } else if (poi.type.equals(POI.BUILDING)) { - Log.i(TAG, "Its a buildings"); - - Building building = (Building) poi; - - uri = Uri.parse("http://id.southampton.ac.uk/building/" + building.id); - } else { - Log.e(TAG, "Error in onItemLongClick"); - return false; - } - - Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath()); - - Intent busStopIntent = new Intent(Intent.ACTION_VIEW, uri); - startActivity(busStopIntent); - - return true; - } - - public void onLocationChanged(Location location) { - Log.i(TAG, "Got location update for FindActivity"); - userLocation = Util.locationToGeoPoint(location); - if (!searchThread.isAlive()) { - searchThread = new Thread(this); - searchThread.start(); - } - } - - public void onProviderDisabled(String arg0) { - } - - public void onProviderEnabled(String provider) { - } - - public void onStatusChanged(String provider, int status, Bundle extras) { - } -}
\ No newline at end of file diff --git a/src/net/cbaines/suma/MapActivity.java b/src/net/cbaines/suma/MapActivity.java index cc7d7b9..58c7918 100644 --- a/src/net/cbaines/suma/MapActivity.java +++ b/src/net/cbaines/suma/MapActivity.java @@ -19,8 +19,11 @@ package net.cbaines.suma; +import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; @@ -42,11 +45,13 @@ import org.osmdroid.views.util.constants.MapViewConstants; import android.app.AlertDialog; import android.app.Dialog; +import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; +import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; @@ -63,20 +68,16 @@ import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.stmt.PreparedQuery; +import com.j256.ormlite.stmt.QueryBuilder; /** * * @author Christopher Baines <cbaines8@gmail.com> * */ -public class MapActivity extends ToastHelperActivity implements MapViewConstants, Runnable, RouteColorConstants, - OnItemClickListener, OnItemLongClickListener, OnSharedPreferenceChangeListener, Preferences { - - /** - * Enable to use the database in the assets folder, if its not enabled, the database is built from the csv files in the assets - * folder - */ - private boolean useBundledDatabase = true; +public class MapActivity extends ToastHelperActivity implements MapViewConstants, RouteColorConstants, OnItemClickListener, + OnItemLongClickListener, OnSharedPreferenceChangeListener, Preferences { private MapView mapView; private MapController mapController; @@ -86,7 +87,12 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants static final int VIEW_DIALOG_ID = 0; static final int FAVOURITE_DIALOG_ID = 1; - private POIDialog favDialog; + static final int WELCOME_DIALOG_ID = 2; + static final int SEARCH_RESULTS_DIALOG_ID = 3; + + private ArrayList<POI> searchResults = null; + + private FavouritesDialog favDialog; private HashMap<String, Overlay> overlays = new HashMap<String, Overlay>(); private HashMap<String, Overlay> pastOverlays; @@ -173,6 +179,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants private MapActivity instance; + private SearchResultsDialog searchResultsDialog; + private static final String TAG = "MapActivity"; @SuppressWarnings("unchecked") @@ -183,8 +191,45 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants instance = this; - Thread databaseThread = new Thread(this); // Start the database thread - databaseThread.start(); + try { + File dbFile = new File(DATABASE_PATH + DATABASE_NAME); + if (dbFile.exists()) { + Log.i(TAG, "Database exists"); + + SQLiteDatabase checkDB = SQLiteDatabase.openDatabase(DATABASE_PATH + DATABASE_NAME, null, + SQLiteDatabase.OPEN_READONLY); + int version = checkDB.getVersion(); + checkDB.close(); + + if (version != DATABASE_VERSION) { + Log.i(TAG, "Not the right version"); + + copyDatabase(); + } + } else { + Log.i(TAG, "Database does not exist"); + + SQLiteDatabase db = getHelper().getWritableDatabase(); + + if (USE_BUNDLED_DATABASE) { + db.close(); + + copyDatabase(); + } else { + Log.i(TAG, "Creating database"); + + try { + DataManager.createDatabase(instance); + } catch (SQLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } setContentView(R.layout.map_activity); @@ -206,13 +251,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants myLocationOverlay.setEnabled(true); Log.i(TAG, "Finished creating myLocationOverlay"); - while (databaseThread.isAlive()) { - Thread.yield(); - } - new Thread(new Runnable() { public void run() { - Thread.currentThread().setPriority(Thread.MAX_PRIORITY); try { showOverlays(); } catch (SQLException e) { @@ -226,57 +266,163 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants mapController = mapView.getController(); mResourceProxy = new DefaultResourceProxyImpl(getApplicationContext()); - GeoPoint userLocation = null; + GeoPoint startLocation = null; - Bundle extras = getIntent().getExtras(); - if (getIntent().getDataString() != null) { + Intent intent = getIntent(); + Bundle extras = intent.getExtras(); - Log.i(TAG, "getIntent().getDataString() " + getIntent().getDataString()); + if (Intent.ACTION_SEARCH.equals(intent.getAction())) { + String query = intent.getStringExtra(SearchManager.QUERY); - String str = getIntent().getDataString().substring(4, getIntent().getDataString().length()); - String[] strParts = str.split(","); + searchResults = new ArrayList<POI>(); - int lat = Util.doubleToIntE6(Double.valueOf(strParts[0])); - int lng; + try { + Dao<Building, String> buildingDao = getHelper().getBuildingDao(); + + QueryBuilder<Building, String> buildingQueryBuilder = buildingDao.queryBuilder(); + buildingQueryBuilder.where().like(Building.ID_FIELD_NAME, "%" + query + "%").or() + .like(Building.NAME_FIELD_NAME, "%" + query + "%"); + PreparedQuery<Building> buildingPreparedQuery = buildingQueryBuilder.prepare(); + List<Building> buildings = buildingDao.query(buildingPreparedQuery); + searchResults.addAll(buildings); + buildings = null; + + Dao<BusStop, String> busStopDao = getHelper().getBusStopDao(); + + QueryBuilder<BusStop, String> busStopQueryBuilder = busStopDao.queryBuilder(); + busStopQueryBuilder.where().like(BusStop.ID_FIELD_NAME, "%" + query + "%").or() + .like(BusStop.DESCRIPTION_FIELD_NAME, "%" + query + "%"); + PreparedQuery<BusStop> busStopPreparedQuery = busStopQueryBuilder.prepare(); + List<BusStop> busStops = busStopDao.query(busStopPreparedQuery); + searchResults.addAll(busStops); + busStops = null; + + Dao<Site, String> siteDao = getHelper().getSiteDao(); + + QueryBuilder<Site, String> siteQueryBuilder = siteDao.queryBuilder(); + siteQueryBuilder.where().like(Site.NAME_FIELD_NAME, "%" + query + "%").or() + .like(Site.ID_FIELD_NAME, "%" + query + "%"); + PreparedQuery<Site> sitePreparedQuery = siteQueryBuilder.prepare(); + List<Site> sites = siteDao.query(sitePreparedQuery); + searchResults.addAll(sites); + sites = null; + + Collections.sort(searchResults, new StringPOIDistanceComparator(query)); + + startLocation = new GeoPoint(50935551, -1393488); + mapController.setZoom(15); - if (strParts[1].contains("?")) { - String zoom = strParts[1].substring(strParts[1].indexOf("?") + 3, strParts[1].length()); - String strLng = strParts[1].substring(0, strParts[1].indexOf("?") - 1); - lng = Util.doubleToIntE6(Double.valueOf(strLng)); + showDialog(SEARCH_RESULTS_DIALOG_ID); - mapController.setZoom(Integer.valueOf(zoom)); - } else { - lng = Util.doubleToIntE6(Double.valueOf(strParts[1])); - mapController.setZoom(15); + searchResultsDialog.setTitle(getResources().getString(R.string.search_results_dialog_title) + query); + if (searchResults.size() == 0) { + searchResultsDialog.setMessage("No results found"); + } else { + searchResultsDialog.setItems(searchResults); + } + + } catch (SQLException e) { + e.printStackTrace(); } - userLocation = new GeoPoint(lat, lng); + } else if (intent.getDataString() != null) { + String dataString = getIntent().getDataString(); + + Log.i(TAG, "getIntent().getDataString() " + dataString); + + if (dataString.startsWith("content")) { + + Uri data = intent.getData(); + + Log.i("Data: ", data.toString()); + + startLocation = new GeoPoint(50935551, -1393488); + } else { + + String str = getIntent().getDataString().substring(4, getIntent().getDataString().length()); + String[] strParts = str.split(","); + int lat = Util.doubleToIntE6(Double.valueOf(strParts[0])); + int lng; + + if (strParts[1].contains("?")) { + String zoom = strParts[1].substring(strParts[1].indexOf("?") + 3, strParts[1].length()); + String strLng = strParts[1].substring(0, strParts[1].indexOf("?") - 1); + lng = Util.doubleToIntE6(Double.valueOf(strLng)); + + mapController.setZoom(Integer.valueOf(zoom)); + } else { + lng = Util.doubleToIntE6(Double.valueOf(strParts[1])); + mapController.setZoom(15); + } + + startLocation = new GeoPoint(lat, lng); + } } else if (extras != null && extras.containsKey("poiPoint")) { String poiPoint = getIntent().getExtras().getString("poiPoint"); Log.i(TAG, "poiPoint " + poiPoint); String[] bits = poiPoint.split(","); - userLocation = new GeoPoint(Double.valueOf(bits[0]), Double.valueOf(bits[1])); + startLocation = new GeoPoint(Double.valueOf(bits[0]), Double.valueOf(bits[1])); mapController.setZoom(20); } else { - userLocation = myLocationOverlay.getMyLocation(); - if (userLocation == null) { - userLocation = new GeoPoint(50935551, -1393488); // ECS + startLocation = myLocationOverlay.getMyLocation(); + if (startLocation == null) { + startLocation = new GeoPoint(50935551, -1393488); // ECS } mapController.setZoom(15); } - mapController.setCenter(userLocation); + mapController.setCenter(startLocation); + + final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); + String appVersion = sharedPrefs.getString(APP_VERSION, APP_NOT_INSTALLED); + + if (appVersion.equals(APP_NOT_INSTALLED) || !appVersion.equals(CURRENT_APP_VERSION)) { + showDialog(WELCOME_DIALOG_ID); + } Log.i(TAG, "Finished onCreate " + (System.currentTimeMillis() - startTime)); } + private void copyDatabase() throws IOException { + Log.i(TAG, "Begining copy database"); + + InputStream myInput = getAssets().open(DATABASE_NAME); + + // Path to the just created empty db + String outFileName = DATABASE_PATH + DATABASE_NAME; + + File database = new File(outFileName); + if (database.exists()) { + database.delete(); + } + + // Open the empty db as the output stream + OutputStream myOutput = new FileOutputStream(outFileName); + + // transfer bytes from the inputfile to the outputfile + byte[] buffer = new byte[1024]; + int length; + while ((length = myInput.read(buffer)) > 0) { + myOutput.write(buffer, 0, length); + } + + // Close the streams + + myOutput.flush(); + + myOutput.close(); + myInput.close(); + + Log.i(TAG, "Finished copying db"); + } + public void onResume() { super.onResume(); - Log.i(TAG, "OnResume"); + Log.i(TAG, "OnResume " + (System.currentTimeMillis() - startTime)); if (myLocationOverlay != null) { final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); final SharedPreferences activityPrefs = getPreferences(0); @@ -299,7 +445,7 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants sharedPrefs.registerOnSharedPreferenceChangeListener(this); activityPrefs.registerOnSharedPreferenceChangeListener(this); } - Log.i(TAG, "Finished OnResume"); + Log.i(TAG, "Finished OnResume " + (System.currentTimeMillis() - startTime)); } public void onPause() { @@ -320,135 +466,6 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants return overlays; } - public void run() { - Log.i(TAG, "Begining loading database " + (System.currentTimeMillis() - startTime)); - - DatabaseHelper helper = getHelper(); - Log.i(TAG, "Got the helper at " + (System.currentTimeMillis() - startTime)); - - boolean dbExist = helper.checkDataBase(); - Log.i(TAG, "Finished checking the database at " + (System.currentTimeMillis() - startTime)); - - if (dbExist) { - // do nothing - database already exist - } else { - - if (useBundledDatabase) { - try { - // By calling this method and empty database will be created - // into the default system path - // of your application so we are gonna be able to overwrite - // that database with our database. - Log.i(TAG, "GetReadableDatabase"); - helper.getWritableDatabase().close(); - - helper.copyDataBase(); - Log.i(TAG, "Out of copy database"); - } catch (IOException ioe) { - throw new Error("Unable to create database"); - } - } else { - Thread buildingThread = null; - Thread busStopThread = null; - Thread siteThread = null; - - Log.i(TAG, "Begining loading databases " + (System.currentTimeMillis() - startTime)); - try { - Dao<Building, String> buildingDao; - - buildingDao = helper.getBuildingDao(); - - long buildingCount = buildingDao.countOf(); - Log.i(TAG, "Building count " + buildingCount); - if (buildingCount < 260) { - buildingThread = new Thread(new Runnable() { - public void run() { - try { - DataManager.loadBuildings(instance); - Log.i(TAG, "Loaded building database " + (System.currentTimeMillis() - startTime)); - } catch (SQLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - - buildingThread.start(); - } - - Dao<BusStop, String> busStopDao = helper.getBusStopDao(); - Dao<BusRoute, Integer> busRouteDao = helper.getBusRouteDao(); - Dao<RouteStop, Integer> routeStopsDao = helper.getRouteStopsDao(); - - long busStopCount = busStopDao.countOf(); - long busRouteCount = busRouteDao.countOf(); - long routeStopsCount = routeStopsDao.countOf(); - - Log.i(TAG, "BusStop count " + busStopCount); - Log.i(TAG, "BusRoute count " + busRouteCount); - Log.i(TAG, "RouteStops count " + routeStopsCount); - if (busStopCount < 217 || busRouteCount < 5 || routeStopsCount < 327) { - busStopThread = new Thread(new Runnable() { - public void run() { - try { - DataManager.loadBusData(instance, true); - Log.i(TAG, "Loaded bus stop database " + (System.currentTimeMillis() - startTime)); - } catch (SQLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - - busStopThread.start(); - } - - Dao<Site, String> siteDao = helper.getSiteDao(); - - long siteCount = siteDao.countOf(); - Log.i(TAG, "Sites count " + siteCount); - if (siteCount < 21) { - siteThread = new Thread(new Runnable() { - public void run() { - try { - DataManager.loadSiteData(instance); - Log.i(TAG, "Loaded site database " + (System.currentTimeMillis() - startTime)); - } catch (SQLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - - siteThread.start(); - } - - while (true) { - if ((buildingThread == null || !buildingThread.isAlive()) - && (busStopThread == null || !busStopThread.isAlive()) - && (siteThread == null || !siteThread.isAlive())) - break; - - Thread.yield(); - } - - Log.i(TAG, "Finished loading databases " + (System.currentTimeMillis() - startTime)); - - } catch (SQLException e1) { - e1.printStackTrace(); - } - } - - } - - Log.i(TAG, "Begining setting up the static values " + (System.currentTimeMillis() - startTime)); - - Log.i(TAG, "Finished the database thread " + (System.currentTimeMillis() - startTime)); - } - private void showOverlays() throws SQLException { Log.i(TAG, "Began showing overlays at " + (System.currentTimeMillis() - startTime)); @@ -473,10 +490,11 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants showBuildingOverlays(); } - Log.i(TAG, "Begining to show the route overlays at " + (System.currentTimeMillis() - startTime)); + Log.v(TAG, "Begining to show the route overlays at " + (System.currentTimeMillis() - startTime)); for (BusRoute busRoute : getHelper().getBusRouteDao()) { if (!busRoute.uniLink) { - // Log.v(TAG, "Bus route " + busRoute.code + "(" + busRoute.id + ") is not unilink"); + // Log.v(TAG, "Bus route " + busRoute.code + "(" + busRoute.id + + // ") is not unilink"); continue; } Log.v(TAG, "Looking at showing " + busRoute.code + " route overlay"); @@ -484,12 +502,13 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants showRouteOverlay(busRoute); } } - Log.i(TAG, "Finished loading routes " + (System.currentTimeMillis() - startTime)); + Log.v(TAG, "Finished loading routes " + (System.currentTimeMillis() - startTime)); - Log.i(TAG, "Begining to show the site overlays at " + (System.currentTimeMillis() - startTime)); + Log.v(TAG, "Begining to show the site overlays at " + (System.currentTimeMillis() - startTime)); try { for (Site site : getHelper().getSiteDao()) { - // Log.v(TAG, "Looking at showing " + site.name + " site overlay"); + // Log.v(TAG, "Looking at showing " + site.name + + // " site overlay"); if (activityPrefs.getBoolean(SITE_OVERLAYS + site.name, SITE_OVERLAYS_ENABLED_BY_DEFAULT)) { showSiteOverlay(site); } @@ -497,9 +516,9 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants } catch (SQLException e) { e.printStackTrace(); } - Log.i(TAG, "Finished showing the site overlays " + (System.currentTimeMillis() - startTime)); + Log.v(TAG, "Finished showing the site overlays " + (System.currentTimeMillis() - startTime)); - Log.i(TAG, "Finished showing all the overlays " + (System.currentTimeMillis() - startTime)); + Log.v(TAG, "Finished showing all the overlays " + (System.currentTimeMillis() - startTime)); } private void showUtilityOverlays() { @@ -915,8 +934,7 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants // Handle item selection switch (item.getItemId()) { case R.id.menu_find: - Intent i = new Intent(MapActivity.this, FindActivity.class); - startActivityForResult(i, 0); + onSearchRequested(); return true; case R.id.menu_preferences: Intent settingsActivity = new Intent(getBaseContext(), PreferencesActivity.class); @@ -968,8 +986,6 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants return false; } - refreshFavouriteDialog(); - return false; case R.id.menu_about: Intent aboutIntent = new Intent(MapActivity.this, AboutActivity.class); @@ -981,47 +997,6 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants } } - private void refreshFavouriteDialog() { - ArrayList<POI> newFavouriteItems = new ArrayList<POI>(); - - try { - Dao<Building, String> buildingDao = getHelper().getBuildingDao(); - Dao<BusStop, String> busStopDao = getHelper().getBusStopDao(); - - final SharedPreferences favouritesPrefs = getSharedPreferences(FAVOURITES_PREFERENCES, MODE_PRIVATE); - for (String id : favouritesPrefs.getAll().keySet()) { - Building building; - BusStop busStop; - if ((building = buildingDao.queryForId(id)) != null) { - newFavouriteItems.add(building); - } else if ((busStop = busStopDao.queryForId(id)) != null) { - newFavouriteItems.add(busStop); - } else { - Log.e(TAG, "Item in favourites " + id + " cannot be found"); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - - Log.i(TAG, "There are " + newFavouriteItems.size() + " favourites"); - if (newFavouriteItems.size() == 0) { - Log.i(TAG, "Favourite dialog has no favourites, displaying message"); - favDialog.setMessage(getResources().getString(R.string.favourites_dialog_message)); - favDialog.setItems(null); - } else { - favDialog.setMessage(""); - favDialog.setItems(newFavouriteItems); - } - } - - @Override - public boolean onSearchRequested() { - Intent i = new Intent(MapActivity.this, FindActivity.class); - startActivityForResult(i, 0); - return false; - } - protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "Got activity result"); if (resultCode == RESULT_OK) { @@ -1058,10 +1033,6 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants Log.i(TAG, "Got null poi id"); } - if (favDialog != null) { - refreshFavouriteDialog(); - } - mapView.invalidate(); } } @@ -1074,52 +1045,92 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants ViewDialog viewDialog = new ViewDialog(instance); return viewDialog; case FAVOURITE_DIALOG_ID: - favDialog = new POIDialog(instance); + favDialog = new FavouritesDialog(instance); favDialog.setOnItemClickListener(this); favDialog.setOnItemLongClickListener(this); favDialog.setTitle(R.string.favourites_dialog_title); return favDialog; + case SEARCH_RESULTS_DIALOG_ID: + searchResultsDialog = new SearchResultsDialog(instance); + searchResultsDialog.setOnItemClickListener(this); + searchResultsDialog.setOnItemLongClickListener(this); + return searchResultsDialog; + case WELCOME_DIALOG_ID: + WelcomeDialog welcomeDialog = new WelcomeDialog(instance); + return welcomeDialog; } return null; } - public void onItemClick(AdapterView<?> parent, View view, int position, long id) { - Log.i(TAG, "OnItemClick pos " + position + " id " + id); - - String poiId = favDialog.adapter.getItemStringId(position); + protected void onPrepareDialog(int id, Dialog dialog) { + if (dialog instanceof FavouritesDialog) { + favDialog = (FavouritesDialog) dialog; - Log.i(TAG, "POI " + poiId + " selected"); + ArrayList<POI> newFavouriteItems = new ArrayList<POI>(); - POI poi = null; - - if (poiId != null) { - Log.i(TAG, "Got id " + poiId); try { - poi = getHelper().getBuildingDao().queryForId(poiId); - if (poi == null) { - poi = getHelper().getBusStopDao().queryForId(poiId); + Dao<Building, String> buildingDao = getHelper().getBuildingDao(); + Dao<BusStop, String> busStopDao = getHelper().getBusStopDao(); + + final SharedPreferences favouritesPrefs = getSharedPreferences(FAVOURITES_PREFERENCES, 0); + for (String idStr : favouritesPrefs.getAll().keySet()) { + Building building; + BusStop busStop; + if ((building = buildingDao.queryForId(idStr)) != null) { + newFavouriteItems.add(building); + } else if ((busStop = busStopDao.queryForId(idStr)) != null) { + newFavouriteItems.add(busStop); + } else { + Log.e(TAG, "Item in favourites " + idStr + " cannot be found"); + } } } catch (SQLException e) { e.printStackTrace(); } - if (poi == null) { - Log.e(TAG, "Could not find poi " + poiId + " in onActivityResult"); + Log.i(TAG, "There are " + newFavouriteItems.size() + " favourites"); + if (newFavouriteItems.size() == 0) { + Log.i(TAG, "Favourite dialog has no favourites, displaying message"); + favDialog.setMessage(getResources().getString(R.string.favourites_dialog_message)); + favDialog.setItems(null); } else { - if (myLocationOverlay != null) { - myLocationOverlay.disableFollowLocation(); - } - mapController.setZoom(20); - mapController.setCenter(poi.point); + favDialog.setMessage(""); + favDialog.setItems(newFavouriteItems); + } + } else if (dialog instanceof SearchResultsDialog) { + searchResultsDialog = (SearchResultsDialog) dialog; + } + } - favDialog.dismiss(); + public void onItemClick(AdapterView<?> parent, View view, int position, long id) { + Log.i(TAG, "OnItemClick pos " + position + " id " + id); + + POI poi = null; + if (favDialog != null) { + poi = favDialog.adapter.getPOIItem(position); + } else if (searchResultsDialog != null) { + poi = searchResultsDialog.adapter.getPOIItem(position); + } + + if (poi != null) { + Log.i(TAG, "Got id " + poi.id); + if (myLocationOverlay != null) { + myLocationOverlay.disableFollowLocation(); } + mapController.setZoom(20); + mapController.setCenter(poi.point); + + if (favDialog != null) { + favDialog.dismiss(); + favDialog = null; + } else if (searchResultsDialog != null) { + searchResultsDialog.dismiss(); + searchResultsDialog = null; + } + } else { Log.i(TAG, "Got null poi id"); - - // mapController.setZoom(15); - // mapController.setCenter(new GeoPoint(50935551, -1393488)); } } @@ -1131,66 +1142,76 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants Log.i(TAG, "OnItemClick pos " + position + " id " + id); - String poiId = favDialog.adapter.getItemStringId(position); + POI poi = null; + if (favDialog != null) { + poi = favDialog.adapter.getPOIItem(position); + } else if (searchResultsDialog != null) { + poi = searchResultsDialog.adapter.getPOIItem(position); + } - Log.i(TAG, "POI " + poiId + " selected"); + if (poi != null) { + Log.i(TAG, "Got id " + poi.id); - POI poi = null; + if (poi.type == POI.BUS_STOP) { + BusStop busStop = (BusStop) poi; - if (poiId != null) { - Log.i(TAG, "Got id " + poiId); - try { - poi = getHelper().getBuildingDao().queryForId(poiId); - if (poi == null) { - poi = getHelper().getBusStopDao().queryForId(poiId); - } - } catch (SQLException e) { - e.printStackTrace(); - } + Log.i(TAG, "Pressed " + busStop.id); - if (poi == null) { - Log.e(TAG, "Could not find poi " + poiId + " in onActivityResult"); - } else { - if (poi.type == POI.BUS_STOP) { - BusStop busStop = (BusStop) poi; + Uri uri = Uri.parse("http://id.southampton.ac.uk/bus-stop/" + busStop.id); - Log.i(TAG, "Pressed " + busStop.id); + Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath()); - Uri uri = Uri.parse("http://id.southampton.ac.uk/bus-stop/" + busStop.id); + Intent busStopIntent = new Intent(Intent.ACTION_VIEW, uri); + startActivity(busStopIntent); - Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath()); + return true; - Intent busStopIntent = new Intent(Intent.ACTION_VIEW, uri); - startActivity(busStopIntent); + } else if (poi.type == POI.BUILDING) { + Building building = (Building) poi; - return true; + Log.i(TAG, "Pressed " + building.id); - } else if (poi.type == POI.BUILDING) { - Building building = (Building) poi; + Uri uri = Uri.parse("http://id.southampton.ac.uk/building/" + building.id); - Log.i(TAG, "Pressed " + building.id); + Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath()); - Uri uri = Uri.parse("http://id.southampton.ac.uk/building/" + building.id); + Intent buildingIntent = new Intent(Intent.ACTION_VIEW, uri); + startActivity(buildingIntent); - Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath()); + return true; - Intent buildingIntent = new Intent(Intent.ACTION_VIEW, uri); - startActivity(buildingIntent); + } else if (poi.type == POI.SITE) { + Site site = (Site) poi; - return true; + Log.i(TAG, "Pressed " + site.id); - } else { + Uri uri = Uri.parse("http://id.southampton.ac.uk/site/" + site.id); + + Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath()); - myLocationOverlay.disableFollowLocation(); - mapController.setZoom(20); - mapController.setCenter(poi.point); + Intent siteIntent = new Intent(Intent.ACTION_VIEW, uri); + startActivity(siteIntent); + return true; + + } else { + + myLocationOverlay.disableFollowLocation(); + mapController.setZoom(20); + mapController.setCenter(poi.point); + + if (favDialog != null) { favDialog.dismiss(); favDialog = null; + } else if (searchResultsDialog != null) { + searchResultsDialog.dismiss(); + searchResultsDialog = null; } + } + } else { - Log.i(TAG, "Got null poi id"); + Log.i(TAG, "Got null poi"); // mapController.setZoom(15); // mapController.setCenter(new GeoPoint(50935551, -1393488)); diff --git a/src/net/cbaines/suma/MapContentProvider.java b/src/net/cbaines/suma/MapContentProvider.java new file mode 100644 index 0000000..efbdf2f --- /dev/null +++ b/src/net/cbaines/suma/MapContentProvider.java @@ -0,0 +1,394 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.cbaines.suma; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import android.app.SearchManager; +import android.content.ContentProvider; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.MatrixCursor; +import android.net.Uri; +import android.provider.BaseColumns; +import android.util.Log; + +import com.j256.ormlite.android.AndroidCompiledStatement; +import com.j256.ormlite.android.apptools.OpenHelperManager; +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.stmt.PreparedQuery; +import com.j256.ormlite.stmt.QueryBuilder; +import com.j256.ormlite.stmt.StatementBuilder.StatementType; + +/** + * Provides access to the dictionary database. + */ +public class MapContentProvider extends ContentProvider { + String TAG = "MapContentProvider"; + + public static String AUTHORITY = "net.cbaines.suma.provider"; + // public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + // + "/building"); + + // MIME types used for searching words or looking up a single definition + public static final String ALLS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.net.cbaines.suma.provider.all"; + public static final String ALL_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.net.cbaines.suma.provider.all"; + public static final String BUILDINGS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + + "/vnd.net.cbaines.suma.provider.building"; + public static final String BUILDING_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + + "/vnd.net.cbaines.suma.provider.building"; + public static final String BUS_STOPS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + + "/vnd.net.cbaines.suma.provider.bus-stop"; + public static final String BUS_STOP_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + + "/vnd.net.cbaines.suma.provider.bus-stop"; + public static final String SITES_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.net.cbaines.suma.provider.site"; + public static final String SITE_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.net.cbaines.suma.provider.site"; + public static final String BUSES_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.net.cbaines.suma.provider.bus"; + public static final String BUS_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.net.cbaines.suma.provider.bus"; + + private DatabaseHelper helper; + + // UriMatcher stuff + private static final int SEARCH_ALL = 0; + private static final int GET_ALL = 1; + private static final int SEARCH_BUILDINGS = 2; + private static final int GET_BUILDING = 3; + private static final int SEARCH_BUS_STOPS = 4; + private static final int GET_BUS_STOP = 5; + private static final int SEARCH_SITES = 6; + private static final int GET_SITE = 7; + private static final int SEARCH_BUSES = 8; + private static final int GET_BUS = 9; + private static final int SEARCH_SUGGEST = 10; + private static final int REFRESH_SHORTCUT = 11; + private static final UriMatcher sURIMatcher = buildUriMatcher(); + + /** + * Builds up a UriMatcher for search suggestion and shortcut refresh queries. + */ + private static UriMatcher buildUriMatcher() { + UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); + // to get definitions... + matcher.addURI(AUTHORITY, "all", SEARCH_BUILDINGS); + matcher.addURI(AUTHORITY, "all/*", GET_BUILDING); + matcher.addURI(AUTHORITY, "building", SEARCH_BUILDINGS); + matcher.addURI(AUTHORITY, "building/*", GET_BUILDING); + matcher.addURI(AUTHORITY, "bus-stop", SEARCH_BUS_STOPS); + matcher.addURI(AUTHORITY, "bus-stop/*", GET_BUS_STOP); + matcher.addURI(AUTHORITY, "site", SEARCH_SITES); + matcher.addURI(AUTHORITY, "site/*", GET_SITE); + matcher.addURI(AUTHORITY, "bus", SEARCH_BUSES); + matcher.addURI(AUTHORITY, "bus/*", GET_BUS); + + // to get suggestions... + matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST); + matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST); + + /* + * The following are unused in this implementation, but if we include {@link SearchManager#SUGGEST_COLUMN_SHORTCUT_ID} as + * a column in our suggestions table, we could expect to receive refresh queries when a shortcutted suggestion is + * displayed in Quick Search Box, in which case, the following Uris would be provided and we would return a cursor with a + * single item representing the refreshed suggestion data. + */ + matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT, REFRESH_SHORTCUT); + matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", REFRESH_SHORTCUT); + return matcher; + } + + @Override + public boolean onCreate() { + helper = OpenHelperManager.getHelper(this.getContext(), DatabaseHelper.class); + return true; + } + + /** + * Handles all the dictionary searches and suggestion queries from the Search Manager. When requesting a specific word, the + * uri alone is required. When searching all of the dictionary for matches, the selectionArgs argument must carry the search + * query as the first element. All other arguments are ignored. + */ + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { + + // Use the UriMatcher to see what kind of query we have and format the + // db query accordingly + switch (sURIMatcher.match(uri)) { + case SEARCH_SUGGEST: + if (selectionArgs == null) { + throw new IllegalArgumentException("selectionArgs must be provided for the Uri: " + uri); + } + try { + return getSuggestions(selectionArgs[0]); + } catch (SQLException e1) { + e1.printStackTrace(); + } + case SEARCH_ALL: + if (selectionArgs == null) { + throw new IllegalArgumentException("selectionArgs must be provided for the Uri: " + uri); + } + try { + return searchAll(selectionArgs[0]); + } catch (SQLException e) { + e.printStackTrace(); + } + case GET_ALL: + try { + return getAll(uri); + } catch (SQLException e) { + e.printStackTrace(); + } + case SEARCH_BUILDINGS: + if (selectionArgs == null) { + throw new IllegalArgumentException("selectionArgs must be provided for the Uri: " + uri); + } + try { + return searchBuildings(selectionArgs[0]); + } catch (SQLException e) { + e.printStackTrace(); + } + case GET_BUILDING: + try { + return getBuilding(uri); + } catch (SQLException e) { + e.printStackTrace(); + } + case REFRESH_SHORTCUT: + try { + return refreshShortcut(uri); + } catch (SQLException e) { + e.printStackTrace(); + } + default: + throw new IllegalArgumentException("Unknown Uri: " + uri); + } + } + + private Cursor getSuggestions(String query) throws SQLException { + Log.v(TAG, "Got query for " + query); + + String[] columnNames = { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_TEXT_1, + SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_INTENT_DATA }; + + List<POI> results = new ArrayList<POI>(); + + MatrixCursor cursor = new MatrixCursor(columnNames); + int id = 0; + + Dao<Building, String> buildingDao = helper.getBuildingDao(); + + QueryBuilder<Building, String> qb = buildingDao.queryBuilder(); + qb.where().like(Building.ID_FIELD_NAME, "%" + query + "%").or().like(Building.NAME_FIELD_NAME, "%" + query + "%"); + PreparedQuery<Building> preparedQuery = qb.prepare(); + + results.addAll(buildingDao.query(preparedQuery)); + + Dao<BusStop, String> busStopDao = helper.getBusStopDao(); + + QueryBuilder<BusStop, String> busStopQB = busStopDao.queryBuilder(); + busStopQB.where().like(BusStop.ID_FIELD_NAME, "%" + query + "%").or() + .like(BusStop.DESCRIPTION_FIELD_NAME, "%" + query + "%"); + PreparedQuery<BusStop> busStopPreparedQuery = busStopQB.prepare(); + + results.addAll(busStopDao.query(busStopPreparedQuery)); + + Dao<Site, String> siteDao = helper.getSiteDao(); + + QueryBuilder<Site, String> siteQB = siteDao.queryBuilder(); + siteQB.where().like(Site.NAME_FIELD_NAME, "%" + query + "%").or().like(Site.ID_FIELD_NAME, "%" + query + "%"); + PreparedQuery<Site> sitePreparedQuery = siteQB.prepare(); + + results.addAll(siteDao.query(sitePreparedQuery)); + + Collections.sort(results, new StringPOIDistanceComparator(query)); + + for (POI poi : results) { + if (poi instanceof Site) { + Site site = (Site) poi; + Object[] values = { + id++, + R.drawable.empty, + site.name, + site.id, + "geo:" + Util.E6IntToDouble(site.point.getLatitudeE6()) + "," + + Util.E6IntToDouble(site.point.getLongitudeE6()) + "?z=18" }; + cursor.addRow(values); + } else if (poi instanceof Building) { + Building building = (Building) poi; + Object[] values = { + id++, + R.drawable.building, + building.name, + building.id, + "geo:" + Util.E6IntToDouble(building.point.getLatitudeE6()) + "," + + Util.E6IntToDouble(building.point.getLongitudeE6()) + "?z=18" }; + cursor.addRow(values); + } else if (poi instanceof BusStop) { + BusStop busStop = (BusStop) poi; + Object[] values = { + id++, + R.drawable.busstop, + busStop.description, + busStop.id, + "geo:" + Util.E6IntToDouble(busStop.point.getLatitudeE6()) + "," + + Util.E6IntToDouble(busStop.point.getLongitudeE6()) + "?z=18" }; + cursor.addRow(values); + } else { + Log.e(TAG, "Error, unexpected class"); + } + } + + return cursor; + } + + private Cursor searchBuildings(String query) throws SQLException { + Dao<Building, String> buildingDao = helper.getBuildingDao(); + + QueryBuilder<Building, String> qb = buildingDao.queryBuilder(); + qb.where().eq(Building.ID_FIELD_NAME, "%" + query + "%").or().eq(Building.NAME_FIELD_NAME, "%" + query + "%"); + PreparedQuery<Building> preparedQuery = qb.prepare(); + + AndroidCompiledStatement compiledStatement = (AndroidCompiledStatement) preparedQuery.compile(helper + .getConnectionSource().getReadOnlyConnection(), StatementType.SELECT); + Cursor cursor = compiledStatement.getCursor(); + + return cursor; + } + + private Cursor getBuilding(Uri uri) throws SQLException { + String buildingID = uri.getLastPathSegment(); + Dao<Building, String> buildingDao = helper.getBuildingDao(); + + QueryBuilder<Building, String> qb = buildingDao.queryBuilder(); + qb.where().eq(Building.ID_FIELD_NAME, buildingID); + PreparedQuery<Building> preparedQuery = qb.prepare(); + + AndroidCompiledStatement compiledStatement = (AndroidCompiledStatement) preparedQuery.compile(helper + .getConnectionSource().getReadOnlyConnection(), StatementType.SELECT); + Cursor cursor = compiledStatement.getCursor(); + + return cursor; + } + + private Cursor searchAll(String query) throws SQLException { + Dao<Building, String> buildingDao = helper.getBuildingDao(); + + QueryBuilder<Building, String> qb = buildingDao.queryBuilder(); + qb.where().eq(Building.ID_FIELD_NAME, "%" + query + "%").or().eq(Building.NAME_FIELD_NAME, "%" + query + "%"); + PreparedQuery<Building> preparedQuery = qb.prepare(); + + AndroidCompiledStatement compiledStatement = (AndroidCompiledStatement) preparedQuery.compile(helper + .getConnectionSource().getReadOnlyConnection(), StatementType.SELECT); + Cursor cursor = compiledStatement.getCursor(); + + return cursor; + } + + private Cursor getAll(Uri uri) throws SQLException { + String buildingID = uri.getLastPathSegment(); + Dao<Building, String> buildingDao = helper.getBuildingDao(); + + QueryBuilder<Building, String> qb = buildingDao.queryBuilder(); + qb.where().eq(Building.ID_FIELD_NAME, buildingID); + PreparedQuery<Building> preparedQuery = qb.prepare(); + + AndroidCompiledStatement compiledStatement = (AndroidCompiledStatement) preparedQuery.compile(helper + .getConnectionSource().getReadOnlyConnection(), StatementType.SELECT); + Cursor cursor = compiledStatement.getCursor(); + + return cursor; + } + + private Cursor refreshShortcut(Uri uri) throws SQLException { + /* + * This won't be called with the current implementation, but if we include {@link + * SearchManager#SUGGEST_COLUMN_SHORTCUT_ID} as a column in our suggestions table, we could expect to receive refresh + * queries when a shortcutted suggestion is displayed in Quick Search Box. In which case, this method will query the table + * for the specific word, using the given item Uri and provide all the columns originally provided with the suggestion + * query. + */ + String buildingID = uri.getLastPathSegment(); + Dao<Building, String> buildingDao = helper.getBuildingDao(); + + QueryBuilder<Building, String> qb = buildingDao.queryBuilder(); + qb.where().eq(Building.ID_FIELD_NAME, buildingID); + PreparedQuery<Building> preparedQuery = qb.prepare(); + + AndroidCompiledStatement compiledStatement = (AndroidCompiledStatement) preparedQuery.compile(helper + .getConnectionSource().getReadOnlyConnection(), StatementType.SELECT); + Cursor cursor = compiledStatement.getCursor(); + + return cursor; + } + + /** + * This method is required in order to query the supported types. It's also useful in our own query() method to determine the + * type of Uri received. + */ + @Override + public String getType(Uri uri) { + switch (sURIMatcher.match(uri)) { + case SEARCH_ALL: + return ALLS_MIME_TYPE; + case GET_ALL: + return ALL_MIME_TYPE; + case SEARCH_BUILDINGS: + return BUILDINGS_MIME_TYPE; + case GET_BUILDING: + return BUILDING_MIME_TYPE; + case SEARCH_BUS_STOPS: + return BUS_STOPS_MIME_TYPE; + case GET_BUS_STOP: + return BUS_STOP_MIME_TYPE; + case SEARCH_SITES: + return SITES_MIME_TYPE; + case GET_SITE: + return SITE_MIME_TYPE; + case SEARCH_BUSES: + return BUSES_MIME_TYPE; + case GET_BUS: + return BUS_MIME_TYPE; + case SEARCH_SUGGEST: + return SearchManager.SUGGEST_MIME_TYPE; + case REFRESH_SHORTCUT: + return SearchManager.SHORTCUT_MIME_TYPE; + default: + throw new IllegalArgumentException("Unknown URL " + uri); + } + } + + // Other required implementations... + + @Override + public Uri insert(Uri uri, ContentValues values) { + throw new UnsupportedOperationException(); + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + throw new UnsupportedOperationException(); + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/net/cbaines/suma/POI.java b/src/net/cbaines/suma/POI.java index c84f90e..f8c1f89 100644 --- a/src/net/cbaines/suma/POI.java +++ b/src/net/cbaines/suma/POI.java @@ -47,7 +47,8 @@ public abstract class POI { @DatabaseField(id = true) public String id; - public int distTo = -1; // Used by the comparator to store distances, then later by the gui to display them. + public int distTo = -1; // Used by the comparator to store distances, then + // later by the gui to display them. public String type; diff --git a/src/net/cbaines/suma/POIArrayAdapter.java b/src/net/cbaines/suma/POIArrayAdapter.java index f9b5271..028f659 100644 --- a/src/net/cbaines/suma/POIArrayAdapter.java +++ b/src/net/cbaines/suma/POIArrayAdapter.java @@ -22,6 +22,7 @@ package net.cbaines.suma; import java.util.List; import android.content.Context; +import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; @@ -74,6 +75,7 @@ public class POIArrayAdapter extends BaseAdapter { } public String getItemStringId(int position) { + Log.v("POIArrayAdapter", POIs.get(position).toString()); return ((POI) POIs.get(position)).id; } }
\ No newline at end of file diff --git a/src/net/cbaines/suma/Preferences.java b/src/net/cbaines/suma/Preferences.java index 0508251..791aad8 100644 --- a/src/net/cbaines/suma/Preferences.java +++ b/src/net/cbaines/suma/Preferences.java @@ -14,5 +14,20 @@ public interface Preferences { static final String SHOW_IDENTIFIERS = "showIdentifiers"; static final boolean SHOW_IDENTIFIERS_ENABLED_BY_DEFAULT = false; + static final String APP_VERSION = "appVersion"; + static final String APP_NOT_INSTALLED = ""; + static final String CURRENT_APP_VERSION = "0.9"; + static final String FAVOURITES_PREFERENCES = "favourites"; + + static final String DATABASE_PATH = "/data/data/net.cbaines.suma/databases/"; + static final String DATABASE_NAME = "data.db"; + + static final int DATABASE_VERSION = 42; + + /** + * Enable to use the database in the assets folder, if its not enabled, the database is built from the csv files in the assets + * folder + */ + static final boolean USE_BUNDLED_DATABASE = true; } diff --git a/src/net/cbaines/suma/SearchResultsDialog.java b/src/net/cbaines/suma/SearchResultsDialog.java new file mode 100644 index 0000000..43fa206 --- /dev/null +++ b/src/net/cbaines/suma/SearchResultsDialog.java @@ -0,0 +1,10 @@ +package net.cbaines.suma; + +import android.content.Context; + +public class SearchResultsDialog extends POIDialog implements Preferences { + + public SearchResultsDialog(Context context) { + super(context); + } +} diff --git a/src/net/cbaines/suma/StringDistanceComparator.java b/src/net/cbaines/suma/StringPOIDistanceComparator.java index d42451f..e8a7539 100644 --- a/src/net/cbaines/suma/StringDistanceComparator.java +++ b/src/net/cbaines/suma/StringPOIDistanceComparator.java @@ -21,21 +21,21 @@ package net.cbaines.suma; import java.util.Comparator; -public class StringDistanceComparator implements Comparator<POI> { +public class StringPOIDistanceComparator implements Comparator<POI> { private String userString; // private static final String TAG = "StringDistanceComparator"; - public StringDistanceComparator(String userString) { + public StringPOIDistanceComparator(String userString) { super(); this.userString = userString; } public int compare(POI poi1, POI poi2) { - int distTo1 = LD(userString, poi1.toString()); + int distTo1 = Math.min(LD(userString, poi1.toString()), LD(userString, poi1.id)); // Log.i(TAG, "Comparing " + userString + " and " + poi1.toString() + // " got dist " + distTo1); - int distTo2 = LD(userString, poi2.toString()); + int distTo2 = Math.min(LD(userString, poi2.toString()), LD(userString, poi2.id)); // Log.i(TAG, "Comparing " + userString + " and " + poi2.toString() + // " got dist " + distTo2); return distTo1 - distTo2; diff --git a/src/net/cbaines/suma/WelcomeDialog.java b/src/net/cbaines/suma/WelcomeDialog.java new file mode 100644 index 0000000..7afec03 --- /dev/null +++ b/src/net/cbaines/suma/WelcomeDialog.java @@ -0,0 +1,64 @@ +/* + * Southampton University Map App + * Copyright (C) 2011 Christopher Baines + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package net.cbaines.suma; + +import android.app.Dialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.TextView; + +public class WelcomeDialog extends Dialog implements OnClickListener, Preferences { + + // private static final String TAG = "WelcomeDialog"; + + final SharedPreferences sharedPrefs; + + private Button continueButton; + + public WelcomeDialog(Context context) { + super(context); + + this.setTitle(R.string.welcome_dialog_title); + + setContentView(R.layout.welcome_dialog); + + sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); + String appVersion = sharedPrefs.getString(APP_VERSION, APP_NOT_INSTALLED); + + if (!appVersion.equals(APP_NOT_INSTALLED)) { + TextView welcomeDialogMessage = (TextView) findViewById(R.id.welcomeDialogMessage); + welcomeDialogMessage.setText(R.string.welcome_dialog_upgrade_message); + } + + continueButton = (Button) findViewById(R.id.welcomeDialogButton); + continueButton.setOnClickListener(this); + } + + public void onClick(View arg0) { + + sharedPrefs.edit().putString(APP_VERSION, CURRENT_APP_VERSION).commit(); + + this.dismiss(); + } +} |