From 4b4a5a0ebc7f285d7cdcfa1d72640dbc097bdbb2 Mon Sep 17 00:00:00 2001 From: Christopher Baines Date: Wed, 1 Feb 2012 20:25:53 +0000 Subject: Versioning changes for 0.2.2 --- AndroidManifest.xml | 4 ++-- res/values/strings.xml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 4fd68e4..c606279 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,8 +1,8 @@ + android:versionCode="5" + android:versionName="0.2.2 (alpha)" > diff --git a/res/values/strings.xml b/res/values/strings.xml index a53109b..7c08887 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -92,7 +92,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.< About Version - 0.2.1 (alpha) + 0.2.2 (alpha) Copyright © 2012, Christopher Baines License -- cgit v1.2.3 From cc3f1f19a6de034413a37dfebd922fb8c51888e1 Mon Sep 17 00:00:00 2001 From: Christopher Baines Date: Sun, 26 Feb 2012 18:23:14 +0000 Subject: Some changes, not sure why. --- src/net/cbaines/suma/BusActivity.java | 528 +++++++++-------- src/net/cbaines/suma/BusSpecificStopView.java | 229 ++++---- src/net/cbaines/suma/BusStopActivity.java | 811 +++++++++++++------------- src/net/cbaines/suma/StopView.java | 218 ++++--- 4 files changed, 891 insertions(+), 895 deletions(-) diff --git a/src/net/cbaines/suma/BusActivity.java b/src/net/cbaines/suma/BusActivity.java index b802cfb..c626158 100644 --- a/src/net/cbaines/suma/BusActivity.java +++ b/src/net/cbaines/suma/BusActivity.java @@ -25,319 +25,315 @@ import android.widget.Toast; import com.j256.ormlite.android.apptools.OrmLiteBaseActivity; public class BusActivity extends OrmLiteBaseActivity implements Preferences { - final static String TAG = "BusActivity"; + final static String TAG = "BusActivity"; - private TextView U1RouteTextView; - private TextView U1NRouteTextView; - private TextView U2RouteTextView; - private TextView U6RouteTextView; - private TextView U9RouteTextView; + private TextView U1RouteTextView; + private TextView U1NRouteTextView; + private TextView U2RouteTextView; + private TextView U6RouteTextView; + private TextView U9RouteTextView; - private TextView busIDTextView; + private TextView busIDTextView; - private TextView busContentMessage; - private LinearLayout busActivityContentLayout; + private TextView busContentMessage; + private LinearLayout busActivityContentLayout; - Toast activityToast; + Toast activityToast; - /** - * The bus this activity is focused on - */ - private Bus bus; - /** - * The bus stop this activity is working from - */ - private BusStop busStop; - - Runnable refreshData; - - protected Timetable timetable; - private Timetable visibleTimetable; + /** + * The bus this activity is focused on + */ + private Bus bus; + /** + * The bus stop this activity is working from + */ + private BusStop busStop; - private ListView timetableView; + Runnable refreshData; - private Context instance; + protected Timetable timetable; + private Timetable visibleTimetable; - // BusStops and if they are being updated by the handler - List busStops; + private ListView timetableView; - private HashMap tasks = new HashMap(); + private Context instance; - Handler handler; + // BusStops and if they are being updated by the handler + List busStops; - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.bus_activity); - instance = this; + private HashMap tasks = new HashMap(); - String busID = getIntent().getExtras().getString("busID"); - String busStopID = getIntent().getExtras().getString("busStopID"); - final DatabaseHelper helper = getHelper(); + Handler handler; - try { - List buses = helper.getBusDao().queryForEq(Bus.ID_FIELD_NAME, busID); - bus = null; - if (buses.size() == 0) { - Log.e(TAG, "Bus " + busID + " not found!"); - } else if (buses.size() == 1) { - bus = buses.get(0); - } else if (buses.size() > 1) { - Log.e(TAG, "Found more than one bus? " + busID); - } + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.bus_activity); + instance = this; - helper.getBusRouteDao().refresh(bus.route); + String busID = getIntent().getExtras().getString("busID"); + String busStopID = getIntent().getExtras().getString("busStopID"); + final DatabaseHelper helper = getHelper(); - busStop = null; - if (busStopID != null) { - List busStops = helper.getBusStopDao().queryForEq(BusStop.ID_FIELD_NAME, busStopID); - if (busStops.size() == 0) { - Log.e(TAG, "BusStop " + busStopID + " not found!"); - } else if (busStops.size() == 1) { - busStop = busStops.get(0); - } else if (busStops.size() > 1) { - Log.e(TAG, "Found more than one busStop? " + busStopID); - } - } - - U1RouteTextView = (TextView) findViewById(R.id.busActivityU1); - U1NRouteTextView = (TextView) findViewById(R.id.busActivityU1N); - U2RouteTextView = (TextView) findViewById(R.id.busActivityU2); - U6RouteTextView = (TextView) findViewById(R.id.busActivityU6); - U9RouteTextView = (TextView) findViewById(R.id.busActivityU9); - - busIDTextView = (TextView) findViewById(R.id.busActivityBusID); - - busContentMessage = (TextView) findViewById(R.id.busActivityMessage); - busActivityContentLayout = (LinearLayout) findViewById(R.id.busActivityContentLayout); - timetableView = (ListView) findViewById(R.id.busActivityTimes); - - if (bus.id != null) { - Log.i(TAG, "Bus id is not null (" + bus.id + ") setting busIDTextView"); - busIDTextView.setText(bus.id + " " + bus.getName()); - } else { - Log.w(TAG, "Bus id is null?"); - // Might not ever happen - busIDTextView.setText("Unidentified"); - } - - U1RouteTextView.setVisibility(View.GONE); - U1NRouteTextView.setVisibility(View.GONE); - U2RouteTextView.setVisibility(View.GONE); - U6RouteTextView.setVisibility(View.GONE); - U9RouteTextView.setVisibility(View.GONE); - - // if (bus.route.uniLink) { - Log.i(TAG, "Bus is uniLink"); - if (bus.route.code.equals("U1")) { - U1RouteTextView.setVisibility(View.VISIBLE); - } else if (bus.route.code.equals("U1N")) { - U1NRouteTextView.setVisibility(View.VISIBLE); - } else if (bus.route.code.equals("U2")) { - U2RouteTextView.setVisibility(View.VISIBLE); - } else if (bus.route.code.equals("U6")) { - U6RouteTextView.setVisibility(View.VISIBLE); - } else if (bus.route.code.equals("U9")) { - U9RouteTextView.setVisibility(View.VISIBLE); - } else { - Log.e(TAG, "Route not found " + bus.route.code); - } - // } else { - // Log.i(TAG, "Bus is not uniLink"); - // } - - } catch (NumberFormatException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } + try { + List buses = helper.getBusDao().queryForEq(Bus.ID_FIELD_NAME, busID); + bus = null; + if (buses.size() == 0) { + Log.e(TAG, "Bus " + busID + " not found!"); + } else if (buses.size() == 1) { + bus = buses.get(0); + } else if (buses.size() > 1) { + Log.e(TAG, "Found more than one bus? " + busID); + } - busStops = bus.route.getRouteSection(instance, bus.direction); - Log.i(TAG, "Got " + busStops.size() + " bus stops for this bus"); + helper.getBusRouteDao().refresh(bus.route); + + busStop = null; + if (busStopID != null) { + List busStops = helper.getBusStopDao().queryForEq(BusStop.ID_FIELD_NAME, busStopID); + if (busStops.size() == 0) { + Log.e(TAG, "BusStop " + busStopID + " not found!"); + } else if (busStops.size() == 1) { + busStop = busStops.get(0); + } else if (busStops.size() > 1) { + Log.e(TAG, "Found more than one busStop? " + busStopID); + } + } - if (bus.destination != null) { - Log.i(TAG, "Bus destination is " + bus.destination); - } else { - Log.i(TAG, "Bus destination is null"); - } + U1RouteTextView = (TextView) findViewById(R.id.busActivityU1); + U1NRouteTextView = (TextView) findViewById(R.id.busActivityU1N); + U2RouteTextView = (TextView) findViewById(R.id.busActivityU2); + U6RouteTextView = (TextView) findViewById(R.id.busActivityU6); + U9RouteTextView = (TextView) findViewById(R.id.busActivityU9); + + busIDTextView = (TextView) findViewById(R.id.busActivityBusID); + + busContentMessage = (TextView) findViewById(R.id.busActivityMessage); + busActivityContentLayout = (LinearLayout) findViewById(R.id.busActivityContentLayout); + timetableView = (ListView) findViewById(R.id.busActivityTimes); + + if (bus.id != null) { + Log.i(TAG, "Bus id is not null (" + bus.id + ") setting busIDTextView"); + busIDTextView.setText(bus.id + " " + bus.getName()); + } else { + Log.w(TAG, "Bus id is null?"); + // Might not ever happen + busIDTextView.setText("Unidentified"); + } - /* - * for (int i = 0;; i++) { BusStop nextStop = bus.route.moveInRoute(instance, busStops.get(i), bus.direction, - * 1); - * - * if (nextStop.equals(busStop) || (bus.destination != null && bus.destination.equals(nextStop))) { break; } - * - * busStops.add(nextStop); busStopsActive.add(false); - * - * if (busStops.size() > 50) { Log.e(TAG, "Got more than 50 bus stops"); break; } } - */ + U1RouteTextView.setVisibility(View.GONE); + U1NRouteTextView.setVisibility(View.GONE); + U2RouteTextView.setVisibility(View.GONE); + U6RouteTextView.setVisibility(View.GONE); + U9RouteTextView.setVisibility(View.GONE); + + // if (bus.route.uniLink) { + Log.i(TAG, "Bus is uniLink"); + if (bus.route.code.equals("U1")) { + U1RouteTextView.setVisibility(View.VISIBLE); + } else if (bus.route.code.equals("U1N")) { + U1NRouteTextView.setVisibility(View.VISIBLE); + } else if (bus.route.code.equals("U2")) { + U2RouteTextView.setVisibility(View.VISIBLE); + } else if (bus.route.code.equals("U6")) { + U6RouteTextView.setVisibility(View.VISIBLE); + } else if (bus.route.code.equals("U9")) { + U9RouteTextView.setVisibility(View.VISIBLE); + } else { + Log.e(TAG, "Route not found " + bus.route.code); + } + // } else { + // Log.i(TAG, "Bus is not uniLink"); + // } + + } catch (NumberFormatException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } - refreshData = new Runnable() { - @Override - public void run() { - for (int num = timetableView.getFirstVisiblePosition(); num < timetableView.getLastVisiblePosition(); num++) { - Stop stop = timetable.get(num); + busStops = bus.route.getRouteSection(instance, bus.direction); + Log.i(TAG, "Got " + busStops.size() + " bus stops for this bus"); - GetTimetableStopTask task = tasks.get(busStops.get(num)); + if (bus.destination != null) { + Log.i(TAG, "Bus destination is " + bus.destination); + } else { + Log.i(TAG, "Bus destination is null"); + } - if (stop.timeOfFetch == null || (stop.timeOfFetch.getTime() - System.currentTimeMillis()) > 20000) { - if (task != null) { - if (task.getStatus() == AsyncTask.Status.FINISHED) { - task = null; - } + /* + * for (int i = 0;; i++) { BusStop nextStop = bus.route.moveInRoute(instance, busStops.get(i), bus.direction, 1); + * + * if (nextStop.equals(busStop) || (bus.destination != null && bus.destination.equals(nextStop))) { break; } + * + * busStops.add(nextStop); busStopsActive.add(false); + * + * if (busStops.size() > 50) { Log.e(TAG, "Got more than 50 bus stops"); break; } } + */ + + refreshData = new Runnable() { + public void run() { + for (int num = timetableView.getFirstVisiblePosition(); num < timetableView.getLastVisiblePosition(); num++) { + Stop stop = timetable.get(num); + + GetTimetableStopTask task = tasks.get(busStops.get(num)); + + if (stop.timeOfFetch == null || (stop.timeOfFetch.getTime() - System.currentTimeMillis()) > 20000) { + if (task != null) { + if (task.getStatus() == AsyncTask.Status.FINISHED) { + task = null; + } + } + + if (task == null) { + task = new GetTimetableStopTask(); + BusStop[] str = { stop.busStop }; + task.execute(str); + tasks.put(stop.busStop, task); + } + } + + } + handler.postDelayed(refreshData, 50000); } + }; - if (task == null) { - task = new GetTimetableStopTask(); - BusStop[] str = { stop.busStop }; - task.execute(str); - tasks.put(stop.busStop, task); - } - } + } - } - handler.postDelayed(refreshData, 50000); - } - }; + public void onResume() { + super.onResume(); - } + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); + if (sharedPrefs.getBoolean(UNI_LINK_BUS_TIMES, UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT) + || sharedPrefs.getBoolean(NON_UNI_LINK_BUS_TIMES, NON_UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT)) { + Log.i(TAG, "Live Times enabled"); + timetable = (Timetable) getLastNonConfigurationInstance(); - public void onResume() { - super.onResume(); + handler = new Handler(); - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - if (sharedPrefs.getBoolean(UNI_LINK_BUS_TIMES, UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT) - || sharedPrefs.getBoolean(NON_UNI_LINK_BUS_TIMES, NON_UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT)) { - Log.i(TAG, "Live Times enabled"); - timetable = (Timetable) getLastNonConfigurationInstance(); + if (timetable == null) { + Log.i(TAG, "No Previous timetable"); + timetable = new Timetable(); + for (int i = 0; i < busStops.size(); i++) { + timetable.add(new Stop(bus, busStops.get(i), null, null, false)); + } + Log.v(TAG, "Finished adding placeholder stops"); + } else { + Log.i(TAG, "Displaying previous timetable"); - handler = new Handler(); + } + displayTimetable(timetable); + handler.postDelayed(refreshData, 500); - if (timetable == null) { - Log.i(TAG, "No Previous timetable"); - timetable = new Timetable(); - for (int i = 0; i < busStops.size(); i++) { - timetable.add(new Stop(bus, busStops.get(i), null, null, false)); + } else { + Log.i(TAG, "Live Times Disabled"); + busContentMessage.setText("Live bus times disabled"); + busContentMessage.setVisibility(View.VISIBLE); } - Log.v(TAG, "Finished adding placeholder stops"); - } else { - Log.i(TAG, "Displaying previous timetable"); - - } - displayTimetable(timetable); - handler.postDelayed(refreshData, 500); - - } else { - Log.i(TAG, "Live Times Disabled"); - busContentMessage.setText("Live bus times disabled"); - busContentMessage.setVisibility(View.VISIBLE); + } - } + public void onPause() { + if (handler != null) { // BusTimes are enabled + handler.removeCallbacks(refreshData); + for (GetTimetableStopTask task : tasks.values()) { + if (task != null) { + task.cancel(true); + } + } - public void onPause() { - if (handler != null) { // BusTimes are enabled - handler.removeCallbacks(refreshData); - for (GetTimetableStopTask task : tasks.values()) { - if (task != null) { - task.cancel(true); + Log.i(TAG, "Stoping refreshing timetable data"); } - } - Log.i(TAG, "Stoping refreshing timetable data"); + super.onPause(); } - super.onPause(); - } + private class GetTimetableStopTask extends AsyncTask { + private String errorMessage; - private class GetTimetableStopTask extends AsyncTask { - private String errorMessage; + private BusStop busStop; - private BusStop busStop; - - private int position; - - protected void onPreExecute() { - // progBar.setVisibility(View.VISIBLE); - } + private int position; - protected Stop doInBackground(BusStop... busStopArray) { - busStop = busStopArray[0]; - position = busStops.indexOf(busStop); - Stop stop = null; + protected void onPreExecute() { + // progBar.setVisibility(View.VISIBLE); + } - try { - Log.i(TAG, "Fetching stop for busStop " + position); - stop = DataManager.getStop(instance, bus, busStop); - if (stop == null) { - stop = new Stop(bus, busStop, null, null, false); + protected Stop doInBackground(BusStop... busStopArray) { + busStop = busStopArray[0]; + position = busStops.indexOf(busStop); + Stop stop = null; + + try { + Log.i(TAG, "Fetching stop for busStop " + position); + stop = DataManager.getStop(instance, bus, busStop); + if (stop == null) { + stop = new Stop(bus, busStop, null, null, false); + } + Log.i(TAG, "Finished fetching stop for busStop " + position); + } catch (SQLException e) { + errorMessage = "Error message regarding SQL?"; + e.printStackTrace(); + } catch (ClientProtocolException e) { + errorMessage = "ClientProtocolException!?!"; + e.printStackTrace(); + } catch (IOException e) { + errorMessage = "Error fetching bus times from server, are you connected to the internet?"; + e.printStackTrace(); + } catch (JSONException e) { + errorMessage = "Error parsing bus times"; + e.printStackTrace(); + } + return stop; } - Log.i(TAG, "Finished fetching stop for busStop " + position); - } catch (SQLException e) { - errorMessage = "Error message regarding SQL?"; - e.printStackTrace(); - } catch (ClientProtocolException e) { - errorMessage = "ClientProtocolException!?!"; - e.printStackTrace(); - } catch (IOException e) { - errorMessage = "Error fetching bus times from server, are you connected to the internet?"; - e.printStackTrace(); - } catch (JSONException e) { - errorMessage = "Error parsing bus times"; - e.printStackTrace(); - } - return stop; - } - protected void onPostExecute(Stop stop) { - // Log.i(TAG, "Got timetable"); - if (stop == null) { - Log.i(TAG, "Its null"); - - busContentMessage.setText(errorMessage); - busContentMessage.setVisibility(View.VISIBLE); - } else { - synchronized (timetable) { - timetable.set(position, stop); - displayTimetable(timetable); + protected void onPostExecute(Stop stop) { + // Log.i(TAG, "Got timetable"); + if (stop == null) { + Log.i(TAG, "Its null"); + + busContentMessage.setText(errorMessage); + busContentMessage.setVisibility(View.VISIBLE); + } else { + synchronized (timetable) { + timetable.set(position, stop); + displayTimetable(timetable); + } + } } - } + } - } - - private void displayTimetable(Timetable timetable) { - visibleTimetable = (Timetable) timetable.clone(); - - // Log.i(TAG, "Displaying timetable, it contains " + visibleTimetable.size() + " stops"); - - if (timetable.size() == 0) { - busContentMessage.setText("No Busses"); - busContentMessage.setVisibility(View.VISIBLE); - busActivityContentLayout.setGravity(Gravity.CENTER); - } else { - if (visibleTimetable.size() == 0) { - busActivityContentLayout.setGravity(Gravity.CENTER); - busContentMessage.setText("No Busses (With the current enabled routes)"); - busContentMessage.setVisibility(View.VISIBLE); - timetableView.setVisibility(View.GONE); - } else { - timetableView.setVisibility(View.VISIBLE); - busContentMessage.setVisibility(View.GONE); - BusSpecificTimetableAdapter adapter; - if ((adapter = (BusSpecificTimetableAdapter) timetableView.getAdapter()) != null) { - adapter.updateTimetable(visibleTimetable); + private void displayTimetable(Timetable timetable) { + visibleTimetable = (Timetable) timetable.clone(); + + // Log.i(TAG, "Displaying timetable, it contains " + visibleTimetable.size() + " stops"); + + if (timetable.size() == 0) { + busContentMessage.setText("No Busses"); + busContentMessage.setVisibility(View.VISIBLE); + busActivityContentLayout.setGravity(Gravity.CENTER); } else { - adapter = new BusSpecificTimetableAdapter(this, visibleTimetable); - timetableView.setAdapter(adapter); - if (busStop != null) { - Log.i(TAG, - "Moving to position of " + busStop.description + " which is " - + busStops.indexOf(busStop)); - timetableView.setSelection(busStops.indexOf(busStop)); - } + if (visibleTimetable.size() == 0) { + busActivityContentLayout.setGravity(Gravity.CENTER); + busContentMessage.setText("No Busses (With the current enabled routes)"); + busContentMessage.setVisibility(View.VISIBLE); + timetableView.setVisibility(View.GONE); + } else { + timetableView.setVisibility(View.VISIBLE); + busContentMessage.setVisibility(View.GONE); + BusSpecificTimetableAdapter adapter; + if ((adapter = (BusSpecificTimetableAdapter) timetableView.getAdapter()) != null) { + adapter.updateTimetable(visibleTimetable); + } else { + adapter = new BusSpecificTimetableAdapter(this, visibleTimetable); + timetableView.setAdapter(adapter); + if (busStop != null) { + Log.i(TAG, "Moving to position of " + busStop.description + " which is " + busStops.indexOf(busStop)); + timetableView.setSelection(busStops.indexOf(busStop)); + } + } + busActivityContentLayout.setGravity(Gravity.TOP); + } } - busActivityContentLayout.setGravity(Gravity.TOP); - } } - } } diff --git a/src/net/cbaines/suma/BusSpecificStopView.java b/src/net/cbaines/suma/BusSpecificStopView.java index 77601ff..293da03 100644 --- a/src/net/cbaines/suma/BusSpecificStopView.java +++ b/src/net/cbaines/suma/BusSpecificStopView.java @@ -38,150 +38,151 @@ import com.j256.ormlite.dao.Dao; public class BusSpecificStopView extends LinearLayout implements OnClickListener, OnLongClickListener { - private static final String TAG = "BusSpecificStopView"; + private static final String TAG = "BusSpecificStopView"; - // private static final String TAG = "StopView"; + // private static final String TAG = "StopView"; - private final TextView location; - private final TextView time; - private String onClickMessage = ""; - private final BusActivity context; + private final TextView location; + private final TextView time; + private String onClickMessage = ""; + private final BusActivity context; - private Stop stop; + private Stop stop; - public BusSpecificStopView(BusActivity context, Stop stop) { - super(context); + public BusSpecificStopView(BusActivity context, Stop stop) { + super(context); - this.context = context; + this.context = context; - this.setOrientation(HORIZONTAL); + this.setOrientation(HORIZONTAL); - location = new TextView(context); - location.setTextSize(22f); + location = new TextView(context); + location.setTextSize(22f); - time = new TextView(context); - time.setTextSize(22f); - time.setGravity(Gravity.RIGHT); + time = new TextView(context); + time.setTextSize(22f); + time.setGravity(Gravity.RIGHT); - setStop(stop); + setStop(stop); - addView(location, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); - addView(time, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); + addView(location, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); + addView(time, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); - } - - public void setStop(Stop stop) { - - // Log.i(TAG, "Time of arival " + stop.arivalTime); - - this.stop = stop; - - if (stop == null) { - Log.e(TAG, "stop == null"); - } - if (stop.busStop == null) { - Log.e(TAG, "stop.busStop == null"); - } - if (stop.busStop.description == null) { - Log.e(TAG, "stop.busStop.description == null"); } - if (stop.busStop.description.length() > 20) { - location.setText(stop.busStop.description.substring(0, 20)); // TODO - } else { - location.setText(stop.busStop.description); // TODO - } - if (stop.arivalTime != null) { - time.setText(stop.getShortTimeToArival()); - } else { - time.setText(""); - } + public void setStop(Stop stop) { - DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class); + // Log.i(TAG, "Time of arival " + stop.arivalTime); - try { - Dao busDao = helper.getBusDao(); + this.stop = stop; - busDao.refresh(stop.bus); - - if (stop.arivalTime != null) { + if (stop == null) { + Log.e(TAG, "stop == null"); + } + if (stop.busStop == null) { + Log.e(TAG, "stop.busStop == null"); + } + if (stop.busStop.description == null) { + Log.e(TAG, "stop.busStop.description == null"); + } - if (stop.bus.id != null) { - if (stop.live) { - onClickMessage = "Bus " + stop.bus.toString() + " at " + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); - } else { - onClickMessage = "Timetabled bus " + stop.bus.toString() + " at " - + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); - } + if (stop.busStop.description.length() > 20) { + location.setText(stop.busStop.description.substring(0, 20)); // TODO } else { - if (stop.live) { - onClickMessage = "Unidentified bus (" + stop.bus.getName() + ") at " - + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); - } else { - onClickMessage = "Timetabled bus (" + stop.bus.getName() + ") at " - + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); - } + location.setText(stop.busStop.description); // TODO } - } else { - if (stop.bus.id != null) { - if (stop.live) { - onClickMessage = "Bus " + stop.bus.toString(); - } else { - onClickMessage = "Timetabled bus " + stop.bus.toString(); - } + if (stop.arivalTime != null) { + time.setText(stop.getShortTimeToArival()); } else { - if (stop.live) { - onClickMessage = "Unidentified bus (" + stop.bus.getName() + ")"; - } else { - onClickMessage = "Timetabled bus (" + stop.bus.getName() + ")"; - } + time.setText(""); } - } - } catch (SQLException e) { - e.printStackTrace(); - } - this.setOnClickListener(this); - this.setOnLongClickListener(this); - } + DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class); + + try { + Dao busDao = helper.getBusDao(); + + busDao.refresh(stop.bus); + + if (stop.arivalTime != null) { + + if (stop.bus.id != null) { + if (stop.live) { + onClickMessage = "Bus " + stop.bus.toString() + " at " + + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); + } else { + onClickMessage = "Timetabled bus " + stop.bus.toString() + " at " + + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); + } + } else { + if (stop.live) { + onClickMessage = "Unidentified bus (" + stop.bus.getName() + ") at " + + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); + } else { + onClickMessage = "Timetabled bus (" + stop.bus.getName() + ") at " + + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); + } + } + } else { + if (stop.bus.id != null) { + if (stop.live) { + onClickMessage = "Bus " + stop.bus.toString(); + } else { + onClickMessage = "Timetabled bus " + stop.bus.toString(); + } + } else { + if (stop.live) { + onClickMessage = "Unidentified bus (" + stop.bus.getName() + ")"; + } else { + onClickMessage = "Timetabled bus (" + stop.bus.getName() + ")"; + } + } + } + } catch (SQLException e) { + e.printStackTrace(); + } - public void onClick(View v) { - if (context.activityToast == null) { - context.activityToast = Toast.makeText(context, onClickMessage, Toast.LENGTH_SHORT); - } else { - context.activityToast.setText(onClickMessage); - context.activityToast.setDuration(Toast.LENGTH_SHORT); + this.setOnClickListener(this); + this.setOnLongClickListener(this); } - context.activityToast.show(); - } - - @Override - public boolean onLongClick(View v) { // TODO - DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class); - try { - Dao busDao = helper.getBusDao(); - - busDao.refresh(stop.bus); - - if (stop.bus.id != null) { - Intent i = new Intent(context, MapActivity.class); - i.putExtra("poiPoint", stop.busStop.point.toDoubleString()); - ((Activity) context).startActivityForResult(i, 0); - } else { + public void onClick(View v) { if (context.activityToast == null) { - context.activityToast = Toast.makeText(context, "Arival prediction not avalible for timetabled buses", Toast.LENGTH_SHORT); + context.activityToast = Toast.makeText(context, onClickMessage, Toast.LENGTH_SHORT); } else { - context.activityToast.setText("Arival prediction not avalible for timetabled buses"); - context.activityToast.setDuration(Toast.LENGTH_SHORT); + context.activityToast.setText(onClickMessage); + context.activityToast.setDuration(Toast.LENGTH_SHORT); } context.activityToast.show(); - } + } - } catch (SQLException e) { - e.printStackTrace(); + public boolean onLongClick(View v) { // TODO + DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class); + + try { + Dao busDao = helper.getBusDao(); + + busDao.refresh(stop.bus); + + if (stop.bus.id != null) { + Intent i = new Intent(context, MapActivity.class); + i.putExtra("poiPoint", stop.busStop.point.toDoubleString()); + ((Activity) context).startActivityForResult(i, 0); + } else { + if (context.activityToast == null) { + context.activityToast = Toast.makeText(context, "Arival prediction not avalible for timetabled buses", + Toast.LENGTH_SHORT); + } else { + context.activityToast.setText("Arival prediction not avalible for timetabled buses"); + context.activityToast.setDuration(Toast.LENGTH_SHORT); + } + context.activityToast.show(); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + return false; } - return false; - } } diff --git a/src/net/cbaines/suma/BusStopActivity.java b/src/net/cbaines/suma/BusStopActivity.java index 03dcbca..ab0a9b5 100644 --- a/src/net/cbaines/suma/BusStopActivity.java +++ b/src/net/cbaines/suma/BusStopActivity.java @@ -59,455 +59,456 @@ import com.j256.ormlite.dao.Dao; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; -public class BusStopActivity extends OrmLiteBaseActivity implements OnCheckedChangeListener, Preferences, OnItemClickListener { +public class BusStopActivity extends OrmLiteBaseActivity implements OnCheckedChangeListener, Preferences, + OnItemClickListener { - final static String TAG = "BusTimeActivity"; - - private boolean dataChanged; - - private ListView busTimeList; - private TextView busName; - private TextView busID; - private CheckBox busFavourite; - private TextView busStopMessage; - private ProgressBar progBar; - private LinearLayout busTimeContentLayout; - - protected Timetable timetable; - private Timetable visibleTimetable; - - protected String busStopID; - private String busStopName; - - private Dao busStopDao; - - private BusStop busStop; - - private GetTimetableTask timetableTask; - - private Context instance; - - private Handler mHandler; - private Runnable refreshData; - - private CheckBox U1RouteRadioButton; - private CheckBox U1NRouteRadioButton; - private CheckBox U2RouteRadioButton; - private CheckBox U6RouteRadioButton; - private CheckBox U9RouteRadioButton; - - private static final int POI_DIALOG_ID = 0; - private POIDialog busDialog; - - private HashSet routes = new HashSet(); - - Toast activityToast; - - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.bustimes); - - final DatabaseHelper helper = getHelper(); - - instance = this; - - busStopID = getIntent().getExtras().getString("busStopID"); - busStopName = getIntent().getExtras().getString("busStopName"); - - U1RouteRadioButton = (CheckBox) findViewById(R.id.radio_u1); - U1NRouteRadioButton = (CheckBox) findViewById(R.id.radio_u1n); - U2RouteRadioButton = (CheckBox) findViewById(R.id.radio_u2); - U6RouteRadioButton = (CheckBox) findViewById(R.id.radio_u6); - U9RouteRadioButton = (CheckBox) findViewById(R.id.radio_u9); - - U1RouteRadioButton.setOnCheckedChangeListener(this); - U1NRouteRadioButton.setOnCheckedChangeListener(this); - U2RouteRadioButton.setOnCheckedChangeListener(this); - U6RouteRadioButton.setOnCheckedChangeListener(this); - U9RouteRadioButton.setOnCheckedChangeListener(this); - - try { - Dao busRouteDao = helper.getBusRouteDao(); - Dao routeStopsDao = helper.getRouteStopsDao(); - - for (BusRoute route : busRouteDao) { - QueryBuilder queryBuilder = routeStopsDao.queryBuilder(); - - queryBuilder.where().eq(RouteStops.ROUTE_ID_FIELD_NAME, route.id).and().eq(RouteStops.STOP_ID_FIELD_NAME, busStopID); - queryBuilder.setCountOf(true); - PreparedQuery preparedQuery = queryBuilder.prepare(); - - long count = routeStopsDao.countOf(preparedQuery); - - if (route.code.equals("U1")) { - if (count != 0) { - U1RouteRadioButton.setVisibility(View.VISIBLE); - routes.add(route); - } else { - U1RouteRadioButton.setVisibility(View.GONE); - } - } else if (route.code.equals("U1N")) { - if (count != 0) { - U1NRouteRadioButton.setVisibility(View.VISIBLE); - routes.add(route); - } else { - U1NRouteRadioButton.setVisibility(View.GONE); - } - } else if (route.code.equals("U2")) { - if (count != 0) { - U2RouteRadioButton.setVisibility(View.VISIBLE); - routes.add(route); - } else { - U2RouteRadioButton.setVisibility(View.GONE); - } - } else if (route.code.equals("U6")) { - if (count != 0) { - U6RouteRadioButton.setVisibility(View.VISIBLE); - routes.add(route); - } else { - U6RouteRadioButton.setVisibility(View.GONE); - } - } else if (route.code.equals("U9")) { - if (count != 0) { - U9RouteRadioButton.setVisibility(View.VISIBLE); - routes.add(route); - } else { - U9RouteRadioButton.setVisibility(View.GONE); - } - } - } + final static String TAG = "BusTimeActivity"; - busStopDao = helper.getBusStopDao(); + private boolean dataChanged; - busStop = busStopDao.queryForId(busStopID); + private ListView busTimeList; + private TextView busName; + private TextView busID; + private CheckBox busFavourite; + private TextView busStopMessage; + private ProgressBar progBar; + private LinearLayout busTimeContentLayout; - busFavourite = (CheckBox) findViewById(R.id.favouriteCheckBox); - busFavourite.setChecked(busStop.favourite); - busFavourite.setOnCheckedChangeListener(this); + protected Timetable timetable; + private Timetable visibleTimetable; - } catch (SQLException e) { - e.printStackTrace(); - } + protected String busStopID; + private String busStopName; - busName = (TextView) findViewById(R.id.busStopName); - busID = (TextView) findViewById(R.id.busStopID); + private Dao busStopDao; - busStopMessage = (TextView) findViewById(R.id.busStopMessage); - progBar = (ProgressBar) findViewById(R.id.busStopLoadBar); - busTimeList = (ListView) findViewById(R.id.busStopTimes); - busTimeContentLayout = (LinearLayout) findViewById(R.id.busTimeContentLayout); + private BusStop busStop; - Log.i(TAG, "Got busstop id " + busStopID); + private GetTimetableTask timetableTask; - busName.setText(busStopName); - busID.setText(busStopID); - } + private Context instance; - public void onResume() { - super.onResume(); + private Handler mHandler; + private Runnable refreshData; - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - if (sharedPrefs.getBoolean(UNI_LINK_BUS_TIMES, UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT) - || sharedPrefs.getBoolean(NON_UNI_LINK_BUS_TIMES, NON_UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT)) { - Log.i(TAG, "Live Times enabled"); - timetable = (Timetable) getLastNonConfigurationInstance(); + private CheckBox U1RouteRadioButton; + private CheckBox U1NRouteRadioButton; + private CheckBox U2RouteRadioButton; + private CheckBox U6RouteRadioButton; + private CheckBox U9RouteRadioButton; - refreshData = new Runnable() { - @Override - public void run() { - timetableTask = new GetTimetableTask(); - timetableTask.execute(busStopID); - mHandler.postDelayed(refreshData, 20000); - } - }; - - mHandler = new Handler(); - - if (timetable == null) { - Log.i(TAG, "No Previous timetable"); - mHandler.post(refreshData); - } else { - Log.i(TAG, "Displaying previous timetable"); - displayTimetable(timetable); - if (System.currentTimeMillis() - timetable.fetchTime.getTime() > 20000) { - mHandler.post(refreshData); + private static final int POI_DIALOG_ID = 0; + private POIDialog busDialog; + + private HashSet routes = new HashSet(); + + Toast activityToast; + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.bustimes); + + final DatabaseHelper helper = getHelper(); + + instance = this; + + busStopID = getIntent().getExtras().getString("busStopID"); + busStopName = getIntent().getExtras().getString("busStopName"); + + U1RouteRadioButton = (CheckBox) findViewById(R.id.radio_u1); + U1NRouteRadioButton = (CheckBox) findViewById(R.id.radio_u1n); + U2RouteRadioButton = (CheckBox) findViewById(R.id.radio_u2); + U6RouteRadioButton = (CheckBox) findViewById(R.id.radio_u6); + U9RouteRadioButton = (CheckBox) findViewById(R.id.radio_u9); + + U1RouteRadioButton.setOnCheckedChangeListener(this); + U1NRouteRadioButton.setOnCheckedChangeListener(this); + U2RouteRadioButton.setOnCheckedChangeListener(this); + U6RouteRadioButton.setOnCheckedChangeListener(this); + U9RouteRadioButton.setOnCheckedChangeListener(this); + + try { + Dao busRouteDao = helper.getBusRouteDao(); + Dao routeStopsDao = helper.getRouteStopsDao(); + + for (BusRoute route : busRouteDao) { + QueryBuilder queryBuilder = routeStopsDao.queryBuilder(); + + queryBuilder.where().eq(RouteStops.ROUTE_ID_FIELD_NAME, route.id).and() + .eq(RouteStops.STOP_ID_FIELD_NAME, busStopID); + queryBuilder.setCountOf(true); + PreparedQuery preparedQuery = queryBuilder.prepare(); + + long count = routeStopsDao.countOf(preparedQuery); + + if (route.code.equals("U1")) { + if (count != 0) { + U1RouteRadioButton.setVisibility(View.VISIBLE); + routes.add(route); + } else { + U1RouteRadioButton.setVisibility(View.GONE); + } + } else if (route.code.equals("U1N")) { + if (count != 0) { + U1NRouteRadioButton.setVisibility(View.VISIBLE); + routes.add(route); + } else { + U1NRouteRadioButton.setVisibility(View.GONE); + } + } else if (route.code.equals("U2")) { + if (count != 0) { + U2RouteRadioButton.setVisibility(View.VISIBLE); + routes.add(route); + } else { + U2RouteRadioButton.setVisibility(View.GONE); + } + } else if (route.code.equals("U6")) { + if (count != 0) { + U6RouteRadioButton.setVisibility(View.VISIBLE); + routes.add(route); + } else { + U6RouteRadioButton.setVisibility(View.GONE); + } + } else if (route.code.equals("U9")) { + if (count != 0) { + U9RouteRadioButton.setVisibility(View.VISIBLE); + routes.add(route); + } else { + U9RouteRadioButton.setVisibility(View.GONE); + } + } + } + + busStopDao = helper.getBusStopDao(); + + busStop = busStopDao.queryForId(busStopID); + + busFavourite = (CheckBox) findViewById(R.id.favouriteCheckBox); + busFavourite.setChecked(busStop.favourite); + busFavourite.setOnCheckedChangeListener(this); + + } catch (SQLException e) { + e.printStackTrace(); } - } - } else { - Log.i(TAG, "Live Times Disabled"); - progBar.setVisibility(View.GONE); - busStopMessage.setText("Live bus times disabled"); - busStopMessage.setVisibility(View.VISIBLE); - } + busName = (TextView) findViewById(R.id.busStopName); + busID = (TextView) findViewById(R.id.busStopID); + + busStopMessage = (TextView) findViewById(R.id.busStopMessage); + progBar = (ProgressBar) findViewById(R.id.busStopLoadBar); + busTimeList = (ListView) findViewById(R.id.busStopTimes); + busTimeContentLayout = (LinearLayout) findViewById(R.id.busTimeContentLayout); - } + Log.i(TAG, "Got busstop id " + busStopID); - public void onPause() { - if (mHandler != null) { // BusTimes are enabled - mHandler.removeCallbacks(refreshData); - if (timetableTask != null) // Could happen if the handler has not created the timetableTask yet - timetableTask.cancel(true); - Log.i(TAG, "Stoping refreshing timetable data"); + busName.setText(busStopName); + busID.setText(busStopID); } - super.onPause(); - } + public void onResume() { + super.onResume(); + + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); + if (sharedPrefs.getBoolean(UNI_LINK_BUS_TIMES, UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT) + || sharedPrefs.getBoolean(NON_UNI_LINK_BUS_TIMES, NON_UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT)) { + Log.i(TAG, "Live Times enabled"); + timetable = (Timetable) getLastNonConfigurationInstance(); + + refreshData = new Runnable() { + public void run() { + timetableTask = new GetTimetableTask(); + timetableTask.execute(busStopID); + mHandler.postDelayed(refreshData, 20000); + } + }; + + mHandler = new Handler(); + + if (timetable == null) { + Log.i(TAG, "No Previous timetable"); + mHandler.post(refreshData); + } else { + Log.i(TAG, "Displaying previous timetable"); + displayTimetable(timetable); + if (System.currentTimeMillis() - timetable.fetchTime.getTime() > 20000) { + mHandler.post(refreshData); + } + } + + } else { + Log.i(TAG, "Live Times Disabled"); + progBar.setVisibility(View.GONE); + busStopMessage.setText("Live bus times disabled"); + busStopMessage.setVisibility(View.VISIBLE); + } - public void finish() { - if (dataChanged) { - getIntent().putExtra("busStopChanged", busStopID); } - setResult(RESULT_OK, getIntent()); - - super.finish(); - } - - public void onCheckedChanged(CompoundButton button, boolean checked) { - if (button.equals(busFavourite)) { - busStop.favourite = checked; - try { - busStopDao.update(busStop); - dataChanged = true; - } catch (SQLException e) { - e.printStackTrace(); - } - } else { - Log.i(TAG, "Route radio button made " + checked); - if (timetable != null) { // If there is a timetable to display - displayTimetable(timetable); - } + public void onPause() { + if (mHandler != null) { // BusTimes are enabled + mHandler.removeCallbacks(refreshData); + if (timetableTask != null) // Could happen if the handler has not created the timetableTask yet + timetableTask.cancel(true); + Log.i(TAG, "Stoping refreshing timetable data"); + } + + super.onPause(); } - } - @Override - public Object onRetainNonConfigurationInstance() { - return timetable; - } + public void finish() { + if (dataChanged) { + getIntent().putExtra("busStopChanged", busStopID); + } - private class GetTimetableTask extends AsyncTask { - String errorMessage; + setResult(RESULT_OK, getIntent()); - protected void onPreExecute() { - progBar.setVisibility(View.VISIBLE); + super.finish(); } - protected Timetable doInBackground(String... activity) { - Timetable newTimetable = null; - try { - final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(instance); - - newTimetable = DataManager.getTimetable(instance, busStopID, sharedPrefs.getBoolean(MapActivity.UNI_LINK_BUS_TIMES, - MapActivity.UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT), sharedPrefs.getBoolean( - MapActivity.NON_UNI_LINK_BUS_TIMES, MapActivity.NON_UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT)); - } catch (SQLException e) { - errorMessage = "Error message regarding SQL?"; - e.printStackTrace(); - } catch (ClientProtocolException e) { - errorMessage = "ClientProtocolException!?!"; - e.printStackTrace(); - } catch (IOException e) { - errorMessage = "Error fetching bus times from server, are you connected to the internet?"; - e.printStackTrace(); - } catch (JSONException e) { - errorMessage = "Error parsing bus times"; - e.printStackTrace(); - } catch (Exception e) { - Log.e(TAG, e.getMessage(), e.getCause()); - } - - return newTimetable; + public void onCheckedChanged(CompoundButton button, boolean checked) { + if (button.equals(busFavourite)) { + busStop.favourite = checked; + try { + busStopDao.update(busStop); + dataChanged = true; + } catch (SQLException e) { + e.printStackTrace(); + } + } else { + Log.i(TAG, "Route radio button made " + checked); + if (timetable != null) { // If there is a timetable to display + displayTimetable(timetable); + } + } } - protected void onPostExecute(Timetable newTimetable) { - Log.i(TAG, "Got timetable for " + busStopID); - if (newTimetable == null) { - Log.i(TAG, "Its null"); - - progBar.setVisibility(View.GONE); - busStopMessage.setText(errorMessage); - busStopMessage.setVisibility(View.VISIBLE); - } else { - progBar.setVisibility(View.GONE); - timetable = newTimetable; - displayTimetable(timetable); - } + @Override + public Object onRetainNonConfigurationInstance() { + return timetable; } - } - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.stop_menu, menu); - return true; - } + private class GetTimetableTask extends AsyncTask { + String errorMessage; - @Override - public boolean onOptionsItemSelected(MenuItem item) { - // Handle item selection - if (item.getItemId() == R.id.menu_previous_stop || item.getItemId() == R.id.menu_next_stop) { - Log.v(TAG, "Got a request for the stop movement"); + protected void onPreExecute() { + progBar.setVisibility(View.VISIBLE); + } - Log.v(TAG, routes.size() + " routes avalible from this stop"); + protected Timetable doInBackground(String... activity) { + Timetable newTimetable = null; + try { + final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(instance); + + newTimetable = DataManager + .getTimetable(instance, busStopID, sharedPrefs.getBoolean(MapActivity.UNI_LINK_BUS_TIMES, + MapActivity.UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT), sharedPrefs.getBoolean( + MapActivity.NON_UNI_LINK_BUS_TIMES, MapActivity.NON_UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT)); + } catch (SQLException e) { + errorMessage = "Error message regarding SQL?"; + e.printStackTrace(); + } catch (ClientProtocolException e) { + errorMessage = "ClientProtocolException!?!"; + e.printStackTrace(); + } catch (IOException e) { + errorMessage = "Error fetching bus times from server, are you connected to the internet?"; + e.printStackTrace(); + } catch (JSONException e) { + errorMessage = "Error parsing bus times"; + e.printStackTrace(); + } catch (Exception e) { + Log.e(TAG, e.getMessage(), e.getCause()); + } - ArrayList busStops = new ArrayList(); + return newTimetable; + } - for (BusRoute route : routes) { - try { - Set tmpStops; - if (item.getItemId() == R.id.menu_next_stop) { - tmpStops = route.moveInRoute(this, getHelper().getBusStopDao().queryForId(busStopID), 1); - } else { - tmpStops = route.moveInRoute(this, getHelper().getBusStopDao().queryForId(busStopID), -1); - } - for (BusStop busStop : tmpStops) { - if (!busStops.contains(busStop)) { - busStops.add(busStop); + protected void onPostExecute(Timetable newTimetable) { + Log.i(TAG, "Got timetable for " + busStopID); + if (newTimetable == null) { + Log.i(TAG, "Its null"); + + progBar.setVisibility(View.GONE); + busStopMessage.setText(errorMessage); + busStopMessage.setVisibility(View.VISIBLE); + } else { + progBar.setVisibility(View.GONE); + timetable = newTimetable; + displayTimetable(timetable); } - } - } catch (SQLException e) { - e.printStackTrace(); } - } + } - Log.i(TAG, "stops " + busStops); + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.stop_menu, menu); + return true; + } - if (busStops.size() == 1) { - Intent i = new Intent(this, BusStopActivity.class); - BusStop stop = (BusStop) busStops.iterator().next(); - if (stop == null) { - Log.e(TAG, "stop == null"); - } - if (stop.id == null) { - Log.e(TAG, "stop.id == null"); - } - i.putExtra("busStopID", stop.id); - i.putExtra("busStopName", stop.description); - startActivity(i); - } else { - showDialog(POI_DIALOG_ID); - if (busDialog == null) { - Log.e(TAG, "Very wierd, just tried to launch the favourite's dialog, but its null?"); - return false; - } + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle item selection + if (item.getItemId() == R.id.menu_previous_stop || item.getItemId() == R.id.menu_next_stop) { + Log.v(TAG, "Got a request for the stop movement"); + + Log.v(TAG, routes.size() + " routes avalible from this stop"); + + ArrayList busStops = new ArrayList(); + + for (BusRoute route : routes) { + try { + Set tmpStops; + if (item.getItemId() == R.id.menu_next_stop) { + tmpStops = route.moveInRoute(this, getHelper().getBusStopDao().queryForId(busStopID), 1); + } else { + tmpStops = route.moveInRoute(this, getHelper().getBusStopDao().queryForId(busStopID), -1); + } + for (BusStop busStop : tmpStops) { + if (!busStops.contains(busStop)) { + busStops.add(busStop); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + } - busDialog.setMessage(""); - busDialog.setItems(busStops); - busDialog.setTitle("Choose Bus Stop"); - - Log.i(TAG, "Showing dialog"); - } - - } else if (item.getItemId() == R.id.menu_refresh_stop) { - if (mHandler != null) { // BusTimes are enabled - mHandler.removeCallbacks(refreshData); - timetableTask.cancel(true); - Log.i(TAG, "Stoping refreshing timetable data"); - - mHandler.post(refreshData); - } else { - // TODO: Toast here... - } - } else { - Log.e(TAG, "No known menu option selected"); - return super.onOptionsItemSelected(item); - } - return true; - } - - private void displayTimetable(Timetable timetable) { - visibleTimetable = (Timetable) timetable.clone(); - - Log.i(TAG, "It contains " + visibleTimetable.size() + " stops"); - - if (timetable.size() == 0) { - busStopMessage.setText("No Busses"); - busStopMessage.setVisibility(View.VISIBLE); - busTimeContentLayout.setGravity(Gravity.CENTER); - } else { - - for (Iterator stopIter = visibleTimetable.iterator(); stopIter.hasNext();) { - Stop stop = stopIter.next(); - Log.i(TAG, "Begin filtering, looking at " + stop + " with route " + stop.bus.route.code); - if (stop.bus.route.code.equals("U1")) { - if (!U1RouteRadioButton.isChecked()) { - stopIter.remove(); - } - } else if (stop.bus.route.code.equals("U1N")) { - if (!U1NRouteRadioButton.isChecked()) { - stopIter.remove(); - } - } else if (stop.bus.route.code.equals("U2")) { - if (!U2RouteRadioButton.isChecked()) { - stopIter.remove(); - } - } else if (stop.bus.route.code.equals("U6")) { - if (!U6RouteRadioButton.isChecked()) { - stopIter.remove(); - } - } else if (stop.bus.route.code.equals("U9")) { - if (!U9RouteRadioButton.isChecked()) { - stopIter.remove(); - } - } - } - - if (visibleTimetable.size() == 0) { - busTimeContentLayout.setGravity(Gravity.CENTER); - busStopMessage.setText("No Busses (With the current enabled routes)"); - busStopMessage.setVisibility(View.VISIBLE); - busTimeList.setVisibility(View.GONE); - } else { - busTimeList.setVisibility(View.VISIBLE); - busStopMessage.setVisibility(View.GONE); - TimetableAdapter adapter; - if ((adapter = (TimetableAdapter) busTimeList.getAdapter()) != null) { - adapter.updateTimetable(visibleTimetable); + Log.i(TAG, "stops " + busStops); + + if (busStops.size() == 1) { + Intent i = new Intent(this, BusStopActivity.class); + BusStop stop = (BusStop) busStops.iterator().next(); + if (stop == null) { + Log.e(TAG, "stop == null"); + } + if (stop.id == null) { + Log.e(TAG, "stop.id == null"); + } + i.putExtra("busStopID", stop.id); + i.putExtra("busStopName", stop.description); + startActivity(i); + } else { + showDialog(POI_DIALOG_ID); + if (busDialog == null) { + Log.e(TAG, "Very wierd, just tried to launch the favourite's dialog, but its null?"); + return false; + } + + busDialog.setMessage(""); + busDialog.setItems(busStops); + busDialog.setTitle("Choose Bus Stop"); + + Log.i(TAG, "Showing dialog"); + } + + } else if (item.getItemId() == R.id.menu_refresh_stop) { + if (mHandler != null) { // BusTimes are enabled + mHandler.removeCallbacks(refreshData); + timetableTask.cancel(true); + Log.i(TAG, "Stoping refreshing timetable data"); + + mHandler.post(refreshData); + } else { + // TODO: Toast here... + } } else { - adapter = new TimetableAdapter(this, visibleTimetable); - busTimeList.setAdapter(adapter); + Log.e(TAG, "No known menu option selected"); + return super.onOptionsItemSelected(item); } - busTimeContentLayout.setGravity(Gravity.TOP); - } + return true; } - } - - @Override - protected Dialog onCreateDialog(int id) { - switch (id) { - case POI_DIALOG_ID: - busDialog = new POIDialog(instance); - busDialog.setOnItemClickListener(this); - return busDialog; + + private void displayTimetable(Timetable timetable) { + visibleTimetable = (Timetable) timetable.clone(); + + Log.i(TAG, "It contains " + visibleTimetable.size() + " stops"); + + if (timetable.size() == 0) { + busStopMessage.setText("No Busses"); + busStopMessage.setVisibility(View.VISIBLE); + busTimeContentLayout.setGravity(Gravity.CENTER); + } else { + + for (Iterator stopIter = visibleTimetable.iterator(); stopIter.hasNext();) { + Stop stop = stopIter.next(); + Log.i(TAG, "Begin filtering, looking at " + stop + " with route " + stop.bus.route.code); + if (stop.bus.route.code.equals("U1")) { + if (!U1RouteRadioButton.isChecked()) { + stopIter.remove(); + } + } else if (stop.bus.route.code.equals("U1N")) { + if (!U1NRouteRadioButton.isChecked()) { + stopIter.remove(); + } + } else if (stop.bus.route.code.equals("U2")) { + if (!U2RouteRadioButton.isChecked()) { + stopIter.remove(); + } + } else if (stop.bus.route.code.equals("U6")) { + if (!U6RouteRadioButton.isChecked()) { + stopIter.remove(); + } + } else if (stop.bus.route.code.equals("U9")) { + if (!U9RouteRadioButton.isChecked()) { + stopIter.remove(); + } + } + } + + if (visibleTimetable.size() == 0) { + busTimeContentLayout.setGravity(Gravity.CENTER); + busStopMessage.setText("No Busses (With the current enabled routes)"); + busStopMessage.setVisibility(View.VISIBLE); + busTimeList.setVisibility(View.GONE); + } else { + busTimeList.setVisibility(View.VISIBLE); + busStopMessage.setVisibility(View.GONE); + TimetableAdapter adapter; + if ((adapter = (TimetableAdapter) busTimeList.getAdapter()) != null) { + adapter.updateTimetable(visibleTimetable); + } else { + adapter = new TimetableAdapter(this, visibleTimetable); + busTimeList.setAdapter(adapter); + } + busTimeContentLayout.setGravity(Gravity.TOP); + } + } } - return null; - } - - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - Log.i(TAG, "OnItemClick pos " + position + " id " + id); - - String poiId = busDialog.adapter.getItemStringId(position); - - Log.i(TAG, "POI " + poiId + " selected"); - - Intent i = new Intent(this, BusStopActivity.class); - try { - busStop = busStopDao.queryForId(poiId); - - if (busStop == null) { - Log.e(TAG, "stop == null"); - } - if (busStop.id == null) { - Log.e(TAG, "stop.id == null"); - } - i.putExtra("busStopID", busStop.id); - i.putExtra("busStopName", busStop.description); - startActivity(i); - } catch (SQLException e) { - e.printStackTrace(); + + @Override + protected Dialog onCreateDialog(int id) { + switch (id) { + case POI_DIALOG_ID: + busDialog = new POIDialog(instance); + busDialog.setOnItemClickListener(this); + return busDialog; + } + return null; } - } + public void onItemClick(AdapterView parent, View view, int position, long id) { + Log.i(TAG, "OnItemClick pos " + position + " id " + id); + + String poiId = busDialog.adapter.getItemStringId(position); + + Log.i(TAG, "POI " + poiId + " selected"); + + Intent i = new Intent(this, BusStopActivity.class); + try { + busStop = busStopDao.queryForId(poiId); + + if (busStop == null) { + Log.e(TAG, "stop == null"); + } + if (busStop.id == null) { + Log.e(TAG, "stop.id == null"); + } + i.putExtra("busStopID", busStop.id); + i.putExtra("busStopName", busStop.description); + startActivity(i); + } catch (SQLException e) { + e.printStackTrace(); + } + + } } diff --git a/src/net/cbaines/suma/StopView.java b/src/net/cbaines/suma/StopView.java index 764072e..ce17721 100644 --- a/src/net/cbaines/suma/StopView.java +++ b/src/net/cbaines/suma/StopView.java @@ -38,133 +38,131 @@ import com.j256.ormlite.dao.Dao; public class StopView extends LinearLayout implements OnClickListener, OnLongClickListener { - // private final ImageView icon; + // private final ImageView icon; - // private static final String TAG = "StopView"; + // private static final String TAG = "StopView"; - private final TextView name; - private final TextView time; - private String onClickMessage = ""; - private final BusStopActivity context; + private final TextView name; + private final TextView time; + private String onClickMessage = ""; + private final BusStopActivity context; - private Stop stop; + private Stop stop; - public StopView(BusStopActivity context, Stop stop) { - super(context); + public StopView(BusStopActivity context, Stop stop) { + super(context); - this.context = context; + this.context = context; - this.setOrientation(HORIZONTAL); + this.setOrientation(HORIZONTAL); - name = new TextView(context); - name.setTextSize(22f); + name = new TextView(context); + name.setTextSize(22f); - time = new TextView(context); - time.setTextSize(22f); - time.setGravity(Gravity.RIGHT); + time = new TextView(context); + time.setTextSize(22f); + time.setGravity(Gravity.RIGHT); - setStop(stop); + setStop(stop); - addView(name, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); - addView(time, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); - } - - public void setStop(Stop stop) { - - // Log.i(TAG, "Time of arival " + stop.arivalTime); - - this.stop = stop; - - name.setText(stop.bus.getName()); - time.setText(stop.getTimeToArival()); - - DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class); - - try { - Dao busDao = helper.getBusDao(); - - busDao.refresh(stop.bus); - - if (stop.bus.id != null) { - if (stop.live) { - onClickMessage = "Bus " + stop.bus.toString() + " at " - + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); - } else { - onClickMessage = "Timetabled bus " + stop.bus.toString() + " at " - + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); - } - } else { - if (stop.live) { - onClickMessage = "Unidentified bus (" + stop.bus.getName() + ") at " - + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); - } else { - onClickMessage = "Timetabled bus (" + stop.bus.getName() + ") at " - + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); - } - } - } catch (SQLException e) { - e.printStackTrace(); + addView(name, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); + addView(time, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); } - this.setOnClickListener(this); - this.setOnLongClickListener(this); - } + public void setStop(Stop stop) { + + // Log.i(TAG, "Time of arival " + stop.arivalTime); + + this.stop = stop; + + name.setText(stop.bus.getName()); + time.setText(stop.getTimeToArival()); + + DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class); + + try { + Dao busDao = helper.getBusDao(); + + busDao.refresh(stop.bus); + + if (stop.bus.id != null) { + if (stop.live) { + onClickMessage = "Bus " + stop.bus.toString() + " at " + + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); + } else { + onClickMessage = "Timetabled bus " + stop.bus.toString() + " at " + + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); + } + } else { + if (stop.live) { + onClickMessage = "Unidentified bus (" + stop.bus.getName() + ") at " + + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); + } else { + onClickMessage = "Timetabled bus (" + stop.bus.getName() + ") at " + + DateFormat.getTimeInstance(DateFormat.SHORT).format(stop.arivalTime); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } - public void onClick(View v) { - if (context.activityToast == null) { - context.activityToast = Toast.makeText(context, onClickMessage, Toast.LENGTH_SHORT); - } else { - context.activityToast.setText(onClickMessage); - context.activityToast.setDuration(Toast.LENGTH_SHORT); + this.setOnClickListener(this); + this.setOnLongClickListener(this); } - context.activityToast.show(); - - } - - @Override - public boolean onLongClick(View v) { - DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class); - - try { - Dao busDao = helper.getBusDao(); - Dao busRouteDao = helper.getBusRouteDao(); - - 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); - - if (stop.bus.id != null && stop.bus.route.uniLink) { - Intent i = new Intent(context, BusActivity.class); - i.putExtra("busID", stop.bus.id); - i.putExtra("busStopID", stop.busStop.id); - ((Activity) context).startActivityForResult(i, 0); - } else { - if (!stop.bus.route.uniLink) { - if (context.activityToast == null) { - context.activityToast = Toast.makeText(context, - "Bus schedules only avalible for Uni-Link buses", Toast.LENGTH_SHORT); - } else { - context.activityToast.setText("Bus schedules only avalible for Uni-Link buses"); - context.activityToast.setDuration(Toast.LENGTH_SHORT); - } - context.activityToast.show(); + + public void onClick(View v) { + if (context.activityToast == null) { + context.activityToast = Toast.makeText(context, onClickMessage, Toast.LENGTH_SHORT); } else { - if (context.activityToast == null) { - context.activityToast = Toast.makeText(context, - "Bus schedules not avalible for unidentified buses", Toast.LENGTH_SHORT); - } else { - context.activityToast.setText("Bus schedules not avalible for unidentified buses"); + context.activityToast.setText(onClickMessage); context.activityToast.setDuration(Toast.LENGTH_SHORT); - } - context.activityToast.show(); } - } + context.activityToast.show(); + + } - } catch (SQLException e) { - e.printStackTrace(); + public boolean onLongClick(View v) { + DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class); + + try { + Dao busDao = helper.getBusDao(); + Dao busRouteDao = helper.getBusRouteDao(); + + 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); + + if (stop.bus.id != null && stop.bus.route.uniLink) { + Intent i = new Intent(context, BusActivity.class); + i.putExtra("busID", stop.bus.id); + i.putExtra("busStopID", stop.busStop.id); + ((Activity) context).startActivityForResult(i, 0); + } else { + if (!stop.bus.route.uniLink) { + if (context.activityToast == null) { + context.activityToast = Toast.makeText(context, "Bus schedules only avalible for Uni-Link buses", + Toast.LENGTH_SHORT); + } else { + context.activityToast.setText("Bus schedules only avalible for Uni-Link buses"); + context.activityToast.setDuration(Toast.LENGTH_SHORT); + } + context.activityToast.show(); + } else { + if (context.activityToast == null) { + context.activityToast = Toast.makeText(context, "Bus schedules not avalible for unidentified buses", + Toast.LENGTH_SHORT); + } else { + context.activityToast.setText("Bus schedules not avalible for unidentified buses"); + context.activityToast.setDuration(Toast.LENGTH_SHORT); + } + context.activityToast.show(); + } + } + + } catch (SQLException e) { + e.printStackTrace(); + } + return true; } - return true; - } } -- cgit v1.2.3 From f58d7d1fc227ed7de50ef5d48a49ff6709f3197b Mon Sep 17 00:00:00 2001 From: Christopher Baines Date: Wed, 29 Feb 2012 16:31:18 +0000 Subject: Fix the bus stop movement, havent fully tested this yet as the live bus data is not working... --- gen/net/cbaines/suma/R.java | Bin 13490 -> 13490 bytes res/layout/bus_stop_activity.xml | 14 ++++++------- src/net/cbaines/suma/BusStopActivity.java | 33 ++++++++++++------------------ 3 files changed, 20 insertions(+), 27 deletions(-) diff --git a/gen/net/cbaines/suma/R.java b/gen/net/cbaines/suma/R.java index f7f3034..b56502e 100644 Binary files a/gen/net/cbaines/suma/R.java and b/gen/net/cbaines/suma/R.java differ diff --git a/res/layout/bus_stop_activity.xml b/res/layout/bus_stop_activity.xml index 3f4dc98..7875852 100644 --- a/res/layout/bus_stop_activity.xml +++ b/res/layout/bus_stop_activity.xml @@ -107,13 +107,6 @@ android:gravity="center" android:orientation="vertical" > - - + + impleme private CheckBox U9RouteRadioButton; private static final int POI_DIALOG_ID = 0; - private POIDialog busDialog; + private POIDialog busStopDialog; private HashSet routes = new HashSet(); @@ -397,15 +397,9 @@ public class BusStopActivity extends OrmLiteBaseActivity impleme if (busStops.size() == 1) { - BusStop stop = (BusStop) busStops.iterator().next(); - if (stop == null) { - Log.e(TAG, "stop == null"); - } - if (stop.id == null) { - Log.e(TAG, "stop.id == null"); - } + BusStop nextBusStop = (BusStop) busStops.iterator().next(); - Uri uri = Uri.parse("http://id.southampton.ac.uk/bus-stop/" + busStop.id); + Uri uri = Uri.parse("http://id.southampton.ac.uk/bus-stop/" + nextBusStop.id); Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath()); @@ -414,14 +408,14 @@ public class BusStopActivity extends OrmLiteBaseActivity impleme } else { showDialog(POI_DIALOG_ID); - if (busDialog == null) { + if (busStopDialog == null) { Log.e(TAG, "Very wierd, just tried to launch the favourite's dialog, but its null?"); return false; } - busDialog.setMessage(""); - busDialog.setItems(busStops); - busDialog.setTitle("Choose Bus Stop"); + busStopDialog.setMessage(""); + busStopDialog.setItems(busStops); + busStopDialog.setTitle("Choose Bus Stop"); Log.i(TAG, "Showing dialog"); } @@ -504,9 +498,9 @@ public class BusStopActivity extends OrmLiteBaseActivity impleme protected Dialog onCreateDialog(int id) { switch (id) { case POI_DIALOG_ID: - busDialog = new POIDialog(instance); - busDialog.setOnItemClickListener(this); - return busDialog; + busStopDialog = new POIDialog(instance); + busStopDialog.setOnItemClickListener(this); + return busStopDialog; } return null; } @@ -514,16 +508,15 @@ public class BusStopActivity extends OrmLiteBaseActivity impleme public void onItemClick(AdapterView parent, View view, int position, long id) { Log.i(TAG, "OnItemClick pos " + position + " id " + id); - String busId = busDialog.adapter.getItemStringId(position); + String busStopID = busStopDialog.adapter.getItemStringId(position); - Log.i(TAG, "Bus " + busId + " selected"); + Log.i(TAG, "Bus " + busStopID + " selected"); - Uri uri = Uri.parse("http://id.southampton.ac.uk/bus/" + busId); + Uri uri = Uri.parse("http://id.southampton.ac.uk/bus-stop/" + busStopID); Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath()); Intent busStopIntent = new Intent(Intent.ACTION_VIEW, uri); - busStopIntent.putExtra("busStopID", busStop.id); startActivity(busStopIntent); } -- cgit v1.2.3 From 5dbed3a0fe85f0ed2a2763be0912f109bdee6c20 Mon Sep 17 00:00:00 2001 From: Christopher Baines Date: Tue, 6 Mar 2012 11:42:24 +0000 Subject: New Search stuff. --- AndroidManifest.xml | 14 ++ gen/net/cbaines/suma/R.java | Bin 14562 -> 14686 bytes res/values/strings.xml | 1 + res/xml/searchable.xml | 6 + src/net/cbaines/suma/FindActivity.java | 13 ++ src/net/cbaines/suma/MapActivity.java | 169 ++++++++++++---------- src/net/cbaines/suma/MapContentProvider.java | 201 +++++++++++++++++++++++++++ 7 files changed, 334 insertions(+), 70 deletions(-) create mode 100644 res/xml/searchable.xml create mode 100644 src/net/cbaines/suma/MapContentProvider.java diff --git a/AndroidManifest.xml b/AndroidManifest.xml index c9efb4a..a9bccd3 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -50,8 +50,22 @@ + + + + + + + + + + diff --git a/gen/net/cbaines/suma/R.java b/gen/net/cbaines/suma/R.java index 49cba3e..e1704a7 100644 Binary files a/gen/net/cbaines/suma/R.java and b/gen/net/cbaines/suma/R.java differ diff --git a/res/values/strings.xml b/res/values/strings.xml index e17ab11..6126937 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -1,6 +1,7 @@ + Search Find Preferences View diff --git a/res/xml/searchable.xml b/res/xml/searchable.xml new file mode 100644 index 0000000..e4602a5 --- /dev/null +++ b/res/xml/searchable.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/src/net/cbaines/suma/FindActivity.java b/src/net/cbaines/suma/FindActivity.java index 669249c..5a07807 100644 --- a/src/net/cbaines/suma/FindActivity.java +++ b/src/net/cbaines/suma/FindActivity.java @@ -27,6 +27,7 @@ import java.util.List; import org.osmdroid.util.GeoPoint; +import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.location.Location; @@ -57,6 +58,9 @@ public class FindActivity extends OrmLiteBaseActivity implements final static String TAG = "FindActivity"; + public static final String ORIGIN = "o"; + public static final int MAP_ACTIVITY = 0; + private EditText searchBar; private ListView listItems; private ProgressBar progBar; @@ -243,9 +247,18 @@ public class FindActivity extends OrmLiteBaseActivity implements super.onCreate(savedInstanceState); setContentView(R.layout.find_activity); + Log.i(TAG, "FindActivity started"); + searchBar = (EditText) findViewById(R.id.searchBar); searchBar.addTextChangedListener(this); + Intent intent = getIntent(); + if (Intent.ACTION_SEARCH.equals(intent.getAction())) { + String query = intent.getStringExtra(SearchManager.QUERY); + Log.i(TAG, "Searching for " + query); + searchBar.setText(query); + } + listItems = (ListView) findViewById(R.id.findListItems); listItems.setOnItemClickListener(this); listItems.setOnItemLongClickListener(this); diff --git a/src/net/cbaines/suma/MapActivity.java b/src/net/cbaines/suma/MapActivity.java index 01e8ec6..6c4664e 100644 --- a/src/net/cbaines/suma/MapActivity.java +++ b/src/net/cbaines/suma/MapActivity.java @@ -73,8 +73,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants 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 + * 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; @@ -124,10 +124,11 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants private static final int NON_UNI_LINK_BUS_STOP_OVERLAY_RANK = 4; // -- Site Overlays - static final String[] SITE_NAMES = { "Highfield Campus", "Boldrewood Campus", "Avenue Campus", "Winchester School of Art", - "The University of Southampton Science Park", "National Oceanography Centre Campus", "Boat House", - "Southampton General Hospital", "Royal South Hants Hospital", "Belgrave Industrial Site", "Highfield Hall", - "Glen Eyre Hall", "South Hill Hall", "Chamberlain Hall", "Hartley Grove", "Bencraft Hall", "Connaught Hall", + static final String[] SITE_NAMES = { "Highfield Campus", "Boldrewood Campus", "Avenue Campus", + "Winchester School of Art", "The University of Southampton Science Park", + "National Oceanography Centre Campus", "Boat House", "Southampton General Hospital", + "Royal South Hants Hospital", "Belgrave Industrial Site", "Highfield Hall", "Glen Eyre Hall", + "South Hill Hall", "Chamberlain Hall", "Hartley Grove", "Bencraft Hall", "Connaught Hall", "Montefiore Hall", "Stoneham Hall", "Erasmus Park" }; private static final String SITE_OVERLAYS = "siteOverlays:"; @@ -165,8 +166,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants // Uni-Link routes static final String[] UNI_LINK_ROUTES = { "U1", "U1N", "U2", "U6", "U9" }; - static final String[] PREFERENCES_GROUPS = { BUS_STOP_OVERLAYS, BUS_ROUTE_OVERLAYS, BUILDING_OVERLAYS, SITE_OVERLAYS, - OTHER_OVERLAYS }; + static final String[] PREFERENCES_GROUPS = { BUS_STOP_OVERLAYS, BUS_ROUTE_OVERLAYS, BUILDING_OVERLAYS, + SITE_OVERLAYS, OTHER_OVERLAYS }; static final String[][] PREFERENCES_CHILDREN = { UNI_LINK_ROUTES, UNI_LINK_ROUTES, BUILDING_TYPES, SITE_NAMES, OTHER_OVERLAY_NAMES }; @@ -198,8 +199,10 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants pastOverlays = (HashMap) getLastNonConfigurationInstance(); /* - * SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); This code in the following - * constructor causes problems in some emulators, disable sensors to fix. + * SensorManager mSensorManager = (SensorManager) + * getSystemService(Context.SENSOR_SERVICE); This code in the following + * constructor causes problems in some emulators, disable sensors to + * fix. */ Log.i(TAG, "Starting creating myLocationOverlay"); myLocationOverlay = new MyLocationOverlay(instance, mapView); @@ -320,6 +323,14 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants return overlays; } + @Override + public boolean onSearchRequested() { + Bundle appData = new Bundle(); + appData.putInt(FindActivity.ORIGIN, FindActivity.MAP_ACTIVITY); + startSearch(null, false, appData, false); + return true; + } + public void run() { Log.i(TAG, "Begining loading database " + (System.currentTimeMillis() - startTime)); @@ -513,7 +524,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants if (scaleBarOverlay != null) { Log.v(TAG, "ScaleBarOverlay is already created"); } else { - if (pastOverlays != null && (scaleBarOverlay = (ScaleBarOverlay) pastOverlays.get(SCALE_BAR_OVERLAY)) != null) { + if (pastOverlays != null + && (scaleBarOverlay = (ScaleBarOverlay) pastOverlays.get(SCALE_BAR_OVERLAY)) != null) { Log.i(TAG, "Finished restoring utility overlays " + (System.currentTimeMillis() - startTime)); } else { scaleBarOverlay = new ScaleBarOverlay(instance); @@ -542,7 +554,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants private void showRouteOverlay(final BusRoute route) { new Thread(new Runnable() { public void run() { - Log.i(TAG, "Begining showing route " + route.code + " overlay at " + (System.currentTimeMillis() - startTime)); + Log.i(TAG, "Begining showing route " + route.code + " overlay at " + + (System.currentTimeMillis() - startTime)); final SharedPreferences activityPrefs = getPreferences(0); final OverlayRankComparator comparator = new OverlayRankComparator(getPreferences(0)); @@ -567,8 +580,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants // TODO Is this a route like U1N or, something else, // this hack works somewhat for now? - PathOverlay routeOverlayU1E = DataManager.getRoutePath(getResources().openRawResource(R.raw.u1e), - colour, mResourceProxy); + PathOverlay routeOverlayU1E = DataManager.getRoutePath( + getResources().openRawResource(R.raw.u1e), colour, mResourceProxy); routeOverlayU1E.getPaint().setAntiAlias(true); routeOverlayU1E.getPaint().setAlpha(145); routeOverlayU1E.getPaint().setStrokeWidth(12); @@ -623,7 +636,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants mapView.postInvalidate(); - Log.i(TAG, "Finished showing route " + route.code + " overlay at " + (System.currentTimeMillis() - startTime)); + Log.i(TAG, "Finished showing route " + route.code + " overlay at " + + (System.currentTimeMillis() - startTime)); } }).start(); } @@ -632,7 +646,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants new Thread(new Runnable() { public void run() { - Log.i(TAG, "Begining showing site " + site.name + " overlay at " + (System.currentTimeMillis() - startTime)); + Log.i(TAG, "Begining showing site " + site.name + " overlay at " + + (System.currentTimeMillis() - startTime)); final SharedPreferences activityPrefs = getPreferences(0); final OverlayRankComparator comparator = new OverlayRankComparator(getPreferences(0)); @@ -641,7 +656,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants if ((siteOverlay = siteOverlays.get(site)) != null) { } else { - if (pastOverlays != null && (siteOverlay = (PathOverlay) pastOverlays.get(SITE_OVERLAYS + site.name)) != null) { + if (pastOverlays != null + && (siteOverlay = (PathOverlay) pastOverlays.get(SITE_OVERLAYS + site.name)) != null) { Log.i(TAG, "Restored " + site.name + " site overlay"); } else { @@ -667,11 +683,13 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants } } - siteOverlay.setEnabled(activityPrefs.getBoolean(SITE_OVERLAYS + site.name, SITE_OVERLAYS_ENABLED_BY_DEFAULT)); + siteOverlay.setEnabled(activityPrefs.getBoolean(SITE_OVERLAYS + site.name, + SITE_OVERLAYS_ENABLED_BY_DEFAULT)); mapView.postInvalidate(); - Log.i(TAG, "Finished showing site " + site.name + " overlay at " + (System.currentTimeMillis() - startTime)); + Log.i(TAG, "Finished showing site " + site.name + " overlay at " + + (System.currentTimeMillis() - startTime)); } }).start(); } @@ -688,8 +706,10 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants } else { if (pastOverlays != null - && (residentialBuildingOverlay = (BuildingNumOverlay) pastOverlays.get(RESIDENTIAL_BUILDING_OVERLAY)) != null) { - nonResidentialBuildingOverlay = (BuildingNumOverlay) pastOverlays.get(NON_RESIDENTIAL_BUILDING_OVERLAY); + && (residentialBuildingOverlay = (BuildingNumOverlay) pastOverlays + .get(RESIDENTIAL_BUILDING_OVERLAY)) != null) { + nonResidentialBuildingOverlay = (BuildingNumOverlay) pastOverlays + .get(NON_RESIDENTIAL_BUILDING_OVERLAY); Log.i(TAG, "Restored building overlays"); } else { @@ -704,7 +724,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants buildingDao = getHelper().getBuildingDao(); - final SharedPreferences favouritesPrefs = getSharedPreferences(FAVOURITES_PREFERENCES, MODE_PRIVATE); + final SharedPreferences favouritesPrefs = getSharedPreferences(FAVOURITES_PREFERENCES, + MODE_PRIVATE); for (Building building : buildingDao) { if (building.residential == true) { @@ -742,8 +763,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants } } - residentialBuildingOverlay.setEnabled(activityPrefs.getBoolean(BUILDING_OVERLAYS + RESIDENTIAL_BUILDING_OVERLAY, - RESIDENTIAL_BUILDING_OVERLAY_ENABLED_BY_DEFAULT)); + residentialBuildingOverlay.setEnabled(activityPrefs.getBoolean(BUILDING_OVERLAYS + + RESIDENTIAL_BUILDING_OVERLAY, RESIDENTIAL_BUILDING_OVERLAY_ENABLED_BY_DEFAULT)); nonResidentialBuildingOverlay.setEnabled(activityPrefs.getBoolean(BUILDING_OVERLAYS + NON_RESIDENTIAL_BUILDING_OVERLAY, NON_RESIDENTIAL_BUILDING_OVERLAY_ENABLED_BY_DEFAULT)); @@ -763,11 +784,16 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants final OverlayRankComparator comparator = new OverlayRankComparator(getPreferences(0)); if (uniLinkBusStopOverlay != null) { - if (!activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) - && !activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1N", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) - && !activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U2", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) - && !activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U6", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) - && !activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U9", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)) { + if (!activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) + && !activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1N", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) + && !activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U2", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) + && !activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U6", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) + && !activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U9", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)) { Log.i(TAG, "Uni-Link bus stop overlay not needed"); overlays.remove(UNI_LINK_BUS_STOP_OVERLAY); @@ -778,25 +804,31 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants uniLinkBusStopOverlay = null; } else { - uniLinkBusStopOverlay.setRoutes(0, - activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); - uniLinkBusStopOverlay.setRoutes(1, - activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1N", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); - uniLinkBusStopOverlay.setRoutes(2, - activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U2", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); - uniLinkBusStopOverlay.setRoutes(3, - activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U6", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); - uniLinkBusStopOverlay.setRoutes(4, - activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U9", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); + uniLinkBusStopOverlay.setRoutes(0, activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); + uniLinkBusStopOverlay.setRoutes(1, activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1N", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); + uniLinkBusStopOverlay.setRoutes(2, activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U2", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); + uniLinkBusStopOverlay.setRoutes(3, activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U6", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); + uniLinkBusStopOverlay.setRoutes(4, activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U9", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); } } else { - if (activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) - || activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1N", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) - || activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U2", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) - || activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U6", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) - || activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U9", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)) { + if (activityPrefs + .getBoolean(BUS_STOP_OVERLAYS + "U1", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) + || activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1N", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) + || activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U2", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) + || activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U6", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT) + || activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U9", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)) { if (pastOverlays != null - && (uniLinkBusStopOverlay = (BusStopOverlay) pastOverlays.get(UNI_LINK_BUS_STOP_OVERLAY)) != null) { + && (uniLinkBusStopOverlay = (BusStopOverlay) pastOverlays + .get(UNI_LINK_BUS_STOP_OVERLAY)) != null) { Log.i(TAG, "Restored Uni-Link bus stop overlay"); } else { @@ -814,16 +846,16 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants } } - uniLinkBusStopOverlay.setRoutes(0, - activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); - uniLinkBusStopOverlay.setRoutes(1, - activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1N", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); - uniLinkBusStopOverlay.setRoutes(2, - activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U2", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); - uniLinkBusStopOverlay.setRoutes(3, - activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U6", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); - uniLinkBusStopOverlay.setRoutes(4, - activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U9", UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); + uniLinkBusStopOverlay.setRoutes(0, activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); + uniLinkBusStopOverlay.setRoutes(1, activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U1N", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); + uniLinkBusStopOverlay.setRoutes(2, activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U2", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); + uniLinkBusStopOverlay.setRoutes(3, activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U6", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); + uniLinkBusStopOverlay.setRoutes(4, activityPrefs.getBoolean(BUS_STOP_OVERLAYS + "U9", + UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)); overlays.put(UNI_LINK_BUS_STOP_OVERLAY, uniLinkBusStopOverlay); @@ -846,7 +878,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants private void showNonUniLinkBusStopOverlay() { new Thread(new Runnable() { public void run() { - Log.i(TAG, "Begining showing non uni link bus stop overlays at " + (System.currentTimeMillis() - startTime)); + Log.i(TAG, "Begining showing non uni link bus stop overlays at " + + (System.currentTimeMillis() - startTime)); // final SharedPreferences activityPrefs = getPreferences(0); final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(instance); @@ -863,12 +896,14 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants } else if (sharedPrefs.getBoolean(NON_UNI_LINK_BUS_STOPS_OVERLAY, NON_UNI_LINK_BUS_STOP_OVERLAY_ENABLED_BY_DEFAULT)) { if (pastOverlays != null - && (nonUniLinkBusStopOverlay = (BusStopOverlay) pastOverlays.get(NON_UNI_LINK_BUS_STOPS_OVERLAY)) != null) { + && (nonUniLinkBusStopOverlay = (BusStopOverlay) pastOverlays + .get(NON_UNI_LINK_BUS_STOPS_OVERLAY)) != null) { Log.i(TAG, "Restored non Uni-Link bus stop overlays"); } else { try { List busStops; - Log.v(TAG, "Begin fetching non Uni-Link BusStops at " + (System.currentTimeMillis() - startTime)); + Log.v(TAG, "Begin fetching non Uni-Link BusStops at " + + (System.currentTimeMillis() - startTime)); busStops = getHelper().getBusStopDao().queryForEq(BusStop.UNI_LINK_FIELD_NAME, false); @@ -898,7 +933,8 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants mapView.postInvalidate(); - Log.i(TAG, "Finished showing non Uni-Link bus stop overlays at " + (System.currentTimeMillis() - startTime)); + Log.i(TAG, "Finished showing non Uni-Link bus stop overlays at " + + (System.currentTimeMillis() - startTime)); } }).start(); } @@ -915,8 +951,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); @@ -950,8 +985,9 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants }; AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage("GPS is not enabled, do you wish to enable it?").setPositiveButton("Yes", dialogClickListener) - .setNegativeButton("No", dialogClickListener).show(); + builder.setMessage("GPS is not enabled, do you wish to enable it?") + .setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener) + .show(); } return true; @@ -1015,13 +1051,6 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants } } - @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) { diff --git a/src/net/cbaines/suma/MapContentProvider.java b/src/net/cbaines/suma/MapContentProvider.java new file mode 100644 index 0000000..46986ab --- /dev/null +++ b/src/net/cbaines/suma/MapContentProvider.java @@ -0,0 +1,201 @@ +/* + * 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 com.j256.ormlite.android.apptools.OpenHelperManager; + +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.net.Uri; +import android.provider.BaseColumns; + +/** + * 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 WORDS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + + "/vnd.example.android.searchabledict"; + public static final String DEFINITION_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + + "/vnd.example.android.searchabledict"; + + private DatabaseHelper helper; + + // UriMatcher stuff + private static final int SEARCH_WORDS = 0; + private static final int GET_WORD = 1; + private static final int SEARCH_SUGGEST = 2; + private static final int REFRESH_SHORTCUT = 3; + 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, "dictionary", SEARCH_WORDS); + matcher.addURI(AUTHORITY, "dictionary/#", GET_WORD); + // 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); + } + return getSuggestions(selectionArgs[0]); + case SEARCH_WORDS: + if (selectionArgs == null) { + throw new IllegalArgumentException("selectionArgs must be provided for the Uri: " + uri); + } + return search(selectionArgs[0]); + case GET_WORD: + return getWord(uri); + case REFRESH_SHORTCUT: + return refreshShortcut(uri); + default: + throw new IllegalArgumentException("Unknown Uri: " + uri); + } + } + + private Cursor getSuggestions(String query) { + query = query.toLowerCase(); + String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, + DictionaryDatabase.KEY_DEFINITION, + /* + * SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, (only if you want + * to refresh shortcuts) + */ + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID }; + + return mDictionary.getWordMatches(query, columns); + } + + private Cursor search(String query) { + query = query.toLowerCase(); + String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, + DictionaryDatabase.KEY_DEFINITION }; + + return mDictionary.getWordMatches(query, columns); + } + + private Cursor getWord(Uri uri) { + String rowId = uri.getLastPathSegment(); + String[] columns = new String[] { DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION }; + + return mDictionary.getWord(rowId, columns); + } + + private Cursor refreshShortcut(Uri uri) { + /* + * 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 rowId = uri.getLastPathSegment(); + String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, + DictionaryDatabase.KEY_DEFINITION, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID }; + + return mDictionary.getWord(rowId, columns); + } + + /** + * 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_WORDS: + return WORDS_MIME_TYPE; + case GET_WORD: + return DEFINITION_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(); + } + +} -- cgit v1.2.3 From a722eac92e7154563bd144ad91b092d23dae8f2a Mon Sep 17 00:00:00 2001 From: Christopher Baines Date: Tue, 6 Mar 2012 14:46:01 +0000 Subject: Basic searchable stuff. --- AndroidManifest.xml | 5 + res/xml/searchable.xml | 9 +- src/net/cbaines/suma/Bus.java | 10 +- src/net/cbaines/suma/BusStopSpecificStopView.java | 3 +- src/net/cbaines/suma/DataManager.java | 95 +++++++---- src/net/cbaines/suma/MapContentProvider.java | 194 ++++++++++++++++------ src/net/cbaines/suma/POI.java | 83 ++++----- 7 files changed, 267 insertions(+), 132 deletions(-) diff --git a/AndroidManifest.xml b/AndroidManifest.xml index a9bccd3..4dfff99 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -169,6 +169,11 @@ android:name=".PreferencesActivity" android:label="@string/preferences" > + + + \ No newline at end of file diff --git a/res/xml/searchable.xml b/res/xml/searchable.xml index e4602a5..7262b3d 100644 --- a/res/xml/searchable.xml +++ b/res/xml/searchable.xml @@ -1,6 +1,13 @@ + android:includeInGlobalSearch="true" + android:label="@string/app_name" + android:searchSettingsDescription="@string/map_activity_search_hint" + android:searchSuggestAuthority="net.cbaines.suma.provider" + android:searchSuggestIntentAction="android.intent.action.VIEW" + android:searchSuggestIntentData="content://net.cbaines.suma.provider/building" + android:searchSuggestSelection=" ?" + android:searchSuggestThreshold="1" > \ No newline at end of file diff --git a/src/net/cbaines/suma/Bus.java b/src/net/cbaines/suma/Bus.java index 865384f..34e20a6 100644 --- a/src/net/cbaines/suma/Bus.java +++ b/src/net/cbaines/suma/Bus.java @@ -35,9 +35,6 @@ public class Bus { final static String ROUTE_FIELD_NAME = "route"; final static String DIRECTION_FIELD_NAME = "direction"; - @DatabaseField(generatedId = true) - int gid; - /** * The identification number of the bus. */ @@ -115,7 +112,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 +125,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/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 ab1f3a7..fd47360 100644 --- a/src/net/cbaines/suma/DataManager.java +++ b/src/net/cbaines/suma/DataManager.java @@ -137,9 +137,13 @@ public class DataManager { /* * Polygon poly = buildingPolys.get(dataBits[1]); * - * if (poly != null) { bdg.outline = poly; // Log.i(TAG, "Adding building " + key + " " + - * bdg.point.getLatitudeE6() + " " + bdg.point.getLongitudeE6() + " " + poly); } else { // Log.i(TAG, - * "Adding building " + key + " " + bdg.point.getLatitudeE6() + " " + bdg.point.getLongitudeE6()); } + * if (poly != null) { bdg.outline = poly; // Log.i(TAG, + * "Adding building " + key + " " + + * bdg.point.getLatitudeE6() + " " + + * bdg.point.getLongitudeE6() + " " + poly); } else { // + * Log.i(TAG, "Adding building " + key + " " + + * bdg.point.getLatitudeE6() + " " + + * bdg.point.getLongitudeE6()); } */ // Log.i(TAG, "Creating building " + bdg.id + " " + bdg.name @@ -163,9 +167,13 @@ public class DataManager { /* * Polygon poly = buildingPolys.get(dataBits[1]); * - * if (poly != null) { bdg.outline = poly; // Log.i(TAG, "Adding building " + key + " " + - * bdg.point.getLatitudeE6() + " " + bdg.point.getLongitudeE6() + " " + poly); } else { // Log.i(TAG, - * "Adding building " + key + " " + bdg.point.getLatitudeE6() + " " + bdg.point.getLongitudeE6()); } + * if (poly != null) { bdg.outline = poly; // Log.i(TAG, + * "Adding building " + key + " " + + * bdg.point.getLatitudeE6() + " " + + * bdg.point.getLongitudeE6() + " " + poly); } else { // + * Log.i(TAG, "Adding building " + key + " " + + * bdg.point.getLatitudeE6() + " " + + * bdg.point.getLongitudeE6()); } */ // Log.i(TAG, "Creating building " + bdg.id + " " + bdg.name @@ -184,13 +192,17 @@ public class DataManager { } /* - * for (Iterator iter = buildingPoints.keySet().iterator(); iter.hasNext();) { String key = iter.next(); + * for (Iterator iter = buildingPoints.keySet().iterator(); + * iter.hasNext();) { String key = iter.next(); * - * Building bdg = new Building(key, buildingPoints.get(key), false); Polygon poly = buildingPolys.get(key); + * Building bdg = new Building(key, buildingPoints.get(key), false); + * Polygon poly = buildingPolys.get(key); * - * if (poly != null) { bdg.outline = poly; // Log.i(TAG, "Adding building " + key + " " + bdg.point.getLatitudeE6() + " " - * + bdg.point.getLongitudeE6() + " " + poly); } else { // Log.i(TAG, "Adding building " + key + " " + - * bdg.point.getLatitudeE6() + " " + bdg.point.getLongitudeE6()); } + * if (poly != null) { bdg.outline = poly; // Log.i(TAG, + * "Adding building " + key + " " + bdg.point.getLatitudeE6() + " " + + * bdg.point.getLongitudeE6() + " " + poly); } else { // Log.i(TAG, + * "Adding building " + key + " " + bdg.point.getLatitudeE6() + " " + + * bdg.point.getLongitudeE6()); } * * buildingDao.create(bdg); } */ @@ -227,18 +239,18 @@ public class DataManager { // Log.i(TAG, "Whole " + dataBits[3] + " First bit " + // quBitsLat[0] + " last bit " + quBitsLat[1]); - double lat = Double.valueOf(quBitsLat[0]) + Double.valueOf(quBitsLat[1].substring(0, quBitsLat[1].length() - 1)) - / 60d; + double lat = Double.valueOf(quBitsLat[0]) + + Double.valueOf(quBitsLat[1].substring(0, quBitsLat[1].length() - 1)) / 60d; // Log.i(TAG, "Whole " + dataBits[4] + " First bit " + // quBitsLng[0] + " last bit " + quBitsLng[1]); - double lng = Double.valueOf(quBitsLng[0]) + Double.valueOf(quBitsLng[1].substring(0, quBitsLng[1].length() - 1)) - / 60d; + double lng = Double.valueOf(quBitsLng[0]) + + Double.valueOf(quBitsLng[1].substring(0, quBitsLng[1].length() - 1)) / 60d; GeoPoint point = new GeoPoint((int) (lat * 1e6), (int) (lng * -1e6)); // Log.i(TAG, "Lat " + point.getLatitudeE6() + " lng " + // point.getLongitudeE6()); - busStopDao.create(new BusStop(dataBits[0].replace("\"", ""), dataBits[1].replace("\"", ""), dataBits[2].replace( - "\"", ""), point)); + busStopDao.create(new BusStop(dataBits[0].replace("\"", ""), dataBits[1].replace("\"", ""), dataBits[2] + .replace("\"", ""), point)); } @@ -359,26 +371,36 @@ public class DataManager { } /* - * for (Iterator busStopIter = busStopDao.iterator(); busStopIter.hasNext();) { BusStop stop = - * busStopIter.next(); // Log.i(TAG, "Looking at stop " + stop.id); + * for (Iterator busStopIter = busStopDao.iterator(); + * busStopIter.hasNext();) { BusStop stop = busStopIter.next(); // + * Log.i(TAG, "Looking at stop " + stop.id); * * - * QueryBuilder routeStopsQueryBuilder = routeStopsDao.queryBuilder(); + * QueryBuilder routeStopsQueryBuilder = + * routeStopsDao.queryBuilder(); * routeStopsQueryBuilder.where().eq(columnName, value) * - * DeleteBuilder deleteBuilder = busStopDao.deleteBuilder(); // only delete the rows where password is - * null deleteBuilder.where().in(RouteStops.STOP_ID_FIELD_NAME, objects) accountDao.delete(deleteBuilder.prepare()); + * DeleteBuilder deleteBuilder = + * busStopDao.deleteBuilder(); // only delete the rows where password is + * null deleteBuilder.where().in(RouteStops.STOP_ID_FIELD_NAME, objects) + * accountDao.delete(deleteBuilder.prepare()); * * - * QueryBuilder routeStopsQueryBuilder = routeStopsDao.queryBuilder(); - * routeStopsQueryBuilder.setCountOf(true); routeStopsQueryBuilder.where().eq(RouteStops.STOP_ID_FIELD_NAME, stop); + * QueryBuilder routeStopsQueryBuilder = + * routeStopsDao.queryBuilder(); + * routeStopsQueryBuilder.setCountOf(true); + * routeStopsQueryBuilder.where().eq(RouteStops.STOP_ID_FIELD_NAME, + * stop); * - * PreparedQuery routeStopsPreparedQuery = routeStopsQueryBuilder.prepare(); List routeStops = - * routeStopsDao.query(routeStopsPreparedQuery); // long num = routeStopsDao.query(routeStopsPreparedQuery).size(); // - * Log.i(TAG, "Number is " + num); + * PreparedQuery routeStopsPreparedQuery = + * routeStopsQueryBuilder.prepare(); List routeStops = + * routeStopsDao.query(routeStopsPreparedQuery); // long num = + * routeStopsDao.query(routeStopsPreparedQuery).size(); // Log.i(TAG, + * "Number is " + num); * - * stop.uniLink = false; for (RouteStops routeStop : routeStops) { if (routeStop.busRoute.uniLink) { stop.uniLink = true; - * } } busStopDao.update(stop); } + * stop.uniLink = false; for (RouteStops routeStop : routeStops) { if + * (routeStop.busRoute.uniLink) { stop.uniLink = true; } } + * busStopDao.update(stop); } */ Log.i(TAG, "Finished loading bus data"); @@ -438,8 +460,6 @@ public class DataManager { Dao routeStopsDao = null; if (routeStopsDao == null) routeStopsDao = helper.getRouteStopsDao(); - if (busDao == null) - busDao = helper.getBusDao(); if (busStopDao == null) busStopDao = helper.getBusStopDao(); @@ -554,9 +574,11 @@ public class DataManager { List routeStops = routeStopsDao.query(routeStopsPreparedQuery); if (routeStops.size() > 0) { - Log.i(TAG, "Found " + routeStops.size() + " stops matching the destStop " + destStop + " on route " + route.code); + 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); + Log.w(TAG, "Found " + routeStops.size() + " stops matching the destStop " + destStop + " on route " + + route.code); } } @@ -642,7 +664,8 @@ public class DataManager { if (route != null) { busRoutes.add(route); } else { - throw new RuntimeException("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); } } @@ -750,8 +773,8 @@ public class DataManager { continue; } - Log.v(TAG, "Found stop for a unidentified " + stop.bus.toString() + " at " + stop.busStop.id + " at " - + stop.arivalTime); + 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/MapContentProvider.java b/src/net/cbaines/suma/MapContentProvider.java index 46986ab..a2b42c3 100644 --- a/src/net/cbaines/suma/MapContentProvider.java +++ b/src/net/cbaines/suma/MapContentProvider.java @@ -16,7 +16,8 @@ package net.cbaines.suma; -import com.j256.ormlite.android.apptools.OpenHelperManager; +import java.sql.SQLException; +import java.util.List; import android.app.SearchManager; import android.content.ContentProvider; @@ -24,8 +25,17 @@ 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. @@ -34,21 +44,40 @@ 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"); + // 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 WORDS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE - + "/vnd.example.android.searchabledict"; - public static final String DEFINITION_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE - + "/vnd.example.android.searchabledict"; + 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_WORDS = 0; - private static final int GET_WORD = 1; - private static final int SEARCH_SUGGEST = 2; - private static final int REFRESH_SHORTCUT = 3; + private static final int SEARCH_BUILDINGS = 0; + private static final int GET_BUILDING = 1; + private static final int SEARCH_BUS_STOPS = 2; + private static final int GET_BUS_STOP = 3; + private static final int SEARCH_SITES = 4; + private static final int GET_SITE = 5; + private static final int SEARCH_BUSES = 6; + private static final int GET_BUS = 7; + private static final int SEARCH_SUGGEST = 8; + private static final int REFRESH_SHORTCUT = 9; private static final UriMatcher sURIMatcher = buildUriMatcher(); /** @@ -58,8 +87,15 @@ public class MapContentProvider extends ContentProvider { private static UriMatcher buildUriMatcher() { UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); // to get definitions... - matcher.addURI(AUTHORITY, "dictionary", SEARCH_WORDS); - matcher.addURI(AUTHORITY, "dictionary/#", GET_WORD); + 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); @@ -100,50 +136,94 @@ public class MapContentProvider extends ContentProvider { if (selectionArgs == null) { throw new IllegalArgumentException("selectionArgs must be provided for the Uri: " + uri); } - return getSuggestions(selectionArgs[0]); - case SEARCH_WORDS: + try { + return getSuggestions(selectionArgs[0]); + } catch (SQLException e1) { + e1.printStackTrace(); + } + case SEARCH_BUILDINGS: if (selectionArgs == null) { throw new IllegalArgumentException("selectionArgs must be provided for the Uri: " + uri); } - return search(selectionArgs[0]); - case GET_WORD: - return getWord(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: - return refreshShortcut(uri); + try { + return refreshShortcut(uri); + } catch (SQLException e) { + e.printStackTrace(); + } default: throw new IllegalArgumentException("Unknown Uri: " + uri); } } - private Cursor getSuggestions(String query) { - query = query.toLowerCase(); - String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, - DictionaryDatabase.KEY_DEFINITION, - /* - * SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, (only if you want - * to refresh shortcuts) - */ - SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID }; - - return mDictionary.getWordMatches(query, columns); + private Cursor getSuggestions(String query) throws SQLException { + Log.v(TAG, "Got query for " + query); + + Dao buildingDao = helper.getBuildingDao(); + + QueryBuilder qb = buildingDao.queryBuilder(); + qb.where().like(Building.ID_FIELD_NAME, "%" + query + "%").or() + .like(Building.NAME_FIELD_NAME, "%" + query + "%"); + PreparedQuery preparedQuery = qb.prepare(); + + List buildings = buildingDao.query(preparedQuery); + Log.v(TAG, "Returning " + buildings.size() + " buildings"); + + String[] columnNames = { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1 }; + + MatrixCursor cursor = new MatrixCursor(columnNames, buildings.size()); + + int id = 0; + for (Building building : buildings) { + Log.v(TAG, "Building " + id + ", " + building.name); + Object[] values = { id++, building.name }; + cursor.addRow(values); + } + + return cursor; } - private Cursor search(String query) { - query = query.toLowerCase(); - String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, - DictionaryDatabase.KEY_DEFINITION }; + private Cursor searchBuildings(String query) throws SQLException { + Dao buildingDao = helper.getBuildingDao(); + + QueryBuilder qb = buildingDao.queryBuilder(); + qb.where().eq(Building.ID_FIELD_NAME, "%" + query + "%").or().eq(Building.NAME_FIELD_NAME, "%" + query + "%"); + PreparedQuery preparedQuery = qb.prepare(); - return mDictionary.getWordMatches(query, columns); + AndroidCompiledStatement compiledStatement = (AndroidCompiledStatement) preparedQuery.compile(helper + .getConnectionSource().getReadOnlyConnection(), StatementType.SELECT); + Cursor cursor = compiledStatement.getCursor(); + + return cursor; } - private Cursor getWord(Uri uri) { - String rowId = uri.getLastPathSegment(); - String[] columns = new String[] { DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION }; + private Cursor getBuilding(Uri uri) throws SQLException { + String buildingID = uri.getLastPathSegment(); + Dao buildingDao = helper.getBuildingDao(); + + QueryBuilder qb = buildingDao.queryBuilder(); + qb.where().eq(Building.ID_FIELD_NAME, buildingID); + PreparedQuery preparedQuery = qb.prepare(); + + AndroidCompiledStatement compiledStatement = (AndroidCompiledStatement) preparedQuery.compile(helper + .getConnectionSource().getReadOnlyConnection(), StatementType.SELECT); + Cursor cursor = compiledStatement.getCursor(); - return mDictionary.getWord(rowId, columns); + return cursor; } - private Cursor refreshShortcut(Uri uri) { + 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 @@ -153,12 +233,18 @@ public class MapContentProvider extends ContentProvider { * using the given item Uri and provide all the columns originally * provided with the suggestion query. */ - String rowId = uri.getLastPathSegment(); - String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, - DictionaryDatabase.KEY_DEFINITION, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, - SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID }; + String buildingID = uri.getLastPathSegment(); + Dao buildingDao = helper.getBuildingDao(); + + QueryBuilder qb = buildingDao.queryBuilder(); + qb.where().eq(Building.ID_FIELD_NAME, buildingID); + PreparedQuery preparedQuery = qb.prepare(); + + AndroidCompiledStatement compiledStatement = (AndroidCompiledStatement) preparedQuery.compile(helper + .getConnectionSource().getReadOnlyConnection(), StatementType.SELECT); + Cursor cursor = compiledStatement.getCursor(); - return mDictionary.getWord(rowId, columns); + return cursor; } /** @@ -168,10 +254,22 @@ public class MapContentProvider extends ContentProvider { @Override public String getType(Uri uri) { switch (sURIMatcher.match(uri)) { - case SEARCH_WORDS: - return WORDS_MIME_TYPE; - case GET_WORD: - return DEFINITION_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: diff --git a/src/net/cbaines/suma/POI.java b/src/net/cbaines/suma/POI.java index 485845c..f8c1f89 100644 --- a/src/net/cbaines/suma/POI.java +++ b/src/net/cbaines/suma/POI.java @@ -25,54 +25,55 @@ import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; public abstract class POI { - public static final String BUS_STOP = "busstop"; - public static final String BUILDING = "building"; - public static final String WAYPOINT = "waypoint"; - public static final String SITE = "site"; + public static final String BUS_STOP = "busstop"; + public static final String BUILDING = "building"; + public static final String WAYPOINT = "waypoint"; + public static final String SITE = "site"; - public static final String ID_FIELD_NAME = "id"; - public static final String POINT_FIELD_NAME = "point"; + public static final String ID_FIELD_NAME = "id"; + public static final String POINT_FIELD_NAME = "point"; - POI() { - } + POI() { + } - public POI(String id, GeoPoint point) { - this.id = id; - this.point = point; - } + public POI(String id, GeoPoint point) { + this.id = id; + this.point = point; + } - @DatabaseField(dataType = DataType.SERIALIZABLE, canBeNull = false) - public GeoPoint point; + @DatabaseField(dataType = DataType.SERIALIZABLE, canBeNull = false) + public GeoPoint point; - @DatabaseField(id = true) - public String id; + @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; + public String type; - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - POI other = (POI) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + POI other = (POI) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } } -- cgit v1.2.3 From 4a45362d8823a84cf9c3c805c006331303a0da33 Mon Sep 17 00:00:00 2001 From: Christopher Baines Date: Tue, 6 Mar 2012 15:11:31 +0000 Subject: Bumped android:minSdkVersion to 8, as implementing search stuff. --- AndroidManifest.xml | 8 +- src/net/cbaines/suma/Bus.java | 3 + src/net/cbaines/suma/FindActivity.java | 380 ------------------------------- src/net/cbaines/suma/MapActivity.java | 2 +- src/net/cbaines/suma/SearchActivity.java | 380 +++++++++++++++++++++++++++++++ 5 files changed, 386 insertions(+), 387 deletions(-) delete mode 100644 src/net/cbaines/suma/FindActivity.java create mode 100644 src/net/cbaines/suma/SearchActivity.java diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 4dfff99..423c58b 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -5,7 +5,7 @@ android:versionName="0.6.5 (alpha)" > @@ -53,12 +53,8 @@ - - - + diff --git a/src/net/cbaines/suma/Bus.java b/src/net/cbaines/suma/Bus.java index 34e20a6..9894e6b 100644 --- a/src/net/cbaines/suma/Bus.java +++ b/src/net/cbaines/suma/Bus.java @@ -35,6 +35,9 @@ public class Bus { final static String ROUTE_FIELD_NAME = "route"; final static String DIRECTION_FIELD_NAME = "direction"; + @DatabaseField(generatedId = true) + int gid; + /** * The identification number of the bus. */ diff --git a/src/net/cbaines/suma/FindActivity.java b/src/net/cbaines/suma/FindActivity.java deleted file mode 100644 index 5a07807..0000000 --- a/src/net/cbaines/suma/FindActivity.java +++ /dev/null @@ -1,380 +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.app.SearchManager; -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 implements Runnable, TextWatcher, - OnItemClickListener, LocationListener, OnItemLongClickListener { - - final static String TAG = "FindActivity"; - - public static final String ORIGIN = "o"; - public static final int MAP_ACTIVITY = 0; - - private EditText searchBar; - private ListView listItems; - private ProgressBar progBar; - private LinearLayout findContentLayout; - - private String searchTerm = ""; - - private Dao buildingDao; - private Dao busStopDao; - private Dao siteDao; - - private POIArrayAdapter adapter; - - private GeoPoint userLocation; - - private Thread searchThread; - - ArrayList getNearestPOIs(int distance) { - Log.i(TAG, "Getting nearest POI's"); - ArrayList nearestPOIs = new ArrayList(); - for (Iterator 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 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 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(); - - 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 buildingQueryBuilder = buildingDao.queryBuilder(); - buildingQueryBuilder.where().like(Building.ID_FIELD_NAME, "%" + thisSearchTerm + "%").or() - .like(Building.NAME_FIELD_NAME, "%" + thisSearchTerm + "%"); - PreparedQuery buildingPreparedQuery = buildingQueryBuilder.prepare(); - List 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 siteQueryBuilder = siteDao.queryBuilder(); - siteQueryBuilder.where().like(Site.ID_FIELD_NAME, "%" + thisSearchTerm + "%").or() - .like(Site.NAME_FIELD_NAME, "%" + thisSearchTerm + "%"); - PreparedQuery sitePreparedQuery = siteQueryBuilder.prepare(); - List 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 busStopQueryBuilder = busStopDao.queryBuilder(); - busStopQueryBuilder.where().like(BusStop.ID_FIELD_NAME, "%" + thisSearchTerm + "%").or() - .like(BusStop.DESCRIPTION_FIELD_NAME, "%" + thisSearchTerm + "%"); - PreparedQuery busStopPreparedQuery = busStopQueryBuilder.prepare(); - List 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); - - Log.i(TAG, "FindActivity started"); - - searchBar = (EditText) findViewById(R.id.searchBar); - searchBar.addTextChangedListener(this); - - Intent intent = getIntent(); - if (Intent.ACTION_SEARCH.equals(intent.getAction())) { - String query = intent.getStringExtra(SearchManager.QUERY); - Log.i(TAG, "Searching for " + query); - searchBar.setText(query); - } - - 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 6c4664e..e966b57 100644 --- a/src/net/cbaines/suma/MapActivity.java +++ b/src/net/cbaines/suma/MapActivity.java @@ -326,7 +326,7 @@ public class MapActivity extends ToastHelperActivity implements MapViewConstants @Override public boolean onSearchRequested() { Bundle appData = new Bundle(); - appData.putInt(FindActivity.ORIGIN, FindActivity.MAP_ACTIVITY); + appData.putInt(SearchActivity.ORIGIN, SearchActivity.MAP_ACTIVITY); startSearch(null, false, appData, false); return true; } diff --git a/src/net/cbaines/suma/SearchActivity.java b/src/net/cbaines/suma/SearchActivity.java new file mode 100644 index 0000000..f7f5e55 --- /dev/null +++ b/src/net/cbaines/suma/SearchActivity.java @@ -0,0 +1,380 @@ +/* + * 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.app.SearchManager; +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 SearchActivity extends OrmLiteBaseActivity implements Runnable, TextWatcher, + OnItemClickListener, LocationListener, OnItemLongClickListener { + + final static String TAG = "FindActivity"; + + public static final String ORIGIN = "o"; + public static final int MAP_ACTIVITY = 0; + + private EditText searchBar; + private ListView listItems; + private ProgressBar progBar; + private LinearLayout findContentLayout; + + private String searchTerm = ""; + + private Dao buildingDao; + private Dao busStopDao; + private Dao siteDao; + + private POIArrayAdapter adapter; + + private GeoPoint userLocation; + + private Thread searchThread; + + ArrayList getNearestPOIs(int distance) { + Log.i(TAG, "Getting nearest POI's"); + ArrayList nearestPOIs = new ArrayList(); + for (Iterator 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 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 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(); + + 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 buildingQueryBuilder = buildingDao.queryBuilder(); + buildingQueryBuilder.where().like(Building.ID_FIELD_NAME, "%" + thisSearchTerm + "%").or() + .like(Building.NAME_FIELD_NAME, "%" + thisSearchTerm + "%"); + PreparedQuery buildingPreparedQuery = buildingQueryBuilder.prepare(); + List 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 siteQueryBuilder = siteDao.queryBuilder(); + siteQueryBuilder.where().like(Site.ID_FIELD_NAME, "%" + thisSearchTerm + "%").or() + .like(Site.NAME_FIELD_NAME, "%" + thisSearchTerm + "%"); + PreparedQuery sitePreparedQuery = siteQueryBuilder.prepare(); + List 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 busStopQueryBuilder = busStopDao.queryBuilder(); + busStopQueryBuilder.where().like(BusStop.ID_FIELD_NAME, "%" + thisSearchTerm + "%").or() + .like(BusStop.DESCRIPTION_FIELD_NAME, "%" + thisSearchTerm + "%"); + PreparedQuery busStopPreparedQuery = busStopQueryBuilder.prepare(); + List 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); + + Log.i(TAG, "FindActivity started"); + + searchBar = (EditText) findViewById(R.id.searchBar); + searchBar.addTextChangedListener(this); + + Intent intent = getIntent(); + if (Intent.ACTION_SEARCH.equals(intent.getAction())) { + String query = intent.getStringExtra(SearchManager.QUERY); + Log.i(TAG, "Searching for " + query); + searchBar.setText(query); + } + + 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 -- cgit v1.2.3