Page MenuHomeGitPull.it

No OneTemporary

Authored By
Unknown
Size
222 KB
Referenced Files
None
Subscribers
None
diff --git a/build.gradle b/build.gradle
index 0c0cfcd4..e59d0732 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,77 +1,78 @@
buildscript {
repositories {
mavenCentral()
maven { url 'https://maven.google.com' }
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.0'
}
ext {
- support_ver = "25.3.1"
+ support_ver = "25.4.0"
}
}
allprojects {
repositories {
mavenCentral()
maven { url 'https://maven.google.com' }
google()
jcenter()
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '27.0.3'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
buildTypes {
debug {
applicationIdSuffix ".debug"
versionNameSuffix "-dev"
}
}
lintOptions {
abortOnError false
}
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
implementation "com.android.support:support-v4:$support_ver"
implementation "com.android.support:appcompat-v7:$support_ver"
implementation "com.android.support:design:$support_ver"
implementation "com.android.support:recyclerview-v7:$support_ver"
implementation "com.android.support:preference-v7:$support_ver"
implementation "com.android.support:cardview-v7:$support_ver"
implementation 'org.jsoup:jsoup:1.11.3'
implementation 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1'
+ implementation 'com.android.volley:volley:1.1.1'
}
}
diff --git a/res/layout/arrivals_nearby_card.xml b/res/layout/arrivals_nearby_card.xml
new file mode 100644
index 00000000..d62dfd74
--- /dev/null
+++ b/res/layout/arrivals_nearby_card.xml
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="utf-8"?>
+<android.support.v7.widget.CardView
+ xmlns:card_view="http://schemas.android.com/apk/res-auto"
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools" android:id="@+id/stop_cardView"
+ android:foreground="?android:attr/selectableItemBackground"
+ android:clickable="true"
+ android:focusable="true"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ card_view:cardCornerRadius="1dp"
+ android:layout_margin="8dp" android:padding="4dp">
+
+
+ <RelativeLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingLeft="8dp"
+ >
+ <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
+ android:id="@+id/lineNameTextView"
+ android:text="10" android:textSize="24sp"
+ android:textColor="@color/orange_700"
+ android:layout_marginLeft="20dp"
+ android:layout_marginStart="20dp"
+ android:layout_alignParentLeft="true"
+ android:layout_margin="10dp"
+ android:textStyle="normal" android:layout_marginRight="20dp" android:layout_marginEnd="20dp"
+ android:layout_marginBottom="20dp"/>
+ <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
+ android:id="@+id/lineDirectionTextView"
+ android:text="piazza statuto" android:textSize="20sp"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:layout_toLeftOf="@id/arrivalsDistanceTextView"
+ android:layout_toRightOf="@id/lineNameTextView"
+ android:textStyle="normal" android:layout_marginRight="6dp" android:layout_marginEnd="6dp"
+ android:layout_alignBaseline="@id/lineNameTextView"
+ android:layout_marginBottom="8dp"
+ android:layout_marginLeft="10dp" android:layout_marginTop="10dp"
+ android:layout_marginStart="10dp"/>
+ <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
+ android:layout_alignBaseline="@id/arrivalsTimeTextView"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:id="@+id/arrivalsDescriptionTextView" android:text="@string/bus_arriving_at"
+ android:textSize="@dimen/text_size_nearby"
+ android:layout_marginLeft="8dp" android:layout_marginTop="8dp" android:layout_marginStart="8dp"
+ android:layout_marginRight="8dp" android:layout_marginEnd="8dp" android:layout_marginBottom="8dp"/>
+ <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
+ android:layout_toRightOf="@id/arrivalsDescriptionTextView"
+ android:layout_margin="@dimen/default_textView_margin"
+ android:id="@+id/arrivalsTimeTextView" android:text="Orario" android:textSize="@dimen/text_size_nearby"
+ android:layout_below="@id/lineDirectionTextView"
+
+ android:textAppearance="?android:attr/textAppearanceLarge"
+ android:layout_alignParentRight="true"
+ android:layout_alignParentEnd="true"/>
+ <!-- Second line -->
+ <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
+ android:layout_marginBottom="10dp"
+ android:id="@+id/arrivalStopDescription"
+ android:text="@string/arrivals_card_at_the_stop" android:textSize="@dimen/text_size_nearby"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:layout_below="@id/arrivalsDescriptionTextView"
+ android:layout_margin="@dimen/default_textView_margin"
+ android:layout_alignBaseline="@id/arrivalStopName"
+ />
+ <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
+ android:layout_toRightOf="@id/arrivalStopDescription"
+ android:layout_toEndOf="@id/arrivalStopDescription"
+ android:layout_below="@id/arrivalsTimeTextView"
+ android:layout_marginBottom="10dp"
+ android:id="@+id/arrivalStopName" android:text="Prova prova" android:textSize="@dimen/text_size_nearby"
+ android:layout_marginLeft="10dp"
+ android:layout_marginStart="10dp"
+ android:textAppearance="?android:attr/textAppearanceLarge"
+ />
+ <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
+ android:layout_margin="@dimen/default_textView_margin"
+ android:layout_marginBottom="10dp"
+ android:layout_marginEnd="15dp"
+ android:id="@+id/arrivalsDistanceTextView" android:text="200 m" android:textSize="15sp"
+ android:layout_marginLeft="15dp"
+ android:layout_marginStart="15dp"
+ android:textAppearance="?android:attr/textAppearanceSmall"
+ android:layout_alignParentRight="true"
+ android:layout_alignParentEnd="true"
+ />
+
+ </RelativeLayout>
+
+</android.support.v7.widget.CardView>
\ No newline at end of file
diff --git a/res/layout/fragment_nearby_stops.xml b/res/layout/fragment_nearby_stops.xml
index 88fcefee..c6464454 100644
--- a/res/layout/fragment_nearby_stops.xml
+++ b/res/layout/fragment_nearby_stops.xml
@@ -1,41 +1,73 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="it.reyboz.bustorino.fragments.NearbyStopsFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/nearby_stops_message" android:id="@+id/titleTextView"
android:textAppearance="@android:style/TextAppearance.Medium"
- android:layout_marginBottom="15dp" android:layout_marginTop="10dp"
- android:gravity="center_horizontal" android:layout_margin="10dp" android:textSize="20sp"/>
+ android:layout_marginBottom="15dp" android:layout_marginTop="15dp"
+ android:gravity="center_horizontal" android:textSize="23sp"
+ android:layout_toLeftOf="@id/switchButton" android:layout_marginLeft="10dp"
+ android:layout_marginStart="10dp" android:layout_marginRight="10dp" android:layout_marginEnd="10dp"
+ />
+ <android.support.v7.widget.AppCompatButton
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ android:text="@string/show_arrivals"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content" android:id="@+id/switchButton"
+ android:layout_alignParentRight="true"
+ android:layout_alignParentEnd="true"
+ android:layout_margin="5dp"
+ android:layout_alignBaseline="@id/titleTextView"
+ app:backgroundTint="@color/teal_300"
+ android:textColor="@android:color/white"
+ />
+ <ProgressBar
+ style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/horizontalProgressBar"
+ android:layout_below="@id/titleTextView"
+ android:layout_alignParentRight="true"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentLeft="true"
+ android:indeterminate="true"
+ android:visibility="gone"
+ />
+
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
- android:layout_height="match_parent" android:layout_below="@+id/titleTextView"
+ android:layout_height="match_parent" android:layout_below="@id/horizontalProgressBar"
android:id="@+id/stopGridRecyclerView"
android:clickable="true"
android:focusable="true" android:visibility="gone"
android:clipChildren="false" android:clipToPadding="true" android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"/>
+
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/loadingBar"
android:paddingTop="10dp"
- android:progressDrawable="@color/blue_700" android:indeterminate="true"
+ android:progressDrawable="@color/blue_700"
+ android:indeterminate="true"
android:indeterminateTint="@color/blue_700"
android:layout_below="@+id/titleTextView" android:layout_centerHorizontal="true"/>
<TextView
android:text="@string/enableGpsText"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/messageTextView"
android:visibility="gone"
android:textAppearance="@style/Base.ThemeOverlay.AppCompat.Light"
android:layout_below="@+id/titleTextView" android:layout_centerHorizontal="true" android:textSize="17sp"
android:layout_marginTop="20dp"
/>
+
+
</RelativeLayout>
diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml
index eab6e557..c9194cf9 100644
--- a/res/values-it/strings.xml
+++ b/res/values-it/strings.xml
@@ -1,95 +1,100 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_description">Stai utilizzando l\'ultimo ritrovato in materia di rispetto della tua privacy.</string>
<string name="search">Cerca</string>
<string name="qrcode">QR Code</string>
<string name="insert_bus_stop_number">Numero fermata</string>
<string name="insert_bus_stop_name">Nome fermata</string>
<string name="insert_bus_stop_number_error">Inserisci il numero della fermata</string>
<string name="insert_bus_stop_name_error">Inserisci il nome della fermata</string>
<string name="network_error">Verifica l\'accesso ad Internet!</string>
<string name="no_bus_stop_have_this_name">Sembra che nessuna fermata abbia questo nome</string>
<string name="parsing_error">Errore di lettura del sito 5T/GTT (dannato sito!)</string>
<string name="passages">Fermata: %1$s</string>
<string name="lines">Linee: %1$s</string>
<string name="results">Scegli la fermata…</string>
<string name="no_passages">Nessun passaggio</string>
<string name="no_qrcode">Nessun QR code</string>
<string name="action_favorites">Preferiti</string>
<string name="action_help">Aiuto</string>
<string name="action_about">Informazioni</string>
<string name="action_about_more">Più informazioni</string>
<string name="action_news">News</string>
<string name="action_bugs">Invia bug</string>
<string name="action_source">Codice sorgente</string>
<string name="action_licence">Licenza</string>
<string name="action_author">Incontra l\'autore</string>
<string name="added_in_favorites">Fermata aggiunta ai preferiti</string>
<string name="cant_add_to_favorites">Impossibile aggiungere ai preferiti (memoria piena o database corrotto?)!</string>
<string name="title_activity_favorites">Preferiti</string>
<string name="tip_add_favorite">Tocca il nome di una fermata per aggiungerla in questa lista</string>
<string name="action_remove_from_favourites">Rimuovi</string>
<string name="action_rename_bus_stop_username">Rinomina</string>
<string name="dialog_rename_bus_stop_username_title">Rinomina fermata</string>
<string name="dialog_rename_bus_stop_username_reset_button">Reset</string>
<string name="about">Informazioni</string>
<string name="howDoesItWork"><b>Tocca il nome della fermata</b> per aggiungerla ai preferiti\n\n<b>Come leggere gli orari:</b>\n<b>&#160;&#160;&#160;12:56*</b> Orario in tempo reale\n<b>&#160;&#160;&#160;12:56</b> &#160; Orario programmato\n\n<b>Trascina giù per aggiornare</b> l\'orario.</string>
<string name="hint_button">OK !</string>
<string name="about_history">
<![CDATA[
<h1>Benvenuto!</h1>
<p>Grazie per aver scelto BusTO, un\'app \"politicamente\" <b>indipendente</b> da GTT/5T, per spostarsi a Torino attraverso <b>software libero</b>:</p>
<p>Perché usare BusTO?</p>
<p>
- Non sei <b>monitorato</b><br>
- Non ci sono <b>pubblicità</b><br>
- La tua <b>privacy</b> è al sicuro<br>
- Inoltre l\'app è molto leggera!<br>
</p>
<h2>Come Funziona?</h2>
<p>Quest\'app ottiene i passaggi dei bus in tempo reale filtrando i dati forniti pubblicamente sul sito <b>www.gtt.to.it</b> o <i>www.5t.torino.it</i> "per uso personale".</p>
<p>Ingredienti:<br>
- <b>Valerio Bozzolan</b> sviluppatore principale.<br>
- <b>Marco Gagino</b> intenso collaboratore, creatore dell\'icona, responsabile della grafica.<br>
- <b>Paolo Alloatti</b> per l\'idea dell\'icona.<br>
- <b>JSoup</b> libreria per "<i>web scaping</i>".<br>
- <b>makovkastar</b> bottone fluttuante.<br>
- <b>Google</b> icone Material Design.<br>
- Tutti i contributori!
</p>
<h2>Licenze</h2>
<p>L\'app e il relativo codice sorgente sono distribuiti sotto la licenza <i>GNU General Public License v3+</i>.
Ciò <b>significa</b> che puoi usare, studiare, migliorare e ricondividere quest\'app con <b>qualunque mezzo</b> e per <b>qualsiasi scopo</b>: a patto di mantenere sempre questi diritti a tua volta e di dare credito a Valerio Bozzolan.
</p>
<h2>Note</h2>
<p>Quest\'applicazione è rilasciata <b>nella speranza che sia utile a tutti</b> ma senza NESSUNA garanzia.</p>
<p>Buon utilizzo! :)</p>
]]>
</string>
<string name="query_too_short">Nome troppo corto, digita più caratteri e riprova</string>
<string name="route_towards_destination">%1$s verso %2$s</string>
<string name="route_towards_unknown">%s (destinazione sconosciuta)</string>
<string name="internal_error">Errore interno inaspettato, impossibile estrarre dati dal sito GTT/5T</string>
<string name="action_view_on_map">Visualizza sulla mappa</string>
<string name="nearby_stops_message">Fermate vicine</string>
<string name="position_searching_message">Ricerca della posizione in corso&#8230;</string>
<string name="no_stops_nearby">Nessuna fermata nei dintorni</string>
<string name="main_menu_pref">Preferenze</string>
<string name="database_update_message">Aggiornamento del database&#8230;</string>
<string name="pref_num_elements">Numero di fermate</string>
<string name="title_activity_settings">Impostazioni</string>
<string name="action_settings">Impostazioni</string>
<string name="pref_recents_group_title">Fermate recenti</string>
<string name="enableGpsText">Abilitare il GPS</string>
<string name="settings_search_radius">Raggio di ricerca</string>
+ <string name="settings_experimental">Funzionalità sperimentali</string>
+ <string name="bus_arriving_at">arriva alle</string>
+ <string name="arrivals_card_at_the_stop">alla fermata</string>
+ <string name="show_arrivals">Mostra arrivi</string>
+ <string name="show_stops">Mostra fermate</string>
</resources>
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index 414ebad3..cd96ff05 100644
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -1,8 +1,10 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="fab_margin">16dp</dimen>
+ <dimen name="text_size_nearby">18sp</dimen>
+ <dimen name="default_textView_margin">6dp</dimen>
</resources>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 4563cecd..ea2ee621 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1,105 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name" translatable="false">BusTO</string>
<string name="app_description">You\'re using the latest in technology when it comes to respecting your privacy.
</string>
<string name="search">Search</string>
<string name="qrcode">Scan QR Code</string>
<string name="insert_bus_stop_number">Bus stop number</string>
<string name="insert_bus_stop_name">Bus stop name</string>
<string name="insert_bus_stop_number_error">Insert bus stop number</string>
<string name="insert_bus_stop_name_error">Insert bus stop name</string>
<string name="route_towards_destination">%1$s towards %2$s</string>
<string name="route_towards_unknown">%s (unknown destination)</string>
<string name="network_error">Verify your Internet connection!</string>
<string name="no_bus_stop_have_this_name">Seems that no bus stop have this name</string>
<string name="parsing_error">Error parsing the 5T/GTT website (damn site!)</string>
<string name="query_too_short">Name too short, type more characters and retry
</string> <!-- TODO: carry out experiments to determine the best wording for this message and publish a paper with the findings -->
<string name="passages">Arrivals at: %1$s</string>
<string name="results">Choose the bus stop…</string>
<string name="lines">Lines: %1$s</string>
<string name="no_passages">No timetable found</string>
<string name="no_qrcode">No QR code</string>
<string name="internal_error">Unexpected internal error, cannot extract data from GTT/5T website</string>
<string name="action_help">Help</string>
<string name="action_about">About</string>
<string name="action_about_more">More about</string>
<string name="action_news">News releases</string>
<string name="action_bugs">Bug submission</string>
<string name="action_source">Source code</string>
<string name="action_licence">Licence</string>
<string name="action_author">Meet the author</string>
<string name="added_in_favorites">Bus stop is now in your favorites</string>
<string name="action_favorites">Favorites</string>
<string name="title_activity_favorites">Favorites</string>
<string name="tip_add_favorite">Press on a bus stop name to populate this list</string>
<string name="action_remove_from_favourites">Delete</string>
<string name="action_rename_bus_stop_username">Rename</string>
<string name="dialog_rename_bus_stop_username_title">Rename the bus stop</string>
<string name="dialog_rename_bus_stop_username_reset_button">Reset</string>
<string name="about">About</string>
<string name="howDoesItWork">
<b>Tap the bus stop name</b>
to add it to the favourites\n\n<b>How to read timelines:</b>\n<b>&#160;&#160;&#160;12:56*</b> Real-time
arrivals\n<b>&#160;&#160;&#160;12:56</b> &#160; Scheduled arrivals\n\n<b>Pull down to refresh</b> the timetable
</string>
<string name="hint_button">GOT IT!</string>
<string name="about_history">
<![CDATA[
<h1>Welcome!</h1>
<p>Thanks for using BusTO, a "politically" <b>independent</b> app useful to move around Torino using a <b>Free/Libre software</b>.</p>
<p>Why use this app?</p>
<p>
- You\'ll never be <b>tracked</b><br>
- You\'ll never see boring <b>ads</b><br>
- We\'ll always respect your <b>privacy</b><br>
- Moreover, it\'s lightweight!<br>
</p>
<h2>How does it work?</h2>
<p>This app will show you bus timetables gathering data from <b>www.gtt.to.it</b> or <b>www.5t.torino.it</b> "for personal use".</p>
<p>Who worked on BusTO:<br>
- <b>Valerio Bozzolan</b> main developer.<br>
- <b>Marco Gagino</b> main contributor and icon creator.<br>
- <b>Paolo Alloatti</b> original concept of the icon.<br>
- <b>JSoup</b> web scraper library.<br>
- <b>makovkastar</b> floating buttons.<br>
- <b>Google</b> Material Design icons.<br>
- All the contributors!
</p>
<h2>Licenses</h2>
<p>The app and the related source code are released by Valerio Bozzolan under the terms of the <i>GNU General Public License v3+</i>).
So everyone is allowed to use, to study, to improve and to share this app by <b>any kind of means</b> and for <b>any purpose</b>: under the conditions of maintaining this rights and of attributing the original work to Valerio Bozzolan.</p>
<h2>Notes</h2>
<p>This app has been developed <b>hoping to be useful to everyone</b> but without ANY warranty.</p>
<p>This translation is kindly provided by Riccardo Caniato and Marco Gagino.</p>
<p>Get involved! :)</p>
]]>
</string>
<string name="cant_add_to_favorites">Cannot add to favorites (storage full or corrupted database?)!</string>
<string name="action_view_on_map">View on a map</string>
<string name="list_fragment_debug" translatable="false">ListFragment - BusTO</string>
<string name="mainSharedPreferences" translatable="false">it.reyboz.bustorino.preferences</string>
<string name="databaseUpdatingPref" translatable="false">db_is_updating</string>
<string name="nearby_stops_message">Nearby stops</string>
<string name="position_searching_message">Finding the position&#8230;</string>
<string name="no_stops_nearby">No stops nearby</string>
<string name="pref_num_elements">Number of stops</string>
<string name="main_menu_pref">Preferences</string>
<string name="title_activity_settings">Settings</string>
<string name="action_settings">Settings</string>
<string name="settings_experimental">Experimental features</string>
<string name="settings_search_radius">Search radius</string>
<string name="pref_recents_group_title">Recent stops</string>
<string name="enableGpsText">Please enable GPS</string>
<string name="database_update_message">Database update in progress&#8230;</string>
+ <string name="bus_arriving_at">is arriving at</string>
+ <string name="arrivals_card_at_the_stop">at the stop</string>
+ <string name="two_strings_format" translatable="false">%1$s - %2$s</string>
+ <string name="show_arrivals">Show arrivals</string>
+ <string name="show_stops">Show stops</string>
</resources>
diff --git a/src/it/reyboz/bustorino/ActivityMain.java b/src/it/reyboz/bustorino/ActivityMain.java
index 96218d23..fd8a7822 100644
--- a/src/it/reyboz/bustorino/ActivityMain.java
+++ b/src/it/reyboz/bustorino/ActivityMain.java
@@ -1,796 +1,796 @@
/*
BusTO - Arrival times for Turin public transports.
Copyright (C) 2014 Valerio Bozzolan
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.*;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NavUtils;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.support.design.widget.FloatingActionButton;
import it.reyboz.bustorino.backend.*;
import it.reyboz.bustorino.fragments.*;
import it.reyboz.bustorino.middleware.*;
import java.util.List;
import static android.location.Criteria.NO_REQUIREMENT;
public class ActivityMain extends GeneralActivity implements FragmentListener {
/*
* Layout elements
*/
private EditText busStopSearchByIDEditText;
private EditText busStopSearchByNameEditText;
private ProgressBar progressBar;
private TextView howDoesItWorkTextView;
private Button hideHintButton;
private MenuItem actionHelpMenuItem;
private SwipeRefreshLayout swipeRefreshLayout;
private FloatingActionButton floatingActionButton;
private FragmentManager framan;
private Snackbar snackbar;
/*
* Search mode
*/
private static final int SEARCH_BY_NAME = 0;
private static final int SEARCH_BY_ID = 1;
private static final int SEARCH_BY_ROUTE = 2; // TODO: implement this (bug #1512948)
private int searchMode;
/*
* Options
*/
private final String OPTION_SHOW_LEGEND = "show_legend";
private final String LOCATION_PERMISSION_GIVEN = "loc_permission";
/*
* Status
*/
private DBStatusManager prefsManager;
private DBStatusManager.OnDBUpdateStatusChangeListener updatelistener;
private static final String DEBUG_TAG="BusTO - MainActivity";
/* // useful for testing:
public class MockFetcher implements ArrivalsFetcher {
@Override
public Palina ReadArrivalTimesAll(String routeID, AtomicReference<result> res) {
SystemClock.sleep(5000);
res.set(result.SERVER_ERROR);
return new Palina();
}
}
private ArrivalsFetcher[] ArrivalFetchers = {new MockFetcher(), new MockFetcher(), new MockFetcher(), new MockFetcher(), new MockFetcher()};*/
private RecursionHelper<ArrivalsFetcher> ArrivalFetchersRecursionHelper = new RecursionHelper<>(new ArrivalsFetcher[] {new GTTJSONFetcher(), new FiveTScraperFetcher()});
private RecursionHelper<StopsFinderByName> StopsFindersByNameRecursionHelper = new RecursionHelper<>(new StopsFinderByName[] {new GTTStopsFetcher(), new FiveTStopsFetcher()});
/*
* Position
*/
//Fine location criteria
private final Criteria cr = new Criteria();
private boolean pendingNearbyStopsRequest = false;
private LocationManager locmgr;
/*
* Database Access
*/
private StopsDB stopsDB;
private UserDB userDB;
private FragmentHelper fh;
///////////////////////////////// EVENT HANDLERS ///////////////////////////////////////////////
/*
* @see swipeRefreshLayout
*/
private Handler handler = new Handler();
private final Runnable refreshing = new Runnable() {
public void run() {
if(framan.findFragmentById(R.id.resultFrame) instanceof ArrivalsFragment){
ArrivalsFragment fragment = (ArrivalsFragment) framan.findFragmentById(R.id.resultFrame);
String stopName = fragment.getStopID();
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(stopName);
} else
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute();
}
};
//// MAIN METHOD ///
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
framan = getSupportFragmentManager();
this.stopsDB = new StopsDB(getApplicationContext());
this.userDB = new UserDB(getApplicationContext());
setContentView(R.layout.activity_main);
busStopSearchByIDEditText = (EditText) findViewById(R.id.busStopSearchByIDEditText);
busStopSearchByNameEditText = (EditText) findViewById(R.id.busStopSearchByNameEditText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
howDoesItWorkTextView = (TextView) findViewById(R.id.howDoesItWorkTextView);
hideHintButton = (Button) findViewById(R.id.hideHintButton);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.listRefreshLayout);
floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton);
framan.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Log.d("MainActivity, BusTO", "BACK STACK CHANGED");
}
});
busStopSearchByIDEditText.setSelectAllOnFocus(true);
busStopSearchByIDEditText
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
// IME_ACTION_SEARCH alphabetical option
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
onSearchClick(v);
return true;
}
return false;
}
});
busStopSearchByNameEditText
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
// IME_ACTION_SEARCH alphabetical option
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
onSearchClick(v);
return true;
}
return false;
}
});
// Called when the layout is pulled down
swipeRefreshLayout
.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
handler.post(refreshing);
}
});
/**
* @author Marco Gagino!!!
*/
//swipeRefreshLayout.setColorSchemeColors(R.color.blue_500, R.color.orange_500); // setColorScheme is deprecated, setColorSchemeColors isn't
swipeRefreshLayout.setColorSchemeResources(R.color.blue_500,R.color.orange_500);
fh = new FragmentHelper(this,R.id.listRefreshLayout,R.id.resultFrame);
setSearchModeBusStopID();
//---------------------------- START INTENT CHECK QUEUE ------------------------------------
// Intercept calls from URL intent
boolean tryedFromIntent = false;
String busStopID = null;
String busStopDisplayName = null;
Uri data = getIntent().getData();
if (data != null) {
busStopID = getBusStopIDFromUri(data);
tryedFromIntent = true;
}
// Intercept calls from other activities
if (!tryedFromIntent) {
Bundle b = getIntent().getExtras();
if (b != null) {
busStopID = b.getString("bus-stop-ID");
busStopDisplayName = b.getString("bus-stop-display-name");
/**
* I'm not very sure if you are coming from an Intent.
* Some launchers work in strange ways.
*/
tryedFromIntent = busStopID != null;
}
}
//---------------------------- END INTENT CHECK QUEUE --------------------------------------
if (busStopID == null) {
// Show keyboard if can't start from intent
// JUST DON'T
// showKeyboard();
// You haven't obtained anything... from an intent?
if (tryedFromIntent) {
// This shows a luser warning
ArrivalFetchersRecursionHelper.reset();
Toast.makeText(getApplicationContext(),
R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show();
}
} else {
// If you are here an intent has worked successfully
setBusStopSearchByIDEditText(busStopID);
/*
//THIS PART SHOULDN'T BE NECESSARY SINCE THE LAST SUCCESSFULLY SEARCHED BUS
// STOP IS ADDED AUTOMATICALLY
Stop nextStop = new Stop(busStopID);
// forcing it as user name even though it could be standard name, it doesn't really matter
nextStop.setStopUserName(busStopDisplayName);
//set stop as last succe
fh.setLastSuccessfullySearchedBusStop(nextStop);
*/
createFragmentForStop(busStopID);
}
//Try (hopefully) database update
//TODO: Start the service in foreground, check last time it ran before
DatabaseUpdateService.startDBUpdate(getApplicationContext());
/*
Set database update
*/
updatelistener = new DBStatusManager.OnDBUpdateStatusChangeListener(){
@Override
public boolean defaultStatusValue() {
return true;
}
@Override
public void onDBStatusChanged(boolean updating) {
if(updating){
createDefaultSnackbar();
}
else if(snackbar!=null){
snackbar.dismiss();
snackbar = null;
}
}
};
prefsManager = new DBStatusManager(getApplicationContext(),updatelistener);
prefsManager.registerListener();
//locationHandler = new GPSLocationAdapter(getApplicationContext());
//--------- NEARBY STOPS--------//
//SETUP LOCATION
locmgr = (LocationManager) getSystemService(LOCATION_SERVICE);
cr.setAccuracy(Criteria.ACCURACY_FINE);
cr.setAltitudeRequired(false);
cr.setBearingRequired(false);
cr.setCostAllowed(true);
cr.setPowerRequirement(Criteria.NO_REQUIREMENT);
//We want the nearby bus stops!
handler.post(new NearbyStopsRequester());
//If there are no providers available, then, wait for them
Log.d("MainActivity", "Created");
}
/**
* Reload bus stop timetable when it's fulled resumed from background.
*/
@Override
protected void onPostResume() {
super.onPostResume();
Log.d("ActivityMain", "onPostResume fired. Last successfully bus stop ID: " + fh.getLastSuccessfullySearchedBusStop());
if (searchMode == SEARCH_BY_ID && fh.getLastSuccessfullySearchedBusStop() != null) {
setBusStopSearchByIDEditText(fh.getLastSuccessfullySearchedBusStop().ID);
//new asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStop.ID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop);
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute();
} else {
//we have new activity or we don't have a new searched stop.
//Let's search stops nearby
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.resultFrame);
}
//show the FAB since it remains hidden
floatingActionButton.show();
//show the Snackbar //TODO: remove
//snackbar = Snackbar.make(floatingActionButton,
// R.string.database_update_message,Snackbar.LENGTH_INDEFINITE);
//snackbar.show();
}
@Override
protected void onPause() {
super.onPause();
fh.stopLastRequestIfNeeded();
fh.setBlockAllActivities(true);
if(updatelistener!=null && prefsManager!=null) prefsManager.unregisterListener();
locmgr.removeUpdates(locListener);
}
@Override
protected void onResume() {
super.onResume();
fh.setBlockAllActivities(false);
if(updatelistener!=null && prefsManager!=null) {
prefsManager.registerListener();
if(prefsManager.isDBUpdating(true)){
createDefaultSnackbar();
}
}
if(pendingNearbyStopsRequest)
handler.post(new NearbyStopsRequester());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
actionHelpMenuItem = menu.findItem(R.id.action_help);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
// Respond to the action bar's Up/Home button
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.action_help:
showHints();
return true;
case R.id.action_favorites:
startActivity(new Intent(ActivityMain.this, ActivityFavorites.class));
return true;
case R.id.action_about:
startActivity(new Intent(ActivityMain.this, ActivityAbout.class));
return true;
case R.id.action_news:
openIceweasel("https://blog.reyboz.it/tag/busto/");
return true;
case R.id.action_bugs:
openIceweasel("https://bugs.launchpad.net/bus-torino");
return true;
case R.id.action_source:
openIceweasel("https://code.launchpad.net/bus-torino");
return true;
case R.id.action_licence:
openIceweasel("https://www.gnu.org/licenses/gpl-3.0.html");
return true;
case R.id.action_author:
// TODO: a neutral website with a cute landing page and credits to everyone? -- boz, Thu Jan 17 02:17:45 CET 2019
openIceweasel("https://boz.reyboz.it/?lovebusto");
return true;
case R.id.action_settings:
Log.d("MAINBusTO","Pressed button preferences");
startActivity(new Intent(ActivityMain.this,ActivitySettings.class));
}
return super.onOptionsItemSelected(item);
}
/**
* OK this is pure shit
*
* @param v View clicked
*/
public void onSearchClick(View v) {
if (searchMode == SEARCH_BY_ID) {
String busStopID = busStopSearchByIDEditText.getText().toString();
//OLD ASYNCTASK
//new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop);
if(busStopID == null || busStopID.length() <= 0) {
showMessage(R.string.insert_bus_stop_number_error);
toggleSpinner(false);
} else{
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(busStopID);
Log.d("MainActiv","Started search for arrivals of stop "+busStopID);
}
} else { // searchMode == SEARCH_BY_NAME
String query = busStopSearchByNameEditText.getText().toString();
//new asyncWgetBusStopSuggestions(query, stopsDB, StopsFindersByNameRecursionHelper);
new AsyncDataDownload(AsyncDataDownload.RequestType.STOPS,fh).execute(query);
}
}
/** PERMISSION STUFF **/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_REQUEST_POSITION:
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
setOption(LOCATION_PERMISSION_GIVEN,true);
//if we sent a request for a new NearbyStopsFragment
if(pendingNearbyStopsRequest){
pendingNearbyStopsRequest=false;
handler.post(new NearbyStopsRequester());
}
} else {
//permission denied
setOption(LOCATION_PERMISSION_GIVEN,false);
}
//add other cases for permissions
}
}
@Override
public void createFragmentForStop(String ID) {
//new asyncWgetBusStopFromBusStopID(ID, ArrivalFetchersRecursionHelper,lastSuccessfullySearchedBusStop);
if(ID == null || ID.length() <= 0) {
// we're still in UI thread, no need to mess with Progress
showMessage(R.string.insert_bus_stop_number_error);
toggleSpinner(false);
} else {
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(ID);
Log.d("MainActiv","Started search for arrivals of stop "+ID);
}
}
/**
* QR scan button clicked
*
* @param v View QRButton clicked
*/
public void onQRButtonClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
/**
* Receive the Barcode Scanner Intent
*
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
Uri uri;
try {
uri = Uri.parse(scanResult != null ? scanResult.getContents() : null); // this apparently prevents NullPointerException. Somehow.
} catch (NullPointerException e) {
Toast.makeText(getApplicationContext(),
R.string.no_qrcode, Toast.LENGTH_SHORT).show();
return;
}
String busStopID = getBusStopIDFromUri(uri);
busStopSearchByIDEditText.setText(busStopID);
createFragmentForStop(busStopID);
}
public void onHideHint(View v) {
hideHints();
setOption(OPTION_SHOW_LEGEND, false);
}
public void onToggleKeyboardLayout(View v) {
if (searchMode == SEARCH_BY_NAME) {
setSearchModeBusStopID();
if (busStopSearchByIDEditText.requestFocus()) {
showKeyboard();
}
} else { // searchMode == SEARCH_BY_ID
setSearchModeBusStopName();
if (busStopSearchByNameEditText.requestFocus()) {
showKeyboard();
}
}
}
private void createDefaultSnackbar(){
if(snackbar==null){
snackbar = Snackbar.make(findViewById(R.id.searchButton),R.string.database_update_message,Snackbar.LENGTH_INDEFINITE);
}
snackbar.show();
}
///////////////////////////////// POSITION STUFF//////////////////////////////////////////////
private void resolveStopRequest(String provider){
Log.d(DEBUG_TAG,"Provider "+provider+" got enabled");
if(locmgr!=null && pendingNearbyStopsRequest && locmgr.getProvider(provider).meetsCriteria(cr)){
pendingNearbyStopsRequest = false;
handler.post(new NearbyStopsRequester());
}
}
final LocationListener locListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.d(DEBUG_TAG,"Location changed");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(DEBUG_TAG,"Location provider status: "+status);
if(status== LocationProvider.AVAILABLE){
resolveStopRequest(provider);
}
}
@Override
public void onProviderEnabled(String provider) {
resolveStopRequest(provider);
}
@Override
public void onProviderDisabled(String provider) {
}
};
class NearbyStopsRequester implements Runnable{
@SuppressLint("MissingPermission")
@Override
public void run() {
if(!getOption(LOCATION_PERMISSION_GIVEN, false)){
pendingNearbyStopsRequest = true;
assertLocationPermissions();
return;
}
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locManager == null) {
Log.e(DEBUG_TAG, "location manager is nihil, cannot create NearbyStopsFragment");
return;
}
if(anyLocationProviderMatchesCriteria(locManager,cr,true) && fh.getLastSuccessfullySearchedBusStop()==null) {
//Go ahead with the request
Log.d("mainActivity","Recreating stop fragment");
swipeRefreshLayout.setVisibility(View.VISIBLE);
- NearbyStopsFragment fragment = NearbyStopsFragment.newInstance();
+ NearbyStopsFragment fragment = NearbyStopsFragment.newInstance(NearbyStopsFragment.TYPE_ARRIVALS);
Fragment oldFrag = framan.findFragmentById(R.id.resultFrame);
FragmentTransaction ft = framan.beginTransaction();
if(oldFrag!=null)
ft.remove(oldFrag);
ft.add(R.id.resultFrame,fragment,"nearbyStop_correct");
ft.commit();
framan.executePendingTransactions();
pendingNearbyStopsRequest = false;
} else if(!anyLocationProviderMatchesCriteria(locManager,cr,true)){
//Wait for the providers
Log.d(DEBUG_TAG,"Queuing position request");
pendingNearbyStopsRequest = true;
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10,0.1f,locListener);
}
}
}
private boolean anyLocationProviderMatchesCriteria(LocationManager mng, Criteria cr, boolean enabled){
List<String> providers = mng.getProviders(cr,enabled);
Log.d(DEBUG_TAG,"Getting enabled location providers: ");
for(String s: providers){
Log.d(DEBUG_TAG,"Provider "+s);
}
return providers.size()>0;
}
///////////////////////////////// OTHER STUFF //////////////////////////////////////////////////
@Override
public void addLastStopToFavorites() {
if(fh.getLastSuccessfullySearchedBusStop() != null) {
new AsyncAddToFavorites(this).execute(fh.getLastSuccessfullySearchedBusStop());
}
}
@Override
public void showFloatingActionButton(boolean yes) {
if(yes) floatingActionButton.show();
else floatingActionButton.hide();
}
@Override
public void enableRefreshLayout(boolean yes) {
swipeRefreshLayout.setEnabled(yes);
}
////////////////////////////////////// GUI HELPERS /////////////////////////////////////////////
@Override
public void showKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View view = searchMode == SEARCH_BY_ID ? busStopSearchByIDEditText : busStopSearchByNameEditText;
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
@Override
public void showMessage(int messageID) {
Toast.makeText(getApplicationContext(), messageID, Toast.LENGTH_SHORT).show();
}
private void setSearchModeBusStopID() {
searchMode = SEARCH_BY_ID;
busStopSearchByNameEditText.setVisibility(View.GONE);
busStopSearchByNameEditText.setText("");
busStopSearchByIDEditText.setVisibility(View.VISIBLE);
floatingActionButton.setImageResource(R.drawable.alphabetical);
}
private void setSearchModeBusStopName() {
searchMode = SEARCH_BY_NAME;
busStopSearchByIDEditText.setVisibility(View.GONE);
busStopSearchByIDEditText.setText("");
busStopSearchByNameEditText.setVisibility(View.VISIBLE);
floatingActionButton.setImageResource(R.drawable.numeric);
}
/**
* Having that cursor at the left of the edit text makes me cancer.
* @param busStopID bus stop ID
*/
private void setBusStopSearchByIDEditText(String busStopID) {
busStopSearchByIDEditText.setText(busStopID);
busStopSearchByIDEditText.setSelection(busStopID.length());
}
private void showHints() {
howDoesItWorkTextView.setVisibility(View.VISIBLE);
hideHintButton.setVisibility(View.VISIBLE);
actionHelpMenuItem.setVisible(false);
}
private void hideHints() {
howDoesItWorkTextView.setVisibility(View.GONE);
hideHintButton.setVisibility(View.GONE);
actionHelpMenuItem.setVisible(true);
}
//TODO: toggle spinner from mainActivity
@Override
public void toggleSpinner(boolean enable) {
if (enable) {
//already set by the RefreshListener when needed
//swipeRefreshLayout.setRefreshing(true);
progressBar.setVisibility(View.VISIBLE);
} else {
swipeRefreshLayout.setRefreshing(false);
progressBar.setVisibility(View.GONE);
}
}
private void prepareGUIForBusLines() {
swipeRefreshLayout.setEnabled(true);
swipeRefreshLayout.setVisibility(View.VISIBLE);
actionHelpMenuItem.setVisible(true);
}
private void prepareGUIForBusStops() {
swipeRefreshLayout.setEnabled(false);
swipeRefreshLayout.setVisibility(View.VISIBLE);
actionHelpMenuItem.setVisible(false);
}
/**
* This provides a temporary fix to make the transition
* to a single asynctask go smoother
* @param fragmentType the type of fragment created
*/
@Override
public void readyGUIfor(FragmentKind fragmentType) {
hideKeyboard();
//if we are getting results, already, stop waiting for nearbyStops
if(pendingNearbyStopsRequest && (fragmentType==FragmentKind.ARRIVALS || fragmentType==FragmentKind.STOPS)) {
locmgr.removeUpdates(locListener);
pendingNearbyStopsRequest = false;
}
if(fragmentType==null) Log.e("ActivityMain","Problem with fragmentType");
else
switch (fragmentType){
case ARRIVALS:
prepareGUIForBusLines();
if (getOption(OPTION_SHOW_LEGEND, true)) {
showHints();
}
break;
case STOPS:
prepareGUIForBusStops();
break;
default:
Log.e("BusTO Activity","Called readyGUI with unsupported type of Fragment");
return;
}
// Shows hints
}
/**
* Open an URL in the default browser.
*
* @param url URL
*/
public void openIceweasel(String url) {
Intent browserIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent1);
}
///////////////////// INTENT HELPER ////////////////////////////////////////////////////////////
/**
* Try to extract the bus stop ID from a URi
*
* @param uri The URL
* @return bus stop ID or null
*/
public static String getBusStopIDFromUri(Uri uri) {
String busStopID;
// everithing catches fire when passing null to a switch.
String host = uri.getHost();
if(host == null) {
Log.e("ActivityMain", "Not an URL: " + uri);
return null;
}
switch(host) {
case "m.gtt.to.it":
// http://m.gtt.to.it/m/it/arrivi.jsp?n=1254
busStopID = uri.getQueryParameter("n");
if (busStopID == null) {
Log.e("ActivityMain", "Expected ?n from: " + uri);
}
break;
case "www.gtt.to.it":
case "gtt.to.it":
// http://www.gtt.to.it/cms/percorari/arrivi?palina=1254
busStopID = uri.getQueryParameter("palina");
if (busStopID == null) {
Log.e("ActivityMain", "Expected ?palina from: " + uri);
}
break;
default:
Log.e("ActivityMain", "Unexpected intent URL: " + uri);
busStopID = null;
}
return busStopID;
}
}
\ No newline at end of file
diff --git a/src/it/reyboz/bustorino/adapters/ArrivalsStopAdapter.java b/src/it/reyboz/bustorino/adapters/ArrivalsStopAdapter.java
new file mode 100644
index 00000000..84c68482
--- /dev/null
+++ b/src/it/reyboz/bustorino/adapters/ArrivalsStopAdapter.java
@@ -0,0 +1,214 @@
+/*
+ BusTO - UI components
+ Copyright (C) 2017 Fabio Mazza
+
+ 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 3 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, see <http://www.gnu.org/licenses/>.
+ */
+package it.reyboz.bustorino.adapters;
+
+import android.content.Context;
+import android.location.Location;
+import android.support.annotation.Nullable;
+import android.support.v4.util.Pair;
+import android.support.v7.widget.RecyclerView;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.RelativeLayout;
+import android.widget.TextView;
+import it.reyboz.bustorino.R;
+import it.reyboz.bustorino.backend.*;
+import it.reyboz.bustorino.fragments.FragmentListener;
+import it.reyboz.bustorino.util.StopSorterByDistance;
+
+import java.util.*;
+
+public class ArrivalsStopAdapter extends RecyclerView.Adapter<ArrivalsStopAdapter.ViewHolder> {
+ private final static int layoutRes = R.layout.arrivals_nearby_card;
+ //private List<Stop> stops;
+ private @Nullable Location userPosition;
+ private FragmentListener listener;
+ private List< Pair<Stop, Route> > routesPairList = new ArrayList<>();
+ private Context context;
+ //Maximum number of stops to keep
+ private final int MAX_STOPS = 20; //TODO: make it programmable
+
+ public ArrivalsStopAdapter(@Nullable List< Pair<Stop, Route> > routesPairList, FragmentListener fragmentListener, Context con, @Nullable Location pos) {
+ listener = fragmentListener;
+ userPosition = pos;
+ this.routesPairList = routesPairList;
+ context = con.getApplicationContext();
+ Collections.sort(this.routesPairList,new RoutePositionSorter(pos));
+ // if(paline!=null)
+ //resetRoutesPairList(paline);
+ }
+
+
+
+ @Override
+ public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+ final View view = LayoutInflater.from(parent.getContext()).inflate(layoutRes, parent, false);
+
+ return new ViewHolder(view);
+ }
+
+ @Override
+ public void onBindViewHolder(ViewHolder holder, int position) {
+ //DO THE ACTUAL WORK TO PUT THE DATA
+ if(routesPairList==null || routesPairList.size() == 0) return; //NO STOPS
+ final Pair<Stop,Route> stopRoutePair = routesPairList.get(position);
+ if(stopRoutePair!=null){
+ final Stop stop = stopRoutePair.first;
+ final Route r = stopRoutePair.second;
+ final Double distance = stop.getDistanceFromLocation(userPosition);
+ if(distance!=Double.POSITIVE_INFINITY){
+ holder.distancetextView.setText(distance.intValue()+" m");
+ } else {
+ holder.distancetextView.setVisibility(View.GONE);
+ }
+ final String stopText = String.format(context.getResources().getString(R.string.two_strings_format),stop.getStopDisplayName(),stop.ID);
+ holder.stopNameView.setText(stopText);
+ //final String routeName = String.format(context.getResources().getString(R.string.two_strings_format),r.getNameForDisplay(),r.destinazione);
+ holder.lineNameTextView.setText(r.getNameForDisplay());
+ /* EXPERIMENTS
+ if(r.destinazione==null || r.destinazione.trim().isEmpty()){
+ holder.lineDirectionTextView.setVisibility(View.GONE);
+ RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.arrivalsDescriptionTextView.getLayoutParams();
+ params.addRule(RelativeLayout.RIGHT_OF,holder.lineNameTextView.getId());
+ holder.arrivalsDescriptionTextView.setLayoutParams(params);
+ } else {
+ RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.arrivalsDescriptionTextView.getLayoutParams();
+ params.removeRule(RelativeLayout.RIGHT_OF);
+ holder.arrivalsDescriptionTextView.setLayoutParams(params);
+ holder.lineDirectionTextView.setVisibility(View.VISIBLE);
+
+ }
+ */
+ holder.lineDirectionTextView.setText(r.destinazione);
+ holder.arrivalsTextView.setText(r.getPassaggiToString(0,2,true));
+ holder.stopID =stop.ID;
+ } else {
+ Log.w("SquareStopAdapter","!! The selected stop is null !!");
+ }
+ }
+
+ @Override
+ public int getItemCount() {
+ return routesPairList.size();
+ }
+
+ class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
+ TextView lineNameTextView;
+ TextView lineDirectionTextView;
+ TextView stopNameView;
+ TextView arrivalsDescriptionTextView;
+ TextView arrivalsTextView;
+ TextView distancetextView;
+ String stopID;
+
+ ViewHolder(View holdView){
+ super(holdView);
+ holdView.setOnClickListener(this);
+ lineNameTextView = (TextView) holdView.findViewById(R.id.lineNameTextView);
+ lineDirectionTextView = (TextView) holdView.findViewById(R.id.lineDirectionTextView);
+ stopNameView = (TextView) holdView.findViewById(R.id.arrivalStopName);
+ arrivalsTextView = (TextView) holdView.findViewById(R.id.arrivalsTimeTextView);
+ arrivalsDescriptionTextView = (TextView) holdView.findViewById(R.id.arrivalsDescriptionTextView);
+ distancetextView = (TextView) holdView.findViewById(R.id.arrivalsDistanceTextView);
+ }
+
+ @Override
+ public void onClick(View v) {
+ listener.createFragmentForStop(stopID);
+ }
+
+ }
+
+ public void resetRoutesPairList(List<Palina> stopList){
+ Collections.sort(stopList,new StopSorterByDistance(userPosition));
+
+ this.routesPairList = new ArrayList<>(stopList.size());
+ int maxNum = Math.min(MAX_STOPS, stopList.size());
+ for(Palina p: stopList.subList(0,maxNum)){
+ //if there are no routes available, skip stop
+ if(p.queryAllRoutes().size() == 0) continue;
+ for(Route r: p.queryAllRoutes()){
+ //if there are no routes, should not do anything
+ routesPairList.add(new Pair<>(p,r));
+ }
+ }
+ //TODO: Sort pairs based on position and arrival times
+ }
+
+ public void setUserPosition(@Nullable Location userPosition) {
+ this.userPosition = userPosition;
+ }
+
+ public void setRoutesPairListAndPosition(List<Pair<Stop, Route>> routesPairList, @Nullable Location pos) {
+ if(routesPairList!=null)
+ this.routesPairList = routesPairList;
+ if(pos!=null){
+ this.userPosition = pos;
+ }
+ Collections.sort(this.routesPairList,new RoutePositionSorter(userPosition));
+
+ }
+
+ /*
+ @Override
+ public Stop getItem(int position) {
+ return stops.get(position);
+ }
+ */
+ class RoutePositionSorter implements Comparator<Pair<Stop,Route>>{
+ private final Location loc;
+ private final double minutialmetro = 6.0/100; //v = 5km/h
+ private final double distancemultiplier = 1./2;
+ public RoutePositionSorter(Location loc) {
+ this.loc = loc;
+ }
+
+ @Override
+ public int compare(Pair<Stop, Route> pair1, Pair<Stop, Route> pair2) throws NullPointerException{
+ int delta = 0;
+ final Stop stop1 = pair1.first, stop2 = pair2.first;
+ double dist1 = utils.measuredistanceBetween(loc.getLatitude(),loc.getLongitude(),
+ stop1.getLatitude(),stop1.getLongitude());
+ double dist2 = utils.measuredistanceBetween(loc.getLatitude(),loc.getLongitude(),
+ stop2.getLatitude(),stop2.getLongitude());
+ final List<Passaggio> passaggi1 = pair1.second.passaggi,
+ passaggi2 = pair2.second.passaggi;
+ if(passaggi1.size()<=0 || passaggi2.size()<=0){
+ Log.e("ArrivalsStopAdapter","Cannot compare: No arrivals in one of the stops");
+ } else {
+ Collections.sort(passaggi1);
+ Collections.sort(passaggi2);
+ int deltaOre = passaggi1.get(0).hh-passaggi2.get(0).hh;
+ if(deltaOre>12)
+ deltaOre -= 24;
+ else if (deltaOre<-12)
+ deltaOre += 24;
+ delta+=deltaOre*60 + passaggi1.get(0).mm-passaggi2.get(0).mm;
+ }
+ delta += (int)((dist1 -dist2)*minutialmetro*distancemultiplier);
+ return delta;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return obj instanceof RoutePositionSorter;
+ }
+ }
+}
diff --git a/src/it/reyboz/bustorino/adapters/PalinaAdapter.java b/src/it/reyboz/bustorino/adapters/PalinaAdapter.java
index 4dfa4a05..f16bade7 100644
--- a/src/it/reyboz/bustorino/adapters/PalinaAdapter.java
+++ b/src/it/reyboz/bustorino/adapters/PalinaAdapter.java
@@ -1,149 +1,144 @@
/*
BusTO (backend components)
Copyright (C) 2016 Ludovico Pavesi
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
-import java.util.List;
+ import java.util.List;
import it.reyboz.bustorino.R;
import it.reyboz.bustorino.backend.Palina;
import it.reyboz.bustorino.backend.Passaggio;
import it.reyboz.bustorino.backend.Route;
/**
* This once was a ListView Adapter for BusLine[].
*
* Thanks to Framentos developers for the guide:
* http://www.framentos.com/en/android-tutorial/2012/07/16/listview-in-android-using-custom-listadapter-and-viewcache/#
*
* @author Valerio Bozzolan
* @author Ludovico Pavesi
*/
public class PalinaAdapter extends ArrayAdapter<Route> {
private LayoutInflater li;
private static int row_layout = R.layout.entry_bus_line_passage;
private static final int metroBg = R.drawable.route_background_metro;
private static final int busBg = R.drawable.route_background_bus;
private static final int extraurbanoBg = R.drawable.route_background_bus_long_distance;
private static final int busIcon = R.drawable.bus;
private static final int trainIcon = R.drawable.subway;
private static final int tramIcon = R.drawable.tram;
//private static final int cityIcon = R.drawable.city;
// hey look, a pattern!
private static class ViewHolder {
TextView rowStopIcon;
TextView rowRouteDestination;
TextView rowRouteTimetable;
}
public PalinaAdapter(Context context, Palina p) {
super(context, row_layout, p.queryAllRoutes());
li = LayoutInflater.from(context);
}
/**
* Some parts taken from the AdapterBusLines class.<br>
* Some parts inspired by these enlightening tutorials:<br>
* http://www.simplesoft.it/android/guida-agli-adapter-e-le-listview-in-android.html<br>
* https://www.codeofaninja.com/2013/09/android-viewholder-pattern-example.html<br>
* And some other bits and bobs TIRATI FUORI DAL NULLA CON L'INTUIZIONE INTELLETTUALE PERCHÉ
* SEMBRA CHE NESSUNO ABBIA LA MINIMA IDEA DI COME FUNZIONA UN ADAPTER SU ANDROID.
*/
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
ViewHolder vh;
if(convertView == null) {
// INFLATE!
// setting a parent here is not supported and causes a fatal exception, apparently.
convertView = li.inflate(row_layout, null);
// STORE TEXTVIEWS!
vh = new ViewHolder();
vh.rowStopIcon = (TextView) convertView.findViewById(R.id.routeID);
vh.rowRouteDestination = (TextView) convertView.findViewById(R.id.routeDestination);
vh.rowRouteTimetable = (TextView) convertView.findViewById(R.id.routesThatStopHere);
// STORE VIEWHOLDER IN\ON\OVER\UNDER\ABOVE\BESIDE THE VIEW!
convertView.setTag(vh);
} else {
// RECOVER THIS STUFF!
vh = (ViewHolder) convertView.getTag();
}
Route route = getItem(position);
- vh.rowStopIcon.setText(route.name);
+ vh.rowStopIcon.setText(route.getNameForDisplay());
if(route.destinazione==null || route.destinazione.length() == 0) {
vh.rowRouteDestination.setVisibility(View.GONE);
} else {
// View Holder Pattern(R) renders each element from a previous one: if the other one had an invisible rowRouteDestination, we need to make it visible.
vh.rowRouteDestination.setVisibility(View.VISIBLE);
vh.rowRouteDestination.setText(route.destinazione);
}
switch (route.type) {
case BUS:
default:
// convertView could contain another background, reset it
vh.rowStopIcon.setBackgroundResource(busBg);
vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0);
break;
case LONG_DISTANCE_BUS:
vh.rowStopIcon.setBackgroundResource(extraurbanoBg);
vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0);
break;
case METRO:
vh.rowStopIcon.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
vh.rowStopIcon.setBackgroundResource(metroBg);
vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(trainIcon, 0, 0, 0);
break;
case RAILWAY:
vh.rowStopIcon.setBackgroundResource(busBg);
vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(trainIcon, 0, 0, 0);
break;
case TRAM: // never used but whatever.
vh.rowStopIcon.setBackgroundResource(busBg);
vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(tramIcon, 0, 0, 0);
break;
}
List<Passaggio> passaggi = route.passaggi;
if(passaggi.size() == 0) {
vh.rowRouteTimetable.setText(R.string.no_passages);
} else {
- String resultString = "";
- for(Passaggio passaggio : passaggi) {
- // "+" calls concat() and some other stuff internally, this should be faster
- resultString = resultString.concat(passaggio.toString()).concat(" ");
- }
- vh.rowRouteTimetable.setText(resultString);
+ vh.rowRouteTimetable.setText(route.getPassaggiToString());
}
return convertView;
}
}
diff --git a/src/it/reyboz/bustorino/backend/Fetcher.java b/src/it/reyboz/bustorino/backend/Fetcher.java
index 789fdd90..3477457b 100644
--- a/src/it/reyboz/bustorino/backend/Fetcher.java
+++ b/src/it/reyboz/bustorino/backend/Fetcher.java
@@ -1,36 +1,36 @@
/*
BusTO (backend components)
Copyright (C) 2016 Ludovico Pavesi
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.backend;
public interface Fetcher {
/**
* Status codes.<br>
*<br>
* OK: got a response, parsed correctly, obtained some data<br>
* CLIENT_OFFLINE: can't connect to the internet<br>
* SERVER_ERROR: the server replied anything other than HTTP 200, basically<br>
* for 404 special constant (see @FiveTAPIFetcher)
* PARSER_ERROR: the server replied something that can't be parsed, probably it's not the data we're looking for (e.g. "PHP: Fatal Error")<br>
* EMPTY_RESULT_SET: the response is valid and indicates there are no stops\routes\"passaggi"\results for your query<br>
* QUERY_TOO_SHORT: input more characters and retry.
*/
enum result {
- OK, CLIENT_OFFLINE, SERVER_ERROR, PARSER_ERROR, EMPTY_RESULT_SET, QUERY_TOO_SHORT,SERVER_ERROR_404
+ OK, CLIENT_OFFLINE, SERVER_ERROR, SETUP_ERROR,PARSER_ERROR, EMPTY_RESULT_SET, QUERY_TOO_SHORT,SERVER_ERROR_404
}
}
diff --git a/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java b/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java
index c7c46cbb..5394a67f 100644
--- a/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java
+++ b/src/it/reyboz/bustorino/backend/FiveTAPIFetcher.java
@@ -1,387 +1,419 @@
/*
BusTO - Backend components
Copyright (C) 2018 Fabio Mazza
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.backend;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
public class FiveTAPIFetcher implements ArrivalsFetcher{
private static final String SECRET_KEY="759C97DC7D115966C30FD9169BB200D9";
private static final String DEBUG_NAME = "FiveTAPIFetcher";
final static LinkedList<String> apiDays = new LinkedList<>(Arrays.asList("dom","lun","mar","mer","gio","ven","sab"));
@Override
public Palina ReadArrivalTimesAll(String stopID, AtomicReference<result> res) {
//set the date for the request as now
Palina p = new Palina(stopID);
//request parameters
String response = performAPIRequest(QueryType.ARRIVALS,stopID,res);
if(response==null) {
if(res.get()==result.SERVER_ERROR_404) {
Log.w(DEBUG_NAME,"Got 404, either the server failed, or the stop was not found, or the hack is not working anymore");
res.set(result.EMPTY_RESULT_SET);
};
return p;
}
+ List<Route> routes = parseArrivalsServerResponse(response,res);
+ for(Route r: routes){
+ p.addRoute(r);
+ }
+ res.set(result.OK);
+ p.sortRoutes();
+ return p;
+ }
+
+ List<Route> parseArrivalsServerResponse(String JSONresponse, AtomicReference<result> res){
+ ArrayList<Route> routes = new ArrayList<>(3);
/*
Slight problem:
"longName": ==> DESCRIPTION
"name": "13N",
"departures": [
{
"arrivalTimeInt": 1272,
"time": "21:12",
"rt": false
}]
"lineType": "URBANO" ==> URBANO can be either bus or tram or METRO
*/
JSONArray arr;
try{
- arr = new JSONArray(response);
+ arr = new JSONArray(JSONresponse);
String type;
Route.Type routetype;
for(int i =0; i<arr.length();i++){
JSONObject lineJSON = arr.getJSONObject(i);
type = lineJSON.getString("lineType");
String lineName=FiveTNormalizer.routeDisplayToInternal(lineJSON.getString("name"));
//set the type of line
if(type.equals("EXTRA"))
routetype = Route.Type.LONG_DISTANCE_BUS;
else routetype = Route.Type.BUS;
//Cut out the spaces in the line Name
//temporary fix
//lineName = lineName.replace(" ","").replace("/","B");
//TODO: parse the line description
Route r = new Route(lineName,routetype,lineJSON.getString("longName"));
- Log.d(DEBUG_NAME,"Creating line with name "+lineJSON.getString("name")+" and description "+lineJSON.getString("longName"));
+ //Log.d(DEBUG_NAME,"Creating line with name "+lineJSON.getString("name")+" and description "+lineJSON.getString("longName"));
final JSONArray passagesJSON = lineJSON.getJSONArray("departures");
for(int j=0;j<passagesJSON.length();j++){
final JSONObject arrival = passagesJSON.getJSONObject(j);
final String passaggio = Passaggio.createPassaggioGTT(arrival.getString("time"),arrival.getBoolean("rt"));
r.addPassaggio(passaggio, Passaggio.Source.FiveTAPI);
//Log.d(DEBUG_NAME,"Adding passage with time "+arrival.getString("time")+"\nrealtime="+arrival.getBoolean("rt"));
}
- p.addRoute(r);
+ routes.add(r);
}
} catch (JSONException e) {
e.printStackTrace();
res.set(result.PARSER_ERROR);
- return p;
+ return routes;
}
- p.sortRoutes();
+ Collections.sort(routes);
res.set(result.OK);
- return p;
+ return routes;
}
- public List<Route> getDirectionsForStop(String stopID, AtomicReference<result> res) {
- String response = performAPIRequest(QueryType.DETAILS,stopID,res);
- if(response == null) return null;
+ public List<Route> parseDirectionsFromResponse(String response) throws IllegalArgumentException,JSONException{
+ if(response == null || response.length()==0) throw new IllegalArgumentException("Response string is null or void");
ArrayList<Route> routes = new ArrayList<>(10);
-
- try {
JSONArray lines =new JSONArray(response);
for(int i=0; i<lines.length();i++){
Route.FestiveInfo festivo = Route.FestiveInfo.UNKNOWN;
final JSONObject branchJSON = lines.getJSONObject(i);
int branchid = branchJSON.getInt("branch");
String description = branchJSON.getString("description");
String direction = branchJSON.getString("direction");
String stops = branchJSON.getJSONObject("branchDetail").getString("stops");
String lineName = branchJSON.getString("lineName");
Route.Type t = null;
//parsing description
String[] exploded = description.split(",");
description = exploded[exploded.length-1]; //the real description
int[] serviceDays = {};
if(exploded.length > 1) {
String secondo = exploded[exploded.length-2];
if (secondo.contains("festivo")) {
festivo = Route.FestiveInfo.FESTIVO;
} else if (secondo.contains("feriale")) {
festivo = Route.FestiveInfo.FERIALE;
} else if(secondo.contains("lun. - ven")) {
serviceDays = Route.reduced_week;
} else if(secondo.contains("sab - fest.")){
serviceDays = Route.weekend;
festivo = Route.FestiveInfo.FESTIVO;
} else {
+ /*
Log.d(DEBUG_NAME,"Parsing details of line "+lineName+" branchid "+branchid+":\n\t"+
- "Couldn't find a the service days\n"+
- "Description: "+secondo+","+description
+ "Couldn't find a the service days\n"+
+ "Description: "+secondo+","+description
);
+ */
}
if(exploded.length>2){
switch (exploded[exploded.length-3].trim()) {
case "bus":
t = Route.Type.BUS;
break;
case "tram":
//never happened, but if it could happen you can get it
t = Route.Type.TRAM;
break;
default:
//nothing
}
}
} else //only one piece
if(description.contains("festivo")){
festivo = Route.FestiveInfo.FESTIVO;
} else if(description.contains("feriale")){
festivo = Route.FestiveInfo.FERIALE;
}
if(t == null &&(lineName.trim().equals("10")|| lineName.trim().equals("15"))) t= Route.Type.TRAM;
if(direction.contains("-")){
//Sometimes the actual filtered direction is instead the full line (including both extremes)
direction = direction.split("-")[1];
}
- Route r = new Route(lineName.trim(),direction.trim(),t,null);
+ Route r = new Route(lineName.trim(),direction.trim(),t,new ArrayList<>());
if(serviceDays.length>0) r.serviceDays = serviceDays;
r.festivo = festivo;
r.branchid = branchid;
r.description = description.trim();
r.setStopsList(Arrays.asList(stops.split(",")));
routes.add(r);
}
- res.set(result.OK);
+ return routes;
+ }
+
+ public List<Route> getDirectionsForStop(String stopID, AtomicReference<result> res) {
+ String response = performAPIRequest(QueryType.DETAILS,stopID,res);
+ List<Route> routes;
+ try{
+ routes = parseDirectionsFromResponse(response);
+ res.set(result.OK);
} catch (JSONException e) {
- res.set(result.PARSER_ERROR);
e.printStackTrace();
- return null;
+ res.set(result.PARSER_ERROR);
+ routes = null;
}
return routes;
}
public ArrayList<Stop> getAllStopsFromGTT(AtomicReference<result> res){
String response = performAPIRequest(QueryType.STOPS_ALL,null,res);
if(response==null) return null;
ArrayList<Stop> stopslist = null;
try{
JSONObject responseJSON = new JSONObject(response);
JSONArray stops = responseJSON.getJSONArray("stops");
stopslist = new ArrayList<>(stops.length());
for (int i=0;i<stops.length();i++){
JSONObject currentStop = stops.getJSONObject(i);
String location = currentStop.getString("location");
if(location.trim().equals("_")) location = null;
String placeName = currentStop.getString("placeName");
if(placeName.trim().equals("_")) placeName = null;
String[] lines = currentStop.getString("lines").split(",");
for(int l = 0; l<lines.length;l++){
lines[l] = FiveTNormalizer.routeDisplayToInternal(lines[l]);
}
Route.Type t;
switch (currentStop.getString("type")){
case "BUS":
t = Route.Type.BUS;
break;
case "METRO":
t = Route.Type.METRO;
break;
case "TRENO":
t = Route.Type.RAILWAY;
break;
default:
t = null;
}
Stop s = new Stop(currentStop.getString("id"),
currentStop.getString("name"),null,location,t,Arrays.asList(lines),
Double.parseDouble(currentStop.getString("lat")),
Double.parseDouble(currentStop.getString("lng")));
if(placeName!=null)
s.setAbsurdGTTPlaceName(placeName);
stopslist.add(s);
}
res.set(result.OK);
} catch (JSONException e) {
e.printStackTrace();
res.set(result.PARSER_ERROR);
return null;
}
return stopslist;
}
+
@Nullable
public ArrayList<Route> getAllLinesFromGTT(AtomicReference<result> res){
String resp = performAPIRequest(QueryType.LINES,null,res);
if(resp==null) {
return null;
}
ArrayList<Route> routes = null;
try {
JSONArray lines = new JSONArray(resp);
routes = new ArrayList<>(lines.length());
for(int i = 0; i<lines.length(); i++) {
JSONObject lineJ = lines.getJSONObject(i);
Route.Type t = null;
switch(lineJ.getString("azienda")){
case "EXTRA":
t = Route.Type.LONG_DISTANCE_BUS;
break;
case "URBANO":
t = Route.Type.BUS;
break;
case "FERRO":
t = Route.Type.RAILWAY;
break;
}
String name = lineJ.getString("name");
routes.add(new Route(name,t,lineJ.getString("longName")));
}
//finish
res.set(result.OK);
} catch (JSONException e) {
e.printStackTrace();
res.set(result.PARSER_ERROR);
return routes;
}
return routes;
}
+ /**
+ * Useful to get all the headers for the GTT server
+ * @param url of the request
+ * @return the request headers
+ * @throws UnsupportedEncodingException from inner method
+ * @throws NoSuchAlgorithmException from inner methods
+ */
+ public static Map<String,String> getHeadersForRequest(String url) throws UnsupportedEncodingException, NoSuchAlgorithmException {
+ final Date d = new Date();
+ HashMap<String, String> param = new HashMap<>();
+ param.put("TOKEN",getAccessToken(url,d));
+ param.put("TIMESTAMP",String.valueOf(d.getTime()));
+ param.put("Accept-Encoding","gzip");
+ param.put("Connection","Keep-Alive");
+ return param;
+
+ }
/**
* Create and perform the network request. This method adds parameters and returns the result
* @param t type of request to be performed
* @param stopID optional parameter, stop ID which you need for passages and branches
* @param res result container
* @return a String which contains the result of the query, to be parsed
*/
@Nullable
public static String performAPIRequest(QueryType t,@Nullable String stopID, AtomicReference<result> res){
- Date d = new Date();
URL u;
- Hashtable<String,String> param = new Hashtable<>();
+ Map<String,String> param;
try {
String address = getURLForOperation(t,stopID);
//Log.d(DEBUG_NAME,"The address to query is: "+address);
- param.put("TOKEN",getAccessToken(address,d));
- param.put("TIMESTAMP",String.valueOf(d.getTime()));
- param.put("Accept-Encoding","gzip");
- param.put("Connection","Keep-Alive");
+ param = getHeadersForRequest(address);
u = new URL(address);
} catch (UnsupportedEncodingException | NoSuchAlgorithmException |MalformedURLException e) {
e.printStackTrace();
res.set(result.PARSER_ERROR);
return null;
}
String response = networkTools.queryURL(u,res,param);
return response;
}
/**
* Get the Token needed to access the API
* @param URL the URL of the request
* @return token
* @throws NoSuchAlgorithmException if the system doesn't support MD5
* @throws UnsupportedEncodingException if we made mistakes in writing utf-8
*/
private static String getAccessToken(String URL,Date d) throws NoSuchAlgorithmException,UnsupportedEncodingException{
MessageDigest md = MessageDigest.getInstance("MD5");
String strippedQuery = URL.replace("http://www.5t.torino.it/proxyws","");
//return the time in milliseconds
long timeMilli = d.getTime();
StringBuilder sb = new StringBuilder();
sb.append(strippedQuery);
sb.append(timeMilli);
sb.append(SECRET_KEY);
String stringToBeHashed = sb.toString();
//Log.d(DEBUG_NAME,"Hashing string: "+stringToBeHashed);
md.reset();
byte[] data = md.digest(stringToBeHashed.getBytes("UTF-8"));
sb = new StringBuilder();
for (byte b : data){
sb.append(String.format("%02x",b));
}
String result = sb.toString();
//Log.d(DEBUG_NAME,"getting token:\n\treduced URL: "+strippedQuery+"\n\ttimestamp: "+timeMilli+"\nTOKEN:"+result.toLowerCase());
return result.toLowerCase();
}
/**
* Get the right url for the operation you are doing, to be fed into the queryURL method
* @param t type of operation
* @param stopID stop on which you are working on
* @return the Url to go to
* @throws UnsupportedEncodingException if it cannot be converted to utf-8
*/
- private static String getURLForOperation(QueryType t,@Nullable String stopID) throws UnsupportedEncodingException {
+ public static String getURLForOperation(QueryType t,@Nullable String stopID) throws UnsupportedEncodingException {
final StringBuilder sb = new StringBuilder();
sb.append("http://www.5t.torino.it/proxyws/ws2.1/rest/");
if(t!=QueryType.LINES) sb.append("stops/");
switch (t){
case ARRIVALS:
sb.append(URLEncoder.encode(stopID,"utf-8"));
sb.append("/departures");
break;
case DETAILS:
sb.append(URLEncoder.encode(stopID,"utf-8"));
sb.append("/branches/details");
break;
case STOPS_ALL:
sb.append("all");
break;
case STOPS_VERSION:
sb.append("version");
break;
case LINES:
sb.append("lines/all");
break;
}
return sb.toString();
}
public enum QueryType {
ARRIVALS, DETAILS,STOPS_ALL, STOPS_VERSION,LINES
}
}
diff --git a/src/it/reyboz/bustorino/backend/FiveTAPIVolleyRequest.java b/src/it/reyboz/bustorino/backend/FiveTAPIVolleyRequest.java
new file mode 100644
index 00000000..186e7f1d
--- /dev/null
+++ b/src/it/reyboz/bustorino/backend/FiveTAPIVolleyRequest.java
@@ -0,0 +1,136 @@
+/*
+ BusTO - Backend components
+ Copyright (C) 2019 Fabio Mazza
+
+ 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 3 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, see <http://www.gnu.org/licenses/>.
+ */
+
+package it.reyboz.bustorino.backend;
+
+import android.support.annotation.Nullable;
+import android.util.Log;
+import com.android.volley.*;
+import com.android.volley.toolbox.HttpHeaderParser;
+import org.json.JSONException;
+
+import java.io.UnsupportedEncodingException;
+import java.security.NoSuchAlgorithmException;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Class to handle request with the Volley Library
+ */
+public class FiveTAPIVolleyRequest extends Request<Palina> {
+ private static final String LOG_TAG = "BusTO-FiveTAPIVolleyReq";
+
+ private ResponseListener listener;
+ final private String url,stopID;
+ final private AtomicReference<Fetcher.result> resultRef;
+ final private FiveTAPIFetcher fetcher;
+ final private FiveTAPIFetcher.QueryType type;
+
+
+
+ private FiveTAPIVolleyRequest(int method, String url, String stopID, FiveTAPIFetcher.QueryType kind,
+ ResponseListener listener,
+ @Nullable Response.ErrorListener errorListener) {
+ super(method, url, errorListener);
+ this.url = url;
+ this.resultRef = new AtomicReference<>();
+ this.fetcher = new FiveTAPIFetcher();
+ this.listener = listener;
+ this.stopID = stopID;
+ this.type = kind;
+ }
+
+ @Nullable
+ public static FiveTAPIVolleyRequest getNewRequest(FiveTAPIFetcher.QueryType type, String stopID,
+ ResponseListener listener, @Nullable Response.ErrorListener errorListener){
+ String url;
+ try {
+ url = FiveTAPIFetcher.getURLForOperation(type,stopID);
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ Log.e(LOG_TAG,"Cannot get an URL for the operation");
+ return null;
+ }
+ return new FiveTAPIVolleyRequest(Method.POST,url,stopID,type,listener,errorListener);
+ }
+
+ @Override
+ protected Response<Palina> parseNetworkResponse(NetworkResponse response) {
+ if(response.statusCode != 200)
+ return Response.error(new VolleyError("Response Error Code "+response.statusCode));
+ final String stringResponse = new String(response.data);
+ List<Route> routeList;
+ switch (type){
+ case ARRIVALS:
+ routeList = fetcher.parseArrivalsServerResponse(stringResponse,resultRef);
+ break;
+ case DETAILS:
+ try {
+ routeList = fetcher.parseDirectionsFromResponse(stringResponse);
+ } catch (JSONException e) {
+ resultRef.set(Fetcher.result.PARSER_ERROR);
+ e.printStackTrace();
+ return Response.error(new ParseError());
+ }
+ break;
+ default:
+ //empty
+ return Response.error(new VolleyError("Invalid query type"));
+ }
+ if(resultRef.get()== Fetcher.result.PARSER_ERROR){
+ return Response.error(new ParseError());
+ }
+ final Palina p = new Palina(stopID);
+ p.setRoutes(routeList);
+ p.sortRoutes();
+ return Response.success(p, HttpHeaderParser.parseCacheHeaders(response));
+ }
+
+ @Override
+ protected void deliverResponse(Palina p) {
+ listener.onResponse(p,type);
+ }
+
+ @Override
+ public Map<String, String> getHeaders() throws AuthFailureError {
+ Map<String,String> headers;
+ try{
+ headers = FiveTAPIFetcher.getHeadersForRequest(url);
+ } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ throw new AuthFailureError("Cannot get the token for the authorization");
+ }
+ return headers;
+ }
+ //from https://stackoverflow.com/questions/21867929/android-how-handle-message-error-from-the-server-using-volley
+ @Override
+ protected VolleyError parseNetworkError(VolleyError volleyError){
+ if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
+ volleyError = new NetworkError(volleyError.networkResponse);
+ }
+
+ return volleyError;
+ }
+
+ public interface ResponseListener{
+ void onResponse(Palina result, FiveTAPIFetcher.QueryType type);
+ }
+
+ //public interface ErrorListener extends Response.ErrorListener{}
+}
diff --git a/src/it/reyboz/bustorino/backend/NetworkVolleyManager.java b/src/it/reyboz/bustorino/backend/NetworkVolleyManager.java
new file mode 100644
index 00000000..dd416b82
--- /dev/null
+++ b/src/it/reyboz/bustorino/backend/NetworkVolleyManager.java
@@ -0,0 +1,49 @@
+/*
+ BusTO (networking components)
+ Copyright (C) 2019 Fabio Mazza
+
+ 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 3 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, see <http://www.gnu.org/licenses/>.
+ */
+package it.reyboz.bustorino.backend;
+
+import android.content.Context;
+import com.android.volley.Request;
+import com.android.volley.RequestQueue;
+import com.android.volley.toolbox.Volley;
+
+public class NetworkVolleyManager {
+ private RequestQueue reqQueue;
+ private static NetworkVolleyManager instance;
+ private static Context context;
+ public final static int DEFAULT_CACHE_SIZE = 1024;
+
+ private NetworkVolleyManager(Context ctx) {
+ context = ctx.getApplicationContext();
+ }
+
+ public static synchronized NetworkVolleyManager getInstance(Context ctx){
+ if(instance==null) instance = new NetworkVolleyManager(ctx.getApplicationContext());
+ return instance;
+ }
+ public RequestQueue getRequestQueue(){
+ if(reqQueue==null) {
+ //Instantiate the queue
+ reqQueue = Volley.newRequestQueue(context);
+ }
+ return reqQueue;
+ }
+ public <Typ> void addToRequestQueue(Request<Typ> req){
+ getRequestQueue().add(req);
+ }
+}
diff --git a/src/it/reyboz/bustorino/backend/Palina.java b/src/it/reyboz/bustorino/backend/Palina.java
index a3495e20..62e02314 100644
--- a/src/it/reyboz/bustorino/backend/Palina.java
+++ b/src/it/reyboz/bustorino/backend/Palina.java
@@ -1,305 +1,317 @@
/*
BusTO (backend components)
Copyright (C) 2016 Ludovico Pavesi
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.backend;
import android.util.Log;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
/**
* Timetable for multiple routes.<br>
* <br>
* Apparently "palina" and a bunch of other terms can't really be translated into English.<br>
* Not in a way that makes sense and keeps the code readable, at least.
*/
public class Palina extends Stop {
private ArrayList<Route> routes = new ArrayList<>();
public Palina(String stopID) {
super(stopID);
}
-
- /**
- * Adds a route to the timetable.
- *
- * @param routeID name
- * @param type bus, underground, railway, ...
- * @param destinazione end of line\terminus (underground stations have the same ID for both directions)
- * @return array index for this route
- */
- public int addRoute(String routeID, String destinazione, Route.Type type) {
- this.routes.add(new Route(routeID, destinazione, type, new ArrayList<Passaggio>(6)));
- return this.routes.size() - 1; // last inserted element and pray that direct access to ArrayList elements really is direct
- }
- public int addRoute(Route r){
- this.routes.add(r);
- return this.routes.size()-1;
+ public Palina(Stop s){
+ super(s.ID,s.getStopDefaultName(),s.getStopUserName(),s.location,s.type,
+ s.getRoutesThatStopHere(),s.getLatitude(),s.getLongitude());
}
+
/**
* Adds a timetable entry to a route.
*
* @param TimeGTT time in GTT format (e.g. "11:22*")
* @param arrayIndex position in the array for this route (returned by addRoute)
*/
public void addPassaggio(String TimeGTT, Passaggio.Source src,int arrayIndex) {
this.routes.get(arrayIndex).addPassaggio(TimeGTT,src);
}
/**
* Count routes with missing directions
* @return number
*/
public int countRoutesWithMissingDirections(){
int i = 0;
for (Route r : routes){
if(r.destinazione==null||r.destinazione.equals(""))
i++;
}
return i;
}
+
+ /**
+ * Adds a route to the timetable.
+ *
+ * @param routeID name
+ * @param type bus, underground, railway, ...
+ * @param destinazione end of line\terminus (underground stations have the same ID for both directions)
+ * @return array index for this route
+ */
+ public int addRoute(String routeID, String destinazione, Route.Type type) {
+ this.routes.add(new Route(routeID, destinazione, type, new ArrayList<Passaggio>(6)));
+ return this.routes.size() - 1; // last inserted element and pray that direct access to ArrayList elements really is direct
+ }
+ public int addRoute(Route r){
+ this.routes.add(r);
+ return this.routes.size()-1;
+ }
+ public void setRoutes(List<Route> routeList){
+ routes = new ArrayList<>(routeList);
+ }
+
+
// /**
// * Clears a route timetable (or creates an empty route) and returns its index
// *
// * @param routeID name
// * @param destinazione end of line\terminus
// * @return array index for this route
// */
// public int updateRoute(String routeID, String destinazione) {
// int s = this.routes.size();
// RouteInternal r;
//
// for(int i = 0; i < s; i++) {
// r = routes.get(i);
// if(r.name.compareTo(routeID) == 0 && r.destinazione.compareTo(destinazione) == 0) {
// // capire se è possibile che ci siano stessa linea e stessa destinazione su 2 righe diverse del sito e qui una sovrascrive l'altra (probabilmente no)
// r.updateFlag();
// r.deletePassaggio();
// return i;
// }
// }
//
// return this.addRoute(routeID, destinazione);
// }
//
// /**
// * Deletes routes marked as "not updated" (= disappeared from the GTT website\API\whatever).
// * Sets all remaining routes to "not updated" because that's how this contraption works.
// */
// public void finishUpdatingRoutes() {
// RouteInternal r;
//
// for(Iterator<RouteInternal> itr = this.routes.iterator(); itr.hasNext(); ) {
// r = itr.next();
// if(r.unupdateFlag()) {
// itr.remove();
// }
// }
// }
// /**
// * Gets the current timetable for a route. Returns null if the route doesn't exist.
// * This is slower than queryRouteByIndex.
// *
// * @return timetable (passaggi)
// */
// public List<Passaggio> queryRoute(String routeID) {
// for(Route r : this.routes) {
// if(routeID.equals(r.name)) {
// return r.getPassaggi();
// }
// }
//
// return null;
// }
//
// /**
// * Gets the current timetable for this route, from its index in the array.
// *
// * @return timetable (passaggi)
// */
// public List<Passaggio> queryRouteByIndex(int index) {
// return this.routes.get(index).getPassaggi();
// }
/**
* Gets every route and its timetable.
*
* @return routes and timetables.
*/
public List<Route> queryAllRoutes() {
return this.routes;
}
public void sortRoutes() {
Collections.sort(this.routes);
}
/**
* Add info about the routes already found from another source
* @param additionalRoutes ArrayList of routes to get the info from
* @return the number of routes modified
*/
public int addInfoFromRoutes(List<Route> additionalRoutes){
if(routes == null || routes.size()==0) {
this.routes = new ArrayList<>(additionalRoutes);
return routes.size();
}
int count=0;
final Calendar c = Calendar.getInstance();
final int todaysInt = c.get(Calendar.DAY_OF_WEEK);
for(Route r:routes) {
int j = 0;
boolean correct = false;
Route selected = null;
//TODO: rewrite this as a simple loop
//MADNESS begins here
while (!correct) {
//find the correct route to merge to
// scan routes and find the first which has the same name
- while (j < additionalRoutes.size() && !r.name.equals(additionalRoutes.get(j).name)) {
+ while (j < additionalRoutes.size() && !r.getName().equals(additionalRoutes.get(j).getName())) {
j++;
}
if (j == additionalRoutes.size()) break; //no match has been found
//should have found the first occurrence of the line
selected = additionalRoutes.get(j);
//move forward
j++;
if (selected.serviceDays != null && selected.serviceDays.length > 0) {
//check if it is in service
for (int d : selected.serviceDays) {
if (d == todaysInt) {
correct = true;
break;
}
}
} else if (r.festivo != null) {
switch (r.festivo) {
case FERIALE:
//Domenica = 1 --> Saturday=7
if (todaysInt <= 7 && todaysInt > 1) correct = true;
break;
case FESTIVO:
if (todaysInt == 1) correct = true; //TODO: implement way to recognize all holidays
break;
case UNKNOWN:
correct = true;
}
} else {
//case a: there is no info because the line is always active
//case b: there is no info because the information is missing
correct = true;
}
}
if (!correct || selected == null) {
- Log.w("Palina_mergeRoutes","Cannot match the route with name "+r.name);
+ Log.w("Palina_mergeRoutes","Cannot match the route with name "+r.getName());
continue; //we didn't find any match
}
//found the correct correspondance
//MERGE INFO
if(r.mergeRouteWithAnother(selected)) count++;
}
return count;
}
+
+
// /**
// * Route with terminus (destinazione) and timetables (passaggi), internal implementation.
// *
// * Contains mostly the same data as the Route public class, but methods are quite different and extending Route doesn't really work, here.
// */
// private final class RouteInternal {
// public final String name;
// public final String destinazione;
// private boolean updated;
// private List<Passaggio> passaggi;
//
// /**
// * Creates a new route and marks it as "updated", since it's new.
// *
// * @param routeID name
// * @param destinazione end of line\terminus
// */
// public RouteInternal(String routeID, String destinazione) {
// this.name = routeID;
// this.destinazione = destinazione;
// this.passaggi = new LinkedList<>();
// this.updated = true;
// }
//
// /**
// * Adds a time (passaggio) to the timetable for this route
// *
// * @param TimeGTT time in GTT format (e.g. "11:22*")
// */
// public void addPassaggio(String TimeGTT) {
// this.passaggi.add(new Passaggio(TimeGTT));
// }
//
// /**
// * Deletes al times (passaggi) from the timetable.
// */
// public void deletePassaggio() {
// this.passaggi = new LinkedList<>();
// this.updated = true;
// }
//
// /**
// * Sets the "updated" flag to false.
// *
// * @return previous state
// */
// public boolean unupdateFlag() {
// if(this.updated) {
// this.updated = false;
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Sets the "updated" flag to true.
// *
// * @return previous state
// */
// public boolean updateFlag() {
// if(this.updated) {
// return true;
// } else {
// this.updated = true;
// return false;
// }
// }
//
// /**
// * Exactly what it says on the tin.
// *
// * @return times from the timetable
// */
// public List<Passaggio> getPassaggi() {
// return this.passaggi;
// }
// }
}
\ No newline at end of file
diff --git a/src/it/reyboz/bustorino/backend/Route.java b/src/it/reyboz/bustorino/backend/Route.java
index c58628cc..dae1d801 100644
--- a/src/it/reyboz/bustorino/backend/Route.java
+++ b/src/it/reyboz/bustorino/backend/Route.java
@@ -1,281 +1,356 @@
/*
BusTO (backend components)
Copyright (C) 2016 Ludovico Pavesi
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.backend;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
public class Route implements Comparable<Route> {
final static int[] reduced_week = {Calendar.MONDAY,Calendar.TUESDAY,Calendar.WEDNESDAY,Calendar.THURSDAY,Calendar.FRIDAY};
final static int[] feriali = {Calendar.MONDAY,Calendar.TUESDAY,Calendar.WEDNESDAY,Calendar.THURSDAY,Calendar.FRIDAY,Calendar.SATURDAY};
final static int[] weekend = {Calendar.SUNDAY,Calendar.SATURDAY};
private final static int BRANCHID_MISSING = -1;
- public final String name;
+ private final String name;
public String destinazione;
public final List<Passaggio> passaggi;
+ //create a copy of the list, so that
+ private List<Passaggio> sortedPassaggi;
public final Type type;
public String description;
//ordered list of stops, from beginning to end of line
private List<String> stopsList = null;
public int branchid = BRANCHID_MISSING;
public int[] serviceDays ={};
//0=>feriale, 1=>festivo -2=>unknown
public FestiveInfo festivo = FestiveInfo.UNKNOWN;
public enum Type { // "long distance" sono gli extraurbani.
BUS(1), LONG_DISTANCE_BUS(2), METRO(3), RAILWAY(4), TRAM(5);
//TODO: decide to give some special parameter to each field
private int code;
Type(int code){
this.code = code;
}
public int getCode(){
return this.code;
}
@Nullable
public static Type fromCode(int i){
switch (i){
case 1:
return BUS;
case 2:
return LONG_DISTANCE_BUS;
case 3:
return METRO;
case 4:
return RAILWAY;
case 5:
return TRAM;
default:
return null;
}
}
}
public enum FestiveInfo{
FESTIVO(1),FERIALE(0),UNKNOWN(-2);
private int code;
FestiveInfo(int code){
this.code = code;
}
public int getCode() {
return code;
}
public static FestiveInfo fromCode(int i){
switch (i){
case -2:
return UNKNOWN;
case 0:
return FERIALE;
case 1:
return FESTIVO;
default:
return UNKNOWN;
}
}
}
-
-
/**
* Constructor.
*
* @param name route ID
* @param destinazione terminus\end of line
* @param type bus, long distance bus, underground, and so on
* @param passaggi timetable, a good choice is an ArrayList of size 6
+ * @param description the description of the line, usually given by the FiveTAPIFetcher
* @see Palina Palina.addRoute() method
*/
- public Route(String name, String destinazione, Type type, List<Passaggio> passaggi) {
+ public Route(String name, String destinazione, List<Passaggio> passaggi, Type type, String description) {
this.name = name;
- this.destinazione = destinazione;
+ this.destinazione = parseDestinazione(destinazione);
this.passaggi = passaggi;
this.type = type;
- this.description = null;
+ this.description = description;
+ }
+
+ /**
+ * Constructor used in GTTJSONFetcher, see above
+ */
+ public Route(String name, String destinazione, Type type, List<Passaggio> passaggi) {
+ this(name,destinazione,passaggi,type,null);
}
/**
- * Constructor used by the new Api
+ * Constructor used by the FiveTAPIFetcher
* @param name stop Name
* @param t optional type
* @param description line rough description
*/
public Route(String name,Type t,String description){
- this.name = name;
- this.type = t;
- this.passaggi = new ArrayList<>();
- this.destinazione = null;
- this.description = description;
+ this(name,null,new ArrayList<>(),t,description);
}
/**
* Exactly what it says on the tin.
*
* @return times from the timetable
*/
public List<Passaggio> getPassaggi() {
return this.passaggi;
}
public void setStopsList(List<String> stopsList) {
this.stopsList = Collections.unmodifiableList(stopsList);
}
public List<String> getStopsList(){
return this.stopsList;
}
/**
* Adds a time (passaggio) to the timetable for this route
*
* @param TimeGTT time in GTT format (e.g. "11:22*")
*/
public void addPassaggio(String TimeGTT, Passaggio.Source source) {
this.passaggi.add(new Passaggio(TimeGTT, source));
}
//Overloaded
public void addPassaggio(int hour, int minutes, boolean realtime, Passaggio.Source source) {
this.passaggi.add(new Passaggio(hour, minutes, realtime, source));
}
+ private String parseDestinazione(String direzione){
+ if(direzione==null) return null;
+ //trial to add space to the parenthesis
+ String[] exploded = direzione.split("\\(");
+ if(exploded.length>1){
+ StringBuilder sb = new StringBuilder();
+ sb.append(exploded[0]);
+ for(int i=1; i<exploded.length;i++) {
+ sb.append(" (");
+ sb.append(exploded[i]);
+ }
+ direzione = sb.toString();
+ }
+ return direzione;
+ }
+
+ /**
+ * Getter for the name
+ * @return the name of the line
+ */
+ public String getName() {
+ return name;
+ }
+
+ public String getNameForDisplay(){
+ if(name.trim().equals("101Metrobus")) return "101 Metrobus";
+ else return name;
+ }
+ /**
+ * Get all passaggi in a single string
+ * @return the string
+ */
+ public String getPassaggiToString(){
+ StringBuilder sb = new StringBuilder();
+ for(Passaggio passaggio : passaggi) {
+ // "+" calls concat() and some other stuff internally, this should be faster
+ //StringBuilder is THE WAY
+ sb.append(passaggio.toString());
+ sb.append(" ");
+ }
+ return sb.toString();
+ }
+
+ public String getPassaggiToString(int start_idx, int number, boolean sort){
+ StringBuilder sb = new StringBuilder();
+ List<Passaggio> arrivals;
+ int max;
+ if(sort){
+ if(sortedPassaggi==null){
+ sortedPassaggi = new ArrayList<>(passaggi.size());
+ sortedPassaggi.addAll(passaggi);
+ Collections.sort(sortedPassaggi);
+ }
+ arrivals = sortedPassaggi;
+ } else arrivals = passaggi;
+ if(start_idx+number>arrivals.size())
+ max = arrivals.size();
+ else max = start_idx+number;
+ for(int j= start_idx; j<max;j++) {
+ // "+" calls concat() and some other stuff internally, this should be faster
+ //StringBuilder is THE WAY
+ sb.append(arrivals.get(j).toString());
+ sb.append(" ");
+ }
+ return sb.toString();
+ }
@Override
public int compareTo(@NonNull Route other) {
int res;
int thisAsInt, otherAsInt;
// sorting by numbers alone yields a far more "natural" result (36N goes before 2024, 95B next to 95, and the like)
thisAsInt = networkTools.failsafeParseInt(this.name.replaceAll("[^0-9]", ""));
otherAsInt = networkTools.failsafeParseInt(other.name.replaceAll("[^0-9]", ""));
// compare.
// numeric route IDs (names)
if(thisAsInt != 0 && otherAsInt != 0) {
res = thisAsInt - otherAsInt;
if(res != 0) {
return res;
}
} else {
// non-numeric
res = this.name.compareTo(other.name);
if (res != 0) {
return res;
}
}
// try comparing their destination
if(this.destinazione!=null){
res = this.destinazione.compareTo(other.destinazione);
if(res != 0) {
return res;
}
}
//compare the lines
if(this.stopsList!=null && other.stopsList!=null){
int d = this.stopsList.size()-other.stopsList.size();
if(d!=0) return d;
else {
//the two have the same number of stops
}
}
// probably useless, but... last attempt.
if(this.type != other.type) {
// ordinal() is evil or whatever, who cares.
return this.type.ordinal() - other.type.ordinal();
}
return 0;
}
public boolean isBranchIdValid(){
return branchid!=BRANCHID_MISSING;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Route){
Route r = (Route) obj;
boolean result = false;
if(this.name.equals(r.name) && this.branchid == r.branchid){
if(this.stopsList!=null && r.stopsList!=null){
int d = this.stopsList.size()-r.stopsList.size();
if(d!=0) {
result = false;
} else {
result = true;
for(int j=0; j<this.stopsList.size();j++){
if(!this.stopsList.get(j).equals(r.stopsList.get(j))) {
result = false;
break;
}
}
}
}
}
return result;
} else return false;
}
/**
* Merge informations from another route
* NO CONSISTENCY CHECKS, DO BEFORE CALLING THIS METHOD
* @param other the other route
* @return true if there have been changes
*/
public boolean mergeRouteWithAnother(Route other){
boolean adjusted = false;
if ((other.serviceDays!=null && this.serviceDays!=null && this.serviceDays.length==0)
|| (other.serviceDays!=null && this.serviceDays==null)) {
this.serviceDays = other.serviceDays;
adjusted = true;
}
if (other.getStopsList() != null && this.getStopsList() == null)
this.setStopsList(other.getStopsList());
+
+ if(this.passaggi!=null && other.passaggi!=null && this.passaggi.size()==0 && other.passaggi.size()>0){
+ this.passaggi.addAll(other.passaggi);
+ }
+
if(this.destinazione == null && other.destinazione!=null) {
this.destinazione = other.destinazione;
adjusted = true;
}
if(!this.isBranchIdValid() && other.isBranchIdValid()) {
this.branchid = other.branchid;
adjusted = true;
}
if(this.festivo == Route.FestiveInfo.UNKNOWN && other.festivo!= Route.FestiveInfo.UNKNOWN){
this.festivo = other.festivo;
adjusted = true;
}
- if(other.description!=null&&
- ((this.festivo == FestiveInfo.FERIALE && this.description.contains("festivo")) ||
- (this.festivo == FestiveInfo.FESTIVO && this.description.contains("feriale")))) {
+ if(other.description!=null && (this.description==null ||
+ (this.festivo == FestiveInfo.FERIALE && this.description.contains("festivo")) ||
+ (this.festivo == FestiveInfo.FESTIVO && this.description.contains("feriale")) ) ) {
this.description = other.description;
}
return adjusted;
}
}
diff --git a/src/it/reyboz/bustorino/backend/Stop.java b/src/it/reyboz/bustorino/backend/Stop.java
index 72eb5ce3..3f5f795b 100644
--- a/src/it/reyboz/bustorino/backend/Stop.java
+++ b/src/it/reyboz/bustorino/backend/Stop.java
@@ -1,290 +1,295 @@
/*
BusTO (backend components)
Copyright (C) 2016 Ludovico Pavesi
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.backend;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import it.reyboz.bustorino.util.LinesNameSorter;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
public class Stop implements Comparable<Stop> {
// remove "final" in case you need to set these from outside the parser\scrapers\fetchers
public final @NonNull String ID;
private @Nullable String name;
private @Nullable String username;
public @Nullable String location;
public @Nullable Route.Type type;
private @Nullable List<String> routesThatStopHere;
private final @Nullable Double lat;
private final @Nullable Double lon;
// leave this non-final
private @Nullable String routesThatStopHereString = null;
private @Nullable String absurdGTTPlaceName = null;
/**
* Hey, look, method overloading!
*/
public Stop(final @Nullable String name, final @NonNull String ID, @Nullable final String location, @Nullable final Route.Type type, @Nullable final List<String> routesThatStopHere) {
this.ID = ID;
this.name = name;
this.username = null;
this.location = (location != null && location.length() == 0) ? null : location;
this.type = type;
this.routesThatStopHere = routesThatStopHere;
this.lat = null;
this.lon = null;
}
/**
* Hey, look, method overloading!
*/
public Stop(final @NonNull String ID) {
this.ID = ID;
this.name = null;
this.username = null;
this.location = null;
this.type = null;
this.routesThatStopHere = null;
this.lat = null;
this.lon = null;
}
/**
* Constructor that sets EVERYTHING.
*/
public Stop(@NonNull String ID, @Nullable String name, @Nullable String userName, @Nullable String location, @Nullable Route.Type type, @Nullable List<String> routesThatStopHere, @Nullable Double lat, @Nullable Double lon) {
this.ID = ID;
this.name = name;
this.username = userName;
this.location = location;
this.type = type;
this.routesThatStopHere = routesThatStopHere;
this.lat = lat;
this.lon = lon;
}
public @Nullable String routesThatStopHereToString() {
// M E M O I Z A T I O N
if(this.routesThatStopHereString != null) {
return this.routesThatStopHereString;
}
// no string yet? build it!
return buildString();
}
@Nullable
public String getAbsurdGTTPlaceName() {
return absurdGTTPlaceName;
}
public void setAbsurdGTTPlaceName(@NonNull String absurdGTTPlaceName) {
this.absurdGTTPlaceName = absurdGTTPlaceName;
}
public void setRoutesThatStopHere(@Nullable List<String> routesThatStopHere) {
this.routesThatStopHere = routesThatStopHere;
}
+ @Nullable
+ protected List<String> getRoutesThatStopHere(){
+ return routesThatStopHere;
+ }
+
private @Nullable String buildString() {
// no routes => no string
if(this.routesThatStopHere == null || this.routesThatStopHere.size() == 0) {
return null;
}
StringBuilder sb = new StringBuilder();
Collections.sort(routesThatStopHere,new LinesNameSorter());
int i, lenMinusOne = routesThatStopHere.size() - 1;
for (i = 0; i < lenMinusOne; i++) {
sb.append(routesThatStopHere.get(i)).append(", ");
}
// last one:
sb.append(routesThatStopHere.get(i));
this.routesThatStopHereString = sb.toString();
return this.routesThatStopHereString;
}
@Override
public int compareTo(@NonNull Stop other) {
int res;
int thisAsInt = networkTools.failsafeParseInt(this.ID);
int otherAsInt = networkTools.failsafeParseInt(other.ID);
// numeric stop IDs
if(thisAsInt != 0 && otherAsInt != 0) {
return thisAsInt - otherAsInt;
} else {
// non-numeric
res = this.ID.compareTo(other.ID);
if (res != 0) {
return res;
}
}
// try with name, then
if(this.name != null && other.name != null) {
res = this.name.compareTo(other.name);
}
// and give up
return res;
}
/**
* Sets a name.
*
* @param name stop name as string (not null)
*/
public final void setStopName(@NonNull String name) {
this.name = name;
}
/**
* Sets user name. Empty string is converted to null.
*
* @param name a string of non-zero length, or null
*/
public final void setStopUserName(@Nullable String name) {
if(name == null) {
this.username = null;
} else if(name.length() == 0) {
this.username = null;
} else {
this.username = name;
}
}
/**
* Returns stop name or username (if set).<br>
* - empty string means "already searched everywhere, can't find it"<br>
* - null means "didn't search, yet. Maybe you should try."<br>
* - string means "here's the name.", obviously.<br>
*
* @return string if known, null if still unknown
*/
public final @Nullable String getStopDisplayName() {
if(this.username == null) {
return this.name;
} else {
return this.username;
}
}
/**
* Same as getStopDisplayName, only returns default name.<br>
* I'd use an @see tag, but Android Studio is incapable of understanding that getStopDefaultName
* refers to the method exactly above this one and not some arcane and esoteric unknown symbol.
*/
public final @Nullable String getStopDefaultName() {
return this.name;
}
/**
* Same as getStopDisplayName, only returns user name.<br>
* Also, never an empty string.
*/
public final @Nullable String getStopUserName() {
return this.username;
}
/**
* Gets username and name from other stop if they exist, sets itself accordingly.
*
* @param other another Stop
* @return did we actually set/change anything?
*/
public final boolean mergeNameFrom(Stop other) {
boolean ret = false;
if(other.name != null) {
if(this.name == null || !this.name.equals(other.name)) {
this.name = other.name;
ret = true;
}
}
if(other.username != null) {
if(this.username == null || !this.username.equals(other.username)) {
this.username = other.username;
ret = true;
}
}
return ret;
}
public final @Nullable String getGeoURL() {
if(this.lat == null || this.lon == null) {
return null;
}
// Android documentation suggests US for machine readable output (use dot as decimal separator)
return String.format(Locale.US, "geo:%f,%f", this.lat, this.lon);
}
public final @Nullable String getGeoURLWithAddress() {
String url = getGeoURL();
if(url == null) {
return null;
}
if(this.location != null) {
try {
String addThis = "?q=".concat(URLEncoder.encode(this.location, "utf-8"));
return url.concat(addThis);
} catch (Exception ignored) {}
}
return url;
}
@Nullable
public Double getLatitude() {
return lat;
}
@Nullable
public Double getLongitude() {
return lon;
}
public Double getDistanceFromLocation(Location loc){
if(this.lat!=null && this.lon !=null)
return utils.measuredistanceBetween(this.lat,this.lon,loc.getLatitude(),loc.getLongitude());
else return Double.POSITIVE_INFINITY;
}
}
diff --git a/src/it/reyboz/bustorino/backend/utils.java b/src/it/reyboz/bustorino/backend/utils.java
index 99becf74..4d9e1018 100644
--- a/src/it/reyboz/bustorino/backend/utils.java
+++ b/src/it/reyboz/bustorino/backend/utils.java
@@ -1,32 +1,32 @@
package it.reyboz.bustorino.backend;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public abstract class utils {
private static final double EarthRadius = 6371e3;
public static Double measuredistanceBetween(double lat1,double long1,double lat2,double long2){
final double phi1 = Math.toRadians(lat1);
final double phi2 = Math.toRadians(lat2);
final double deltaPhi = Math.toRadians(lat2-lat1);
final double deltaTheta = Math.toRadians(long2-long1);
final double a = Math.sin(deltaPhi/2)*Math.sin(deltaPhi/2)+
Math.cos(phi1)*Math.cos(phi2)*Math.sin(deltaTheta/2)*Math.sin(deltaTheta/2);
final double c = 2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));
- return EarthRadius*c;
+ return Math.abs(EarthRadius*c);
}
public static int convertDipToPixels(Context con,float dips)
{
return (int) (dips * con.getResources().getDisplayMetrics().density + 0.5f);
}
public static int calculateNumColumnsFromSize(View containerView, int pixelsize){
int width = containerView.getWidth();
float ncols = ((float)width)/pixelsize;
return (int) Math.floor(ncols);
}
}
diff --git a/src/it/reyboz/bustorino/fragments/FragmentKind.java b/src/it/reyboz/bustorino/fragments/FragmentKind.java
index 514ddd8c..07f50782 100644
--- a/src/it/reyboz/bustorino/fragments/FragmentKind.java
+++ b/src/it/reyboz/bustorino/fragments/FragmentKind.java
@@ -1,22 +1,22 @@
/*
BusTO (fragments)
Copyright (C) 2018 Fabio Mazza
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.fragments;
public enum FragmentKind {
- STOPS,ARRIVALS,FAVORITES,NEARBY
+ STOPS,ARRIVALS,FAVORITES,NEARBY_STOPS,NEARBY_ARRIVALS
}
diff --git a/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java b/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java
index 88153b7c..7ad40c8c 100644
--- a/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java
+++ b/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java
@@ -1,374 +1,612 @@
/*
BusTO - Fragments components
Copyright (C) 2018 Fabio Mazza
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
+import android.support.v4.util.Pair;
import android.support.v7.preference.PreferenceManager;
+import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
+import com.android.volley.*;
import it.reyboz.bustorino.R;
+import it.reyboz.bustorino.adapters.ArrivalsStopAdapter;
+import it.reyboz.bustorino.backend.*;
+import it.reyboz.bustorino.backend.FiveTAPIFetcher.QueryType;
import it.reyboz.bustorino.middleware.AppLocationManager;
-import it.reyboz.bustorino.backend.Route;
-import it.reyboz.bustorino.backend.Stop;
-import it.reyboz.bustorino.backend.utils;
import it.reyboz.bustorino.middleware.AppDataProvider;
import it.reyboz.bustorino.middleware.NextGenDB.Contract.*;
import it.reyboz.bustorino.adapters.SquareStopAdapter;
import it.reyboz.bustorino.util.LocationCriteria;
import it.reyboz.bustorino.util.StopSorterByDistance;
import java.util.*;
public class NearbyStopsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private FragmentListener mListener;
private FragmentLocationListener fragmentLocationListener;
private final String[] PROJECTION = {StopsTable.COL_ID,StopsTable.COL_LAT,StopsTable.COL_LONG,
StopsTable.COL_NAME,StopsTable.COL_TYPE,StopsTable.COL_LINES_STOPPING};
private final static String DEBUG_TAG = "NearbyStopsFragment";
+ private final static String FRAGMENT_TYPE_KEY = "FragmentType";
+ public final static int TYPE_STOPS = 19, TYPE_ARRIVALS = 20;
+ private int fragment_type;
//data Bundle
private final String BUNDLE_LOCATION = "location";
private final int LOADER_ID = 0;
private RecyclerView gridRecyclerView;
private SquareStopAdapter dataAdapter;
private AutoFitGridLayoutManager gridLayoutManager;
boolean canStartDBQuery = true;
private Location lastReceivedLocation = null;
- private ProgressBar loadingProgressBar;
+ private ProgressBar circlingProgressBar,flatProgressBar;
private int distance;
- private SharedPreferences globalSharedPref;
+ protected SharedPreferences globalSharedPref;
private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;
private TextView messageTextView;
private CommonScrollListener scrollListener;
- private boolean firstLoc = true;
+ private AppCompatButton switchButton;
+ private boolean firstLocForStops = true,firstLocForArrivals = true;
public static final int COLUMN_WIDTH_DP = 250;
private Integer MAX_DISTANCE = -3;
private int MIN_NUM_STOPS = -1;
+ private int TIME_INTERVAL_REQUESTS = -1;
private AppLocationManager locManager;
+ //These are useful for the case of nearby arrivals
+ private ArrivalsManager arrivalsManager = null;
+ private ArrivalsStopAdapter arrivalsStopAdapter = null;
+
public NearbyStopsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
* @return A new instance of fragment NearbyStopsFragment.
*/
- public static NearbyStopsFragment newInstance() {
+ public static NearbyStopsFragment newInstance(int fragmentType) {
+ if(fragmentType != TYPE_STOPS && fragmentType != TYPE_ARRIVALS )
+ throw new IllegalArgumentException("WRONG KIND OF FRAGMENT USED");
NearbyStopsFragment fragment = new NearbyStopsFragment();
- Bundle args = new Bundle();
+ final Bundle args = new Bundle(1);
+ args.putInt(FRAGMENT_TYPE_KEY,fragmentType);
fragment.setArguments(args);
return fragment;
}
+
+
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
- /*
- mParam1 = getArguments().getString(ARG_PARAM1);
- mParam2 = getArguments().getString(ARG_PARAM2);
- */
+ setFragmentType(getArguments().getInt(FRAGMENT_TYPE_KEY));
}
locManager = AppLocationManager.getInstance(getContext());
fragmentLocationListener = new FragmentLocationListener(this);
globalSharedPref = getContext().getSharedPreferences(getString(R.string.mainSharedPreferences),Context.MODE_PRIVATE);
globalSharedPref.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
+
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_nearby_stops, container, false);
gridRecyclerView = (RecyclerView) root.findViewById(R.id.stopGridRecyclerView);
gridLayoutManager = new AutoFitGridLayoutManager(getContext().getApplicationContext(), utils.convertDipToPixels(getContext(),COLUMN_WIDTH_DP));
gridRecyclerView.setLayoutManager(gridLayoutManager);
gridRecyclerView.setHasFixedSize(false);
- loadingProgressBar = (ProgressBar) root.findViewById(R.id.loadingBar);
+ circlingProgressBar = (ProgressBar) root.findViewById(R.id.loadingBar);
+ flatProgressBar = (ProgressBar) root.findViewById(R.id.horizontalProgressBar);
messageTextView = (TextView) root.findViewById(R.id.messageTextView);
+ switchButton = (AppCompatButton) root.findViewById(R.id.switchButton);
+
preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d(DEBUG_TAG,"Key "+key+" was changed");
if(key.equals(getString(R.string.databaseUpdatingPref))){
if(!sharedPreferences.getBoolean(getString(R.string.databaseUpdatingPref),true)){
canStartDBQuery = true;
Log.d(DEBUG_TAG,"The database has finished updating, can start update now");
}
}
}
};
scrollListener = new CommonScrollListener(mListener,false);
+ switchButton.setOnClickListener(v -> {
+ if(fragment_type==TYPE_ARRIVALS){
+ setFragmentType(TYPE_STOPS);
+ switchButton.setText(getString(R.string.show_arrivals));
+ if(dataAdapter!=null)
+ gridRecyclerView.setAdapter(dataAdapter);
+
+ } else if (fragment_type==TYPE_STOPS){
+ setFragmentType(TYPE_ARRIVALS);
+ switchButton.setText(getString(R.string.show_stops));
+ if(arrivalsStopAdapter!=null)
+ gridRecyclerView.setAdapter(arrivalsStopAdapter);
+ }
+ fragmentLocationListener.lastUpdateTime = -1;
+ locManager.removeLocationRequestFor(fragmentLocationListener);
+ locManager.addLocationRequestFor(fragmentLocationListener);
+ });
return root;
}
+ protected ArrayList<Stop> createStopListFromCursor(Cursor data){
+ ArrayList<Stop> stopList = new ArrayList<>();
+ final int col_id = data.getColumnIndex(StopsTable.COL_ID);
+ final int latInd = data.getColumnIndex(StopsTable.COL_LAT);
+ final int lonInd = data.getColumnIndex(StopsTable.COL_LONG);
+ final int nameindex = data.getColumnIndex(StopsTable.COL_NAME);
+ final int typeIndex = data.getColumnIndex(StopsTable.COL_TYPE);
+ final int linesIndex = data.getColumnIndex(StopsTable.COL_LINES_STOPPING);
+
+ data.moveToFirst();
+ for(int i=0; i<data.getCount();i++){
+ String[] routes = data.getString(linesIndex).split(",");
+
+ stopList.add(new Stop(data.getString(col_id),data.getString(nameindex),null,null,
+ Route.Type.fromCode(data.getInt(typeIndex)),
+ Arrays.asList(routes), //the routes should be compact, not normalized yet
+ data.getDouble(latInd),data.getDouble(lonInd)
+ )
+ );
+ //Log.d("NearbyStopsFragment","Got stop with id "+data.getString(col_id)+
+ //" and name "+data.getString(nameindex));
+ data.moveToNext();
+ }
+ return stopList;
+ }
+
+ /**
+ * Use this method to set the fragment type
+ * @param type the type, TYPE_ARRIVALS or TYPE_STOPS
+ */
+ private void setFragmentType(int type){
+ if(type!=TYPE_ARRIVALS && type !=TYPE_STOPS)
+ throw new IllegalArgumentException("type not recognized");
+ this.fragment_type = type;
+ switch(type){
+ case TYPE_ARRIVALS:
+
+ TIME_INTERVAL_REQUESTS = 5*1000;
+ break;
+ case TYPE_STOPS:
+ TIME_INTERVAL_REQUESTS = 1000;
+
+ }
+ }
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentListener) {
mListener = (FragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onPause() {
super.onPause();
canStartDBQuery = false;
gridRecyclerView.setAdapter(null);
locManager.removeLocationRequestFor(fragmentLocationListener);
Log.d(DEBUG_TAG,"On paused called");
}
@Override
public void onResume() {
super.onResume();
canStartDBQuery = !globalSharedPref.getBoolean(getString(R.string.databaseUpdatingPref),false);
try{
if(canStartDBQuery) locManager.addLocationRequestFor(fragmentLocationListener);
} catch (SecurityException ex){
//ignored
//try another location provider
}
if(dataAdapter!=null){
gridRecyclerView.setAdapter(dataAdapter);
- loadingProgressBar.setVisibility(View.GONE);
+ circlingProgressBar.setVisibility(View.GONE);
}
+ mListener.enableRefreshLayout(false);
Log.d(DEBUG_TAG,"OnResume called");
//Re-read preferences
SharedPreferences shpr = PreferenceManager.getDefaultSharedPreferences(getContext().getApplicationContext());
//For some reason, they are all saved as strings
MAX_DISTANCE = shpr.getInt(getString(R.string.pref_key_radius_recents),1000);
MIN_NUM_STOPS = Integer.parseInt(shpr.getString(getString(R.string.pref_key_num_recents),"12"));
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
gridRecyclerView.setVisibility(View.INVISIBLE);
gridRecyclerView.addOnScrollListener(scrollListener);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
+ if(arrivalsManager!=null) arrivalsManager.cancelAllRequests();
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//BUILD URI
lastReceivedLocation = args.getParcelable(BUNDLE_LOCATION);
Uri.Builder builder = new Uri.Builder();
builder.scheme("content").authority(AppDataProvider.AUTHORITY)
.appendPath("stops").appendPath("location")
.appendPath(String.valueOf(lastReceivedLocation.getLatitude()))
.appendPath(String.valueOf(lastReceivedLocation.getLongitude()))
.appendPath(String.valueOf(distance)); //distance
CursorLoader cl = new CursorLoader(getContext(),builder.build(),PROJECTION,null,null,null);
cl.setUpdateThrottle(2000);
return cl;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
- ArrayList<Stop> stopList = new ArrayList<>();
- data.moveToFirst();
if (0 > MAX_DISTANCE) throw new AssertionError();
- if(!globalSharedPref.getBoolean(getString(R.string.databaseUpdatingPref),false) && (data.getCount()<MIN_NUM_STOPS || distance<=MAX_DISTANCE)){
+ if(!isDBUpdating() && (data.getCount()<MIN_NUM_STOPS || distance<=MAX_DISTANCE)){
distance = distance*2;
Bundle d = new Bundle();
d.putParcelable(BUNDLE_LOCATION,lastReceivedLocation);
getLoaderManager().restartLoader(LOADER_ID,d,this);
return;
}
Log.d("LoadFromCursor","Number of nearby stops: "+data.getCount());
- final int col_id = data.getColumnIndex(StopsTable.COL_ID);
- final int latInd = data.getColumnIndex(StopsTable.COL_LAT);
- final int lonInd = data.getColumnIndex(StopsTable.COL_LONG);
- final int nameindex = data.getColumnIndex(StopsTable.COL_NAME);
- final int typeIndex = data.getColumnIndex(StopsTable.COL_TYPE);
- final int linesIndex = data.getColumnIndex(StopsTable.COL_LINES_STOPPING);
- for(int i=0; i<data.getCount();i++){
- String[] routes = data.getString(linesIndex).split(",");
-
- stopList.add(new Stop(data.getString(col_id),data.getString(nameindex),null,null,
- Route.Type.fromCode(data.getInt(typeIndex)),
- Arrays.asList(routes), //the routes should be compact, not normalized yet
- data.getDouble(latInd),data.getDouble(lonInd)
- )
- );
- //Log.d("NearbyStopsFragment","Got stop with id "+data.getString(col_id)+
- //" and name "+data.getString(nameindex));
- data.moveToNext();
- }
+ ////////
+ ArrayList<Stop> stopList = createStopListFromCursor(data);
if(data.getCount()>0) {
//quick trial to hopefully always get the stops in the correct order
Collections.sort(stopList,new StopSorterByDistance(lastReceivedLocation));
-
- if(firstLoc) {
- dataAdapter = new SquareStopAdapter(stopList, mListener, lastReceivedLocation);
- gridRecyclerView.setAdapter(dataAdapter);
- firstLoc = false;
- }else {
- dataAdapter.setStops(stopList);
- dataAdapter.setUserPosition(lastReceivedLocation);
- }
- dataAdapter.notifyDataSetChanged();
- if (gridRecyclerView.getVisibility() != View.VISIBLE) {
- loadingProgressBar.setVisibility(View.GONE);
- gridRecyclerView.setVisibility(View.VISIBLE);
+ switch (fragment_type){
+ case TYPE_STOPS:
+ showStopsInRecycler(stopList);
+ break;
+ case TYPE_ARRIVALS:
+ arrivalsManager = new ArrivalsManager(stopList);
+ flatProgressBar.setVisibility(View.VISIBLE);
+ flatProgressBar.setProgress(0);
+ flatProgressBar.setIndeterminate(false);
+ //for the moment, be satisfied with only one location
+ //AppLocationManager.getInstance(getContext()).removeLocationRequestFor(fragmentLocationListener);
+ break;
+ default:
}
- messageTextView.setVisibility(View.GONE);
+
} else {
- messageTextView.setVisibility(View.VISIBLE);
- messageTextView.setText(R.string.no_stops_nearby);
- loadingProgressBar.setVisibility(View.GONE);
+ setNoStopsLayout();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
+ //useful methods
+ protected boolean isDBUpdating(){
+ return globalSharedPref.getBoolean(getString(R.string.databaseUpdatingPref),false);
+ }
+
+
+ /////// GUI METHODS ////////
+ private void showStopsInRecycler(List<Stop> stops){
+
+ if(firstLocForStops) {
+ dataAdapter = new SquareStopAdapter(stops, mListener, lastReceivedLocation);
+ gridRecyclerView.setAdapter(dataAdapter);
+ firstLocForStops = false;
+ }else {
+ dataAdapter.setStops(stops);
+ dataAdapter.setUserPosition(lastReceivedLocation);
+ }
+ dataAdapter.notifyDataSetChanged();
+
+ //showRecyclerHidingLoadMessage();
+ if (gridRecyclerView.getVisibility() != View.VISIBLE) {
+ circlingProgressBar.setVisibility(View.GONE);
+ gridRecyclerView.setVisibility(View.VISIBLE);
+ }
+ messageTextView.setVisibility(View.GONE);
+ }
+
+ private void showArrivalsInRecycler(List<Palina> palinas){
+ Collections.sort(palinas,new StopSorterByDistance(lastReceivedLocation));
+
+ final ArrayList<Pair<Stop,Route>> routesPairList = new ArrayList<>(10);
+ //int maxNum = Math.min(MAX_STOPS, stopList.size());
+ for(Palina p: palinas){
+ //if there are no routes available, skip stop
+ if(p.queryAllRoutes().size() == 0) continue;
+ for(Route r: p.queryAllRoutes()){
+ //if there are no routes, should not do anything
+ routesPairList.add(new Pair<>(p,r));
+ }
+ }
+ if(firstLocForArrivals){
+ arrivalsStopAdapter = new ArrivalsStopAdapter(routesPairList,mListener,getContext(),lastReceivedLocation);
+ gridRecyclerView.setAdapter(arrivalsStopAdapter);
+ firstLocForArrivals = false;
+ } else {
+ arrivalsStopAdapter.setRoutesPairListAndPosition(routesPairList,lastReceivedLocation);
+ }
+
+ arrivalsStopAdapter.notifyDataSetChanged();
+
+ showRecyclerHidingLoadMessage();
+ }
+
+ private void setNoStopsLayout(){
+ messageTextView.setVisibility(View.VISIBLE);
+ messageTextView.setText(R.string.no_stops_nearby);
+ circlingProgressBar.setVisibility(View.GONE);
+ }
+
+ /**
+ * Does exactly what is says on the tin
+ */
+ private void showRecyclerHidingLoadMessage(){
+ if (gridRecyclerView.getVisibility() != View.VISIBLE) {
+ circlingProgressBar.setVisibility(View.GONE);
+ gridRecyclerView.setVisibility(View.VISIBLE);
+ }
+ messageTextView.setVisibility(View.GONE);
+ }
+
+ class ArrivalsManager implements FiveTAPIVolleyRequest.ResponseListener, Response.ErrorListener{
+ final HashMap<String,Palina> mStops;
+ final Map<String,List<Route>> routesToAdd = new HashMap<>();
+ final static String REQUEST_TAG = "NearbyArrivals";
+ private final QueryType[] types = {QueryType.ARRIVALS,QueryType.DETAILS};
+ final NetworkVolleyManager volleyManager;
+ private final int MAX_ARRIVAL_STOPS =35;
+ int activeRequestCount = 0,reqErrorCount = 0, reqSuccessCount=0;
+
+ ArrivalsManager(List<Stop> stops){
+ mStops = new HashMap<>();
+ volleyManager = NetworkVolleyManager.getInstance(getContext());
+
+ for(Stop s: stops.subList(0,Math.min(stops.size(), MAX_ARRIVAL_STOPS))){
+ mStops.put(s.ID,new Palina(s));
+ for(QueryType t: types) {
+ final FiveTAPIVolleyRequest req = FiveTAPIVolleyRequest.getNewRequest(t, s.ID, this, this);
+ if (req != null) {
+ req.setTag(REQUEST_TAG);
+ volleyManager.addToRequestQueue(req);
+ activeRequestCount++;
+ }
+ }
+ }
+ flatProgressBar.setMax(activeRequestCount);
+ }
+
+
+
+ @Override
+ public void onErrorResponse(VolleyError error) {
+ if(error instanceof ParseError){
+ //TODO
+ Log.w(DEBUG_TAG,"Parsing error for stop request");
+ } else if (error instanceof NetworkError){
+ String s;
+ if(error.networkResponse!=null)
+ s = new String(error.networkResponse.data);
+ else s="";
+ Log.w(DEBUG_TAG,"Network error: "+s);
+ }else {
+ Log.w(DEBUG_TAG,"Volley Error: "+error.getMessage());
+ }
+ if(error.networkResponse!=null){
+ Log.w(DEBUG_TAG, "Error status code: "+error.networkResponse.statusCode);
+ }
+ //counters
+ activeRequestCount--;
+ reqErrorCount++;
+ flatProgressBar.setProgress(reqErrorCount+reqSuccessCount);
+ }
+
+ @Override
+ public void onResponse(Palina result, QueryType type) {
+ //counter for requests
+ activeRequestCount--;
+ reqSuccessCount++;
+
+
+ final Palina palinaInMap = mStops.get(result.ID);
+ //palina cannot be null here
+ if(palinaInMap == null) throw new IllegalStateException("Cannot get the palina from the map");
+ //necessary to split the Arrivals and Details cases
+ switch (type){
+ case ARRIVALS:
+ palinaInMap.addInfoFromRoutes(result.queryAllRoutes());
+ final List<Route> possibleRoutes = routesToAdd.get(result.ID);
+ if(possibleRoutes!=null) {
+ palinaInMap.addInfoFromRoutes(possibleRoutes);
+ routesToAdd.remove(result.ID);
+ }
+ break;
+ case DETAILS:
+ if(palinaInMap.queryAllRoutes().size()>0){
+ //merge the branches
+ palinaInMap.addInfoFromRoutes(result.queryAllRoutes());
+ } else {
+ routesToAdd.put(result.ID,result.queryAllRoutes());
+ }
+ break;
+ default:
+ throw new IllegalArgumentException("Wrong QueryType in onResponse");
+ }
+
+ final ArrayList<Palina> outList = new ArrayList<>();
+ for(Palina p: mStops.values()){
+ final List<Route> routes = p.queryAllRoutes();
+ if(routes!=null && routes.size()>0) outList.add(p);
+ }
+ showArrivalsInRecycler(outList);
+ flatProgressBar.setProgress(reqErrorCount+reqSuccessCount);
+ if(activeRequestCount==0) {
+ flatProgressBar.setIndeterminate(true);
+ flatProgressBar.setVisibility(View.GONE);
+ }
+ }
+ void cancelAllRequests(){
+ volleyManager.getRequestQueue().cancelAll(REQUEST_TAG);
+ }
+ }
/**
* Local locationListener, to use for the GPS
*/
class FragmentLocationListener implements AppLocationManager.LocationRequester{
LoaderManager.LoaderCallbacks<Cursor> callbacks;
private int oldLocStatus = -2;
private LocationCriteria cr;
+ private long lastUpdateTime = -1;
public FragmentLocationListener(LoaderManager.LoaderCallbacks<Cursor> callbacks) {
this.callbacks = callbacks;
}
@Override
public void onLocationChanged(Location location) {
//set adapter
float accuracy = location.getAccuracy();
if(accuracy<60 && canStartDBQuery) {
distance = 20;
final Bundle msgBundle = new Bundle();
msgBundle.putParcelable(BUNDLE_LOCATION,location);
getLoaderManager().restartLoader(LOADER_ID,msgBundle,callbacks);
}
+ lastUpdateTime = System.currentTimeMillis();
Log.d("LocationListener","can start loader "+ canStartDBQuery);
}
@Override
public void onLocationStatusChanged(int status) {
switch(status){
case AppLocationManager.LOCATION_GPS_AVAILABLE:
messageTextView.setVisibility(View.GONE);
break;
case AppLocationManager.LOCATION_UNAVAILABLE:
messageTextView.setText(R.string.enableGpsText);
messageTextView.setVisibility(View.VISIBLE);
break;
default:
Log.e(DEBUG_TAG,"Location status not recognized");
}
}
@Override
public LocationCriteria getLocationCriteria() {
- if(cr==null){
- cr = new LocationCriteria(60);
- }
- return cr;
+
+ return new LocationCriteria(60,TIME_INTERVAL_REQUESTS);
+ }
+
+ @Override
+ public long getLastUpdateTimeMillis() {
+ return lastUpdateTime;
+ }
+ void resetUpdateTime(){
+ lastUpdateTime = -1;
}
}
/**
* Simple trick to get an automatic number of columns (from https://www.journaldev.com/13792/android-gridlayoutmanager-example)
*
*/
class AutoFitGridLayoutManager extends GridLayoutManager {
private int columnWidth;
private boolean columnWidthChanged = true;
public AutoFitGridLayoutManager(Context context, int columnWidth) {
super(context, 1);
setColumnWidth(columnWidth);
}
public void setColumnWidth(int newColumnWidth) {
if (newColumnWidth > 0 && newColumnWidth != columnWidth) {
columnWidth = newColumnWidth;
columnWidthChanged = true;
}
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (columnWidthChanged && columnWidth > 0) {
int totalSpace;
if (getOrientation() == VERTICAL) {
totalSpace = getWidth() - getPaddingRight() - getPaddingLeft();
} else {
totalSpace = getHeight() - getPaddingTop() - getPaddingBottom();
}
int spanCount = Math.max(1, totalSpace / columnWidth);
setSpanCount(spanCount);
columnWidthChanged = false;
}
super.onLayoutChildren(recycler, state);
}
}
}
diff --git a/src/it/reyboz/bustorino/fragments/ResultListFragment.java b/src/it/reyboz/bustorino/fragments/ResultListFragment.java
index 0e7a26b7..6d42a9e2 100644
--- a/src/it/reyboz/bustorino/fragments/ResultListFragment.java
+++ b/src/it/reyboz/bustorino/fragments/ResultListFragment.java
@@ -1,293 +1,293 @@
/*
BusTO - Fragments components
Copyright (C) 2016 Fabio Mazza
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.fragments;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.support.design.widget.FloatingActionButton;
import it.reyboz.bustorino.ActivityMain;
import it.reyboz.bustorino.R;
import it.reyboz.bustorino.backend.FiveTNormalizer;
import it.reyboz.bustorino.backend.Palina;
import it.reyboz.bustorino.backend.Route;
import it.reyboz.bustorino.backend.Stop;
/**
* This is a generalized fragment that can be used both for
*
*
*/
public class ResultListFragment extends Fragment{
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
static final String LIST_TYPE = "list-type";
private static final String STOP_TITLE = "messageExtra";
protected static final String LIST_STATE = "list_state";
private static final String MESSAGE_TEXT_VIEW = "message_text_view";
private FragmentKind adapterKind;
private boolean adapterSet = false;
private FragmentListener mListener;
private TextView messageTextView;
private FloatingActionButton fabutton;
private ListView resultsListView;
private ListAdapter mListAdapter = null;
boolean listShown;
private Parcelable mListInstanceState = null;
public ResultListFragment() {
// Required empty public constructor
}
public ListView getResultsListView() {
return resultsListView;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param listType whether the list is used for STOPS or LINES (Orari)
* @return A new instance of fragment ResultListFragment.
*/
public static ResultListFragment newInstance(FragmentKind listType, String eventualStopTitle) {
ResultListFragment fragment = new ResultListFragment();
Bundle args = new Bundle();
args.putSerializable(LIST_TYPE, listType);
if (eventualStopTitle != null)
args.putString(STOP_TITLE, eventualStopTitle);
fragment.setArguments(args);
return fragment;
}
public static ResultListFragment newInstance(FragmentKind listType) {
return newInstance(listType, null);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
adapterKind = (FragmentKind) getArguments().getSerializable(LIST_TYPE);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_list_view, container, false);
messageTextView = (TextView) root.findViewById(R.id.messageTextView);
if (adapterKind != null) {
resultsListView = (ListView) root.findViewById(R.id.resultsListView);
switch (adapterKind) {
case STOPS:
resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*
* Casting because of Javamerda
* @url http://stackoverflow.com/questions/30549485/androids-list-view-parameterized-type-in-adapterview-onitemclicklistener
*/
Stop busStop = (Stop) parent.getItemAtPosition(position);
mListener.createFragmentForStop(busStop.ID);
}
});
//set the textviewMessage
setTextViewMessage(getString(R.string.results));
break;
case ARRIVALS:
resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String routeName;
Route r = (Route) parent.getItemAtPosition(position);
- routeName = FiveTNormalizer.routeInternalToDisplay(r.name);
+ routeName = FiveTNormalizer.routeInternalToDisplay(r.getNameForDisplay());
if (routeName == null) {
- routeName = r.name;
+ routeName = r.getNameForDisplay();
}
if (r.destinazione == null || r.destinazione.length() == 0) {
Toast.makeText(getContext(),
getString(R.string.route_towards_unknown, routeName), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(),
getString(R.string.route_towards_destination, routeName, r.destinazione), Toast.LENGTH_SHORT).show();
}
}
});
String displayName = getArguments().getString(STOP_TITLE);
setTextViewMessage(String.format(
getString(R.string.passages), displayName));
break;
default:
throw new IllegalStateException("Argument passed was not of a supported type");
}
String probablemessage = getArguments().getString(MESSAGE_TEXT_VIEW);
if (probablemessage != null) {
//Log.d("BusTO fragment " + this.getTag(), "We have a possible message here in the savedInstaceState: " + probablemessage);
messageTextView.setText(probablemessage);
messageTextView.setVisibility(View.VISIBLE);
}
} else
Log.d(getString(R.string.list_fragment_debug), "No content root for fragment");
return root;
}
public boolean isFragmentForTheSameStop(Palina p) {
return adapterKind.equals(FragmentKind.ARRIVALS) && getTag().equals(getFragmentTag(p));
}
public static String getFragmentTag(Palina p) {
return p.ID;
}
@Override
public void onResume() {
super.onResume();
//Log.d(getString(R.string.list_fragment_debug),"Fragment restored, saved listAdapter is "+(mListAdapter));
if (mListAdapter != null) {
ListAdapter adapter = mListAdapter;
mListAdapter = null;
setListAdapter(adapter);
}
if (mListInstanceState != null) {
Log.d("resultsListView", "trying to restore instance state");
resultsListView.onRestoreInstanceState(mListInstanceState);
}
switch (adapterKind) {
case ARRIVALS:
resultsListView.setOnScrollListener(new CommonScrollListener(mListener, true));
fabutton.show();
break;
case STOPS:
resultsListView.setOnScrollListener(new CommonScrollListener(mListener, false));
break;
default:
//NONE
}
mListener.readyGUIfor(adapterKind);
}
@Override
public void onPause() {
if (adapterKind.equals(FragmentKind.ARRIVALS)) {
SwipeRefreshLayout reflay = (SwipeRefreshLayout) getActivity().findViewById(R.id.listRefreshLayout);
reflay.setEnabled(false);
Log.d("BusTO Fragment " + this.getTag(), "RefreshLayout disabled");
}
super.onPause();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentListener) {
mListener = (FragmentListener) context;
fabutton = (FloatingActionButton) getActivity().findViewById(R.id.floatingActionButton);
} else {
throw new RuntimeException(context.toString()
+ " must implement ResultFragmentListener");
}
}
@Override
public void onDetach() {
mListener = null;
if (fabutton != null)
fabutton.show();
super.onDetach();
}
@Override
public void onDestroyView() {
resultsListView = null;
//Log.d(getString(R.string.list_fragment_debug), "called onDestroyView");
getArguments().putString(MESSAGE_TEXT_VIEW, messageTextView.getText().toString());
super.onDestroyView();
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
Log.d("ResultListFragment", "onViewStateRestored");
if (savedInstanceState != null) {
mListInstanceState = savedInstanceState.getParcelable(LIST_STATE);
Log.d("ResultListFragment", "listInstanceStatePresent :" + mListInstanceState);
}
}
public void setListAdapter(ListAdapter adapter) {
boolean hadAdapter = mListAdapter != null;
mListAdapter = adapter;
if (resultsListView != null) {
resultsListView.setAdapter(adapter);
resultsListView.setVisibility(View.VISIBLE);
}
}
/**
* Set the message textView
* @param message the whole message to write in the textView
*/
public void setTextViewMessage(String message) {
messageTextView.setText(message);
switch (adapterKind) {
case ARRIVALS:
final ActivityMain activ = (ActivityMain) getActivity();
messageTextView.setClickable(true);
messageTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.addLastStopToFavorites();
}
});
break;
case STOPS:
messageTextView.setClickable(false);
break;
}
messageTextView.setVisibility(View.VISIBLE);
}
}
diff --git a/src/it/reyboz/bustorino/middleware/AppDataProvider.java b/src/it/reyboz/bustorino/middleware/AppDataProvider.java
index e6ff5d23..c0362b59 100644
--- a/src/it/reyboz/bustorino/middleware/AppDataProvider.java
+++ b/src/it/reyboz/bustorino/middleware/AppDataProvider.java
@@ -1,266 +1,268 @@
/*
BusTO (middleware)
Copyright (C) 2018 Fabio Mazza
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.middleware;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import it.reyboz.bustorino.backend.DBStatusManager;
import it.reyboz.bustorino.middleware.NextGenDB.Contract.*;
import java.util.List;
public class AppDataProvider extends ContentProvider {
public static final String AUTHORITY = "it.reyboz.bustorino.provider";
private static final int STOP_OP = 1;
private static final int LINE_OP = 2;
private static final int BRANCH_OP = 3;
private static final int FAVORITES_OP =4;
private static final int MANY_STOPS = 5;
private static final int ADD_UPDATE_BRANCHES = 6;
private static final int LINE_INSERT_OP = 7;
private static final int CONNECTIONS = 8;
private static final int LOCATION_SEARCH = 9;
private static final String DEBUG_TAG="AppDataProvider";
private Context con;
private NextGenDB appDBHelper;
private UserDB udbhelper;
private SQLiteDatabase db;
private DBStatusManager preferences;
public AppDataProvider() {
}
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
/*
* The calls to addURI() go here, for all of the content URI patterns that the provider
* should recognize.
*/
sUriMatcher.addURI(AUTHORITY, "stop/#", STOP_OP);
sUriMatcher.addURI(AUTHORITY,"stops",MANY_STOPS);
sUriMatcher.addURI(AUTHORITY,"stops/location/*/*/*",LOCATION_SEARCH);
/*
* Sets the code for a single row to 2. In this case, the "#" wildcard is
* used. "content://com.example.app.provider/table3/3" matches, but
* "content://com.example.app.provider/table3 doesn't.
*/
sUriMatcher.addURI(AUTHORITY, "line/#", LINE_OP);
sUriMatcher.addURI(AUTHORITY,"branch/#",BRANCH_OP);
sUriMatcher.addURI(AUTHORITY,"line/insert",LINE_INSERT_OP);
sUriMatcher.addURI(AUTHORITY,"branches",ADD_UPDATE_BRANCHES);
sUriMatcher.addURI(AUTHORITY,"connections",CONNECTIONS);
sUriMatcher.addURI(AUTHORITY,"favorites/#",FAVORITES_OP);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Implement this to handle requests to delete one or more rows.
db = appDBHelper.getWritableDatabase();
int rows;
switch (sUriMatcher.match(uri)){
case MANY_STOPS:
rows = db.delete(NextGenDB.Contract.StopsTable.TABLE_NAME,null,null);
break;
default:
throw new UnsupportedOperationException("Not yet implemented");
}
return rows;
}
@Override
public String getType(Uri uri) {
// TODO: Implement this to handle requests for the MIME type of the data
// at the given URI.
int match = sUriMatcher.match(uri);
String baseTypedir = "vnd.android.cursor.dir/";
String baseTypeitem = "vnd.android.cursor.item/";
switch (match){
case LOCATION_SEARCH:
return baseTypedir+"stop";
case LINE_OP:
return baseTypeitem+"line";
case CONNECTIONS:
return baseTypedir+"stops";
}
return baseTypedir+"/item";
}
@Override
public Uri insert(Uri uri, ContentValues values) throws IllegalArgumentException{
//AVOID OPENING A DB CONNECTION, WILL THROW VERY NASTY ERRORS
if(preferences.isDBUpdating(true))
return null;
db = appDBHelper.getWritableDatabase();
Uri finalUri;
long last_rowid = -1;
switch (sUriMatcher.match(uri)){
case ADD_UPDATE_BRANCHES:
Log.d("InsBranchWithProvider","new Insert request");
String line_name = values.getAsString(NextGenDB.Contract.LinesTable.COLUMN_NAME);
if(line_name==null) throw new IllegalArgumentException("No line name given");
long lineid = -1;
Cursor c = db.query(LinesTable.TABLE_NAME,
new String[]{LinesTable._ID,LinesTable.COLUMN_NAME,LinesTable.COLUMN_DESCRIPTION},NextGenDB.Contract.LinesTable.COLUMN_NAME +" =?",
new String[]{line_name},null,null,null);
Log.d("InsBranchWithProvider","finding line in the database: "+c.getCount()+" matches");
if(c.getCount() == 0){
//There are no lines, insert?
//NOPE
/*
c.close();
ContentValues cv = new ContentValues();
cv.put(LinesTable.COLUMN_NAME,line_name);
lineid = db.insert(LinesTable.TABLE_NAME,null,cv);
*/
break;
}else {
c.moveToFirst();
/*
while(c.moveToNext()){
Log.d("InsBranchWithProvider","line: "+c.getString(c.getColumnIndex(LinesTable.COLUMN_NAME))+"\n"
+c.getString(c.getColumnIndex(LinesTable.COLUMN_DESCRIPTION)));
}*/
lineid = c.getInt(c.getColumnIndex(NextGenDB.Contract.LinesTable._ID));
c.close();
}
values.remove(NextGenDB.Contract.LinesTable.COLUMN_NAME);
values.put(BranchesTable.COL_LINE,lineid);
last_rowid = db.insertWithOnConflict(NextGenDB.Contract.BranchesTable.TABLE_NAME,null,values,SQLiteDatabase.CONFLICT_REPLACE);
break;
case MANY_STOPS:
//Log.d("AppDataProvider_busTO","New stop insert request");
try{
last_rowid = db.insertOrThrow(NextGenDB.Contract.StopsTable.TABLE_NAME,null,values);
} catch (SQLiteConstraintException e){
Log.w("AppDataProvider_busTO","Insert failed because of constraint");
last_rowid = -1;
e.printStackTrace();
}
break;
case CONNECTIONS:
try{
last_rowid = db.insertOrThrow(NextGenDB.Contract.ConnectionsTable.TABLE_NAME,null,values);
} catch (SQLiteConstraintException e){
Log.w("AppDataProvider_busTO","Insert failed because of constraint");
last_rowid = -1;
e.printStackTrace();
}
break;
default:
throw new IllegalArgumentException("Invalid parameters");
}
finalUri = ContentUris.withAppendedId(uri,last_rowid);
return finalUri;
}
@Override
public boolean onCreate() {
con = getContext();
appDBHelper = new NextGenDB(getContext());
udbhelper = new UserDB(getContext());
if(con!=null) {
preferences = new DBStatusManager(con,null);
} else {
preferences = null;
Log.e(DEBUG_TAG,"Cannot get shared preferences");
}
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) throws UnsupportedOperationException,IllegalArgumentException {
//IMPORTANT
+ //The app should not query when the DB is updating, but apparently, it does
if(preferences.isDBUpdating(true))
- throw new UnsupportedOperationException("DB is updating");
+ //throw new UnsupportedOperationException("DB is updating");
+ return null;
SQLiteDatabase db = appDBHelper.getReadableDatabase();
List<String> parts = uri.getPathSegments();
switch (sUriMatcher.match(uri)){
case LOCATION_SEARCH:
//authority/stops/location/"Lat"/"Lon"/"distance"
//distance in metres (integer)
if(parts.size()>=4 && "location".equals(parts.get(1))){
Double latitude = Double.parseDouble(parts.get(2));
Double longitude = Double.parseDouble(parts.get(3));
//converting distance to a float to not lose precision
float distance = parts.size()>=5 ? Float.parseFloat(parts.get(4))/1000 : 0.1f;
if(parts.size()>=5)
Log.d("LocationSearch"," given distance to search is "+parts.get(4)+" m");
Double distasAngle = (distance/6371)*180/Math.PI; //small angles approximation, still valid for about 500 metres
String whereClause = StopsTable.COL_LAT+ "< "+(latitude+distasAngle)+" AND "
+StopsTable.COL_LAT +" > "+(latitude-distasAngle)+" AND "+
StopsTable.COL_LONG+" < "+(longitude+distasAngle)+" AND "+StopsTable.COL_LONG+" > "+(longitude-distasAngle);
//Log.d("Provider-LOCSearch","Querying stops by position, query args: \n"+whereClause);
return db.query(StopsTable.TABLE_NAME,projection,whereClause,null,null,null,null);
}
else {
Log.w(DEBUG_TAG,"Not enough parameters");
if(parts.size()>=5) for(String s:parts) Log.d(DEBUG_TAG,"\t element "+parts.indexOf(s)+" is: "+s);
return null;
}
case FAVORITES_OP:
final String stopFavSelection = UserDB.getFavoritesColumnNamesAsArray[0]+" = ?";
db = udbhelper.getReadableDatabase();
Log.d(DEBUG_TAG,"Asked information on Favorites about stop with id "+uri.getLastPathSegment());
return db.query(UserDB.TABLE_NAME,projection,stopFavSelection,new String[]{uri.getLastPathSegment()},null,null,sortOrder);
case STOP_OP:
//Let's try this plain and simple
final String[] selectionValues = {uri.getLastPathSegment()};
final String stopSelection = StopsTable.COL_ID+" = ?";
Log.d(DEBUG_TAG,"Asked information about stop with id "+selectionValues[0]);
return db.query(StopsTable.TABLE_NAME,projection,stopSelection,selectionValues,null,null,sortOrder);
default:
Log.d("DataProvider","got request "+uri.getPath()+" which doesn't match anything");
}
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO: Implement this to handle requests to update one or more rows.
throw new UnsupportedOperationException("Not yet implemented");
}
// public static Uri getBaseUriGivenOp(int operationType);
public static Uri.Builder getUriBuilderToComplete(){
final Uri.Builder b = new Uri.Builder();
b.scheme("content").authority(AUTHORITY);
return b;
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
}
diff --git a/src/it/reyboz/bustorino/middleware/AppLocationManager.java b/src/it/reyboz/bustorino/middleware/AppLocationManager.java
index 3997ab85..8aa4573f 100644
--- a/src/it/reyboz/bustorino/middleware/AppLocationManager.java
+++ b/src/it/reyboz/bustorino/middleware/AppLocationManager.java
@@ -1,168 +1,197 @@
/*
BusTO (middleware)
Copyright (C) 2019 Fabio Mazza
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.middleware;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import it.reyboz.bustorino.util.LocationCriteria;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.ListIterator;
/**
* Singleton class used to access location. Possibly extended with other location sources.
*/
public class AppLocationManager implements LocationListener {
public static final int LOCATION_GPS_AVAILABLE = 22;
public static final int LOCATION_UNAVAILABLE = -22;
private Context con;
private LocationManager locMan;
public static final String DEBUG_TAG = "BUSTO LocAdapter";
private final String BUNDLE_LOCATION = "location";
private static AppLocationManager instance;
private int oldGPSLocStatus = LOCATION_UNAVAILABLE;
+ private int minimum_time_milli = -1;
private ArrayList<WeakReference<LocationRequester>> requestersRef = new ArrayList<>();
private AppLocationManager(Context con) {
this.con = con;
locMan = (LocationManager) con.getSystemService(Context.LOCATION_SERVICE);
}
public static AppLocationManager getInstance(Context con) {
if(instance==null) instance = new AppLocationManager(con.getApplicationContext());
return instance;
}
- private void startRequestingPosition(){
+ private void requestGPSPositionUpdates(){
+ final int timeinterval = (minimum_time_milli>0 && minimum_time_milli<Integer.MAX_VALUE)? minimum_time_milli : 2000;
try {
- locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5, this);
+ locMan.removeUpdates(this);
+ locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, timeinterval, 5, this);
} catch (SecurityException exc){
exc.printStackTrace();
Toast.makeText(con,"Cannot access GPS location",Toast.LENGTH_SHORT).show();
}
}
- private void cleanRequesters(){
+ private void cleanAndUpdateRequesters(){
+ minimum_time_milli = Integer.MAX_VALUE;
ListIterator<WeakReference<LocationRequester>> iter = requestersRef.listIterator();
while(iter.hasNext()){
final LocationRequester cReq = iter.next().get();
if(cReq==null) iter.remove();
+ else {
+ minimum_time_milli = Math.min(cReq.getLocationCriteria().getTimeInterval(),minimum_time_milli);
+ }
}
+ Log.d(DEBUG_TAG,"Updated requesters, got "+requestersRef.size()+" listeners to update every "+minimum_time_milli+" ms at least");
}
public void addLocationRequestFor(LocationRequester req){
boolean present = false;
+ minimum_time_milli = Integer.MAX_VALUE;
ListIterator<WeakReference<LocationRequester>> iter = requestersRef.listIterator();
while(iter.hasNext()){
final LocationRequester cReq = iter.next().get();
if(cReq==null) iter.remove();
else if(cReq.equals(req)){
present = true;
+ minimum_time_milli = Math.min(cReq.getLocationCriteria().getTimeInterval(),minimum_time_milli);
}
}
if(!present) {
WeakReference<LocationRequester> newref = new WeakReference<>(req);
requestersRef.add(newref);
+ minimum_time_milli = Math.min(req.getLocationCriteria().getTimeInterval(),minimum_time_milli);
+ Log.d(DEBUG_TAG,"Added new stop requester, instance of "+req.getClass().getSimpleName());
}
if(requestersRef.size()>0){
- startRequestingPosition();
+ requestGPSPositionUpdates();
+
}
}
public void removeLocationRequestFor(LocationRequester req){
+ minimum_time_milli = Integer.MAX_VALUE;
ListIterator<WeakReference<LocationRequester>> iter = requestersRef.listIterator();
while(iter.hasNext()){
final LocationRequester cReq = iter.next().get();
if(cReq==null || cReq.equals(req)) iter.remove();
+ else {
+ minimum_time_milli = Math.min(cReq.getLocationCriteria().getTimeInterval(),minimum_time_milli);
+ }
+ }
+ if(requestersRef.size()<=0){
+ locMan.removeUpdates(this);
+ } else {
+ requestGPSPositionUpdates();
}
}
private void sendLocationStatusToAll(int status){
ListIterator<WeakReference<LocationRequester>> iter = requestersRef.listIterator();
while(iter.hasNext()){
final LocationRequester cReq = iter.next().get();
if(cReq==null) iter.remove();
else cReq.onLocationStatusChanged(status);
}
}
@Override
public void onLocationChanged(Location location) {
Log.d("GPSLocationListener","found location:\nlat: "+location.getLatitude()+" lon: "+location.getLongitude()+"\naccuracy: "+location.getAccuracy());
ListIterator<WeakReference<LocationRequester>> iter = requestersRef.listIterator();
+ int new_min_interval = Integer.MAX_VALUE;
while(iter.hasNext()){
- final LocationRequester cReq = iter.next().get();
- if(cReq==null) iter.remove();
+ final LocationRequester requester = iter.next().get();
+ if(requester==null) iter.remove();
else{
- final LocationCriteria cr = cReq.getLocationCriteria();
- if(location.getAccuracy()<cr.getMinAccuracy()){
- cReq.onLocationChanged(location);
+ final long timeNow = System.currentTimeMillis();
+ final LocationCriteria criteria = requester.getLocationCriteria();
+ if(location.getAccuracy()<criteria.getMinAccuracy() &&
+ (timeNow - requester.getLastUpdateTimeMillis())>criteria.getTimeInterval()){
+ requester.onLocationChanged(location);
+ Log.d("AppLocationManager","Updating position for instance of requester "+requester.getClass().getSimpleName());
}
-
+ //update minimum time interval
+ new_min_interval = Math.min(requester.getLocationCriteria().getTimeInterval(),new_min_interval);
}
}
+ minimum_time_milli = new_min_interval;
if(requestersRef.size()==0){
//stop requesting the position
locMan.removeUpdates(this);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
//IF ANOTHER LOCATION SOURCE IS READY, USE IT
//OTHERWISE, SIGNAL THAT WE HAVE NO LOCATION
if(oldGPSLocStatus !=status){
if(status == LocationProvider.OUT_OF_SERVICE || status == LocationProvider.TEMPORARILY_UNAVAILABLE) {
sendLocationStatusToAll(LOCATION_UNAVAILABLE);
}else if(status == LocationProvider.AVAILABLE){
sendLocationStatusToAll(LOCATION_GPS_AVAILABLE);
}
oldGPSLocStatus = status;
}
}
@Override
public void onProviderEnabled(String provider) {
- startRequestingPosition();
+ requestGPSPositionUpdates();
}
@Override
public void onProviderDisabled(String provider) {
locMan.removeUpdates(this);
}
public interface LocationRequester{
void onLocationChanged(Location loc);
void onLocationStatusChanged(int status);
+ long getLastUpdateTimeMillis();
LocationCriteria getLocationCriteria();
}
}
diff --git a/src/it/reyboz/bustorino/middleware/AsyncDataDownload.java b/src/it/reyboz/bustorino/middleware/AsyncDataDownload.java
index 180dcda7..18907f78 100644
--- a/src/it/reyboz/bustorino/middleware/AsyncDataDownload.java
+++ b/src/it/reyboz/bustorino/middleware/AsyncDataDownload.java
@@ -1,318 +1,318 @@
/*
BusTO (middleware)
Copyright (C) 2018 Fabio Mazza
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.middleware;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import it.reyboz.bustorino.R;
import it.reyboz.bustorino.backend.*;
import it.reyboz.bustorino.fragments.FragmentHelper;
import it.reyboz.bustorino.middleware.NextGenDB.Contract.*;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.Calendar;
/**
* This should be used to download data, but not to display it
*/
public class AsyncDataDownload extends AsyncTask<String,Fetcher.result,Object>{
private static final String TAG = "BusTO-DataDownload";
private boolean failedAll = false;
private AtomicReference<Fetcher.result> res;
private RequestType t;
private String query;
WeakReference<FragmentHelper> helperRef;
private ArrayList<Thread> otherActivities = new ArrayList<>();
public AsyncDataDownload(RequestType type,FragmentHelper fh) {
t = type;
helperRef = new WeakReference<>(fh);
fh.setLastTaskRef(new WeakReference<AsyncDataDownload>(this));
res = new AtomicReference<>();
}
@Override
protected Object doInBackground(String... params) {
RecursionHelper r;
boolean success=false;
Object result;
switch (t){
case ARRIVALS:
r = new RecursionHelper<>(new ArrivalsFetcher[] {new FiveTAPIFetcher(),new GTTJSONFetcher(), new FiveTScraperFetcher()});
break;
case STOPS:
r = new RecursionHelper<>(new StopsFinderByName[] {new GTTStopsFetcher(), new FiveTStopsFetcher()});
break;
default:
//TODO put error message
return null;
}
FragmentHelper fh = helperRef.get();
//If the FragmentHelper is null, that means the activity doesn't exist anymore
if (fh == null){
return null;
}
//Log.d(TAG,"refresh layout reference is: "+fh.isRefreshLayoutReferenceTrue());
while(r.valid()) {
if(this.isCancelled()) {
return null;
}
//get the data from the fetcher
switch (t){
case ARRIVALS:
ArrivalsFetcher f = (ArrivalsFetcher) r.getAndMoveForward();
Log.d(TAG,"Using the ArrivalsFetcher: "+f.getClass());
Stop lastSearchedBusStop = fh.getLastSuccessfullySearchedBusStop();
Palina p;
String stopID;
if(params.length>0)
stopID=params[0]; //(it's a Palina)
else if(lastSearchedBusStop!=null)
stopID = lastSearchedBusStop.ID; //(it's a Palina)
else {
publishProgress(Fetcher.result.QUERY_TOO_SHORT);
return null;
}
//Skip the FiveTAPIFetcher for the Metro Stops because it shows incomprehensible arrival times
if(f instanceof FiveTAPIFetcher && Integer.parseInt(stopID)>= 8200)
continue;
p= f.ReadArrivalTimesAll(stopID,res);
publishProgress(res.get());
if(f instanceof FiveTAPIFetcher){
AtomicReference<Fetcher.result> gres = new AtomicReference<>();
List<Route> branches = ((FiveTAPIFetcher) f).getDirectionsForStop(stopID,gres);
if(gres.get() == Fetcher.result.OK){
p.addInfoFromRoutes(branches);
Thread t = new Thread(new BranchInserter(branches,fh,stopID));
t.start();
otherActivities.add(t);
}
//put updated values into Database
}
if(lastSearchedBusStop != null && res.get()== Fetcher.result.OK) {
// check that we don't have the same stop
if(lastSearchedBusStop.ID.equals(p.ID)) {
// searched and it's the same
String sn = lastSearchedBusStop.getStopDisplayName();
if(sn != null) {
// "merge" Stop over Palina and we're good to go
p.mergeNameFrom(lastSearchedBusStop);
}
}
}
result = p;
//TODO: find a way to avoid overloading the user with toasts
break;
case STOPS:
StopsFinderByName finder = (StopsFinderByName) r.getAndMoveForward();
List<Stop> resultList= finder.FindByName(params[0], this.res); //it's a List<Stop>
Log.d(TAG,"Using the StopFinderByName: "+finder.getClass());
query =params[0];
result = resultList; //dummy result
break;
default:
result = null;
}
//find if it went well
if(res.get()== Fetcher.result.OK) {
//wait for other threads to finish
for(Thread t: otherActivities){
try {
t.join();
} catch (InterruptedException e) {
//do nothing
}
}
return result;
}
}
//at this point, we are sure that the result has been negative
failedAll=true;
return null;
}
@Override
protected void onProgressUpdate(Fetcher.result... values) {
FragmentHelper fh = helperRef.get();
if (fh!=null)
for (Fetcher.result r : values){
//TODO: make Toast
fh.showErrorMessage(r);
}
else {
Log.w(TAG,"We had to show some progress but activity was destroyed");
}
}
@Override
protected void onPostExecute(Object o) {
FragmentHelper fh = helperRef.get();
if(failedAll || o == null || fh == null){
//everything went bad
if(fh!=null) fh.toggleSpinner(false);
cancel(true);
//TODO: send message here
return;
}
if(isCancelled()) return;
switch (t){
case ARRIVALS:
Palina palina = (Palina) o;
fh.createOrUpdateStopFragment(palina);
break;
case STOPS:
//this should never be a problem
List<Stop> stopList = (List<Stop>) o;
if(query!=null && !isCancelled()) {
fh.createFragmentFor(stopList,query);
} else Log.e(TAG,"QUERY NULL, COULD NOT CREATE FRAGMENT");
break;
case DBUPDATE:
break;
}
}
@Override
protected void onCancelled() {
FragmentHelper fh = helperRef.get();
if (fh!=null) fh.toggleSpinner(false);
}
@Override
protected void onPreExecute() {
FragmentHelper fh = helperRef.get();
if (fh!=null) fh.toggleSpinner(true);
}
public enum RequestType {
ARRIVALS,STOPS,DBUPDATE
}
public class BranchInserter implements Runnable{
private List<Route> routesToInsert;
private String stopID;
private FragmentHelper fragmentHelper;
public BranchInserter(List<Route> routesToInsert,FragmentHelper fh,String stopID) {
this.routesToInsert = routesToInsert;
this.stopID = stopID;
this.fragmentHelper = fh;
}
@Override
public void run() {
ContentValues[] values = new ContentValues[routesToInsert.size()];
ArrayList<ContentValues> connectionsVals = new ArrayList<>(routesToInsert.size()*4);
long starttime,endtime;
for (Route r:routesToInsert){
//if it has received an interrupt, stop
if(Thread.interrupted()) return;
//otherwise, build contentValues
final ContentValues cv = new ContentValues();
cv.put(BranchesTable.COL_BRANCHID,r.branchid);
- cv.put(LinesTable.COLUMN_NAME,r.name);
+ cv.put(LinesTable.COLUMN_NAME,r.getName());
cv.put(BranchesTable.COL_DIRECTION,r.destinazione);
cv.put(BranchesTable.COL_DESCRIPTION,r.description);
for (int day :r.serviceDays) {
switch (day){
case Calendar.MONDAY:
cv.put(BranchesTable.COL_LUN,1);
break;
case Calendar.TUESDAY:
cv.put(BranchesTable.COL_MAR,1);
break;
case Calendar.WEDNESDAY:
cv.put(BranchesTable.COL_MER,1);
break;
case Calendar.THURSDAY:
cv.put(BranchesTable.COL_GIO,1);
break;
case Calendar.FRIDAY:
cv.put(BranchesTable.COL_VEN,1);
break;
case Calendar.SATURDAY:
cv.put(BranchesTable.COL_SAB,1);
break;
case Calendar.SUNDAY:
cv.put(BranchesTable.COL_DOM,1);
break;
}
}
if(r.type!=null) cv.put(BranchesTable.COL_TYPE, r.type.getCode());
cv.put(BranchesTable.COL_FESTIVO, r.festivo.getCode());
values[routesToInsert.indexOf(r)] = cv;
for(int i=0; i<r.getStopsList().size();i++){
String stop = r.getStopsList().get(i);
final ContentValues connVal = new ContentValues();
connVal.put(ConnectionsTable.COLUMN_STOP_ID,stop);
connVal.put(ConnectionsTable.COLUMN_ORDER,i);
connVal.put(ConnectionsTable.COLUMN_BRANCH,r.branchid);
//add to global connVals
connectionsVals.add(connVal);
}
}
starttime = System.currentTimeMillis();
ContentResolver cr = fragmentHelper.getContentResolver();
try {
cr.bulkInsert(Uri.parse("content://" + AppDataProvider.AUTHORITY + "/branches/"), values);
endtime = System.currentTimeMillis();
Log.d("DataDownload", "Inserted branches, took " + (endtime - starttime) + " ms");
} catch (SQLException exc){
Log.e("AsyncDataDownload","Inserting data: some error happened, aborting the database insert");
exc.printStackTrace();
return;
}
starttime = System.currentTimeMillis();
ContentValues[] valArr = connectionsVals.toArray(new ContentValues[0]);
Log.d("DataDownloadInsert","inserting "+valArr.length+" connections");
int rows = fragmentHelper.insertBatchDataInNextGenDB(valArr,ConnectionsTable.TABLE_NAME);
endtime = System.currentTimeMillis();
Log.d("DataDownload","Inserted connections found, took "+(endtime-starttime)+" ms, inserted "+rows+" rows");
}
}
}
diff --git a/src/it/reyboz/bustorino/middleware/DatabaseUpdateService.java b/src/it/reyboz/bustorino/middleware/DatabaseUpdateService.java
index fe800562..cdae12ac 100644
--- a/src/it/reyboz/bustorino/middleware/DatabaseUpdateService.java
+++ b/src/it/reyboz/bustorino/middleware/DatabaseUpdateService.java
@@ -1,270 +1,270 @@
/*
BusTO (middleware)
Copyright (C) 2018 Fabio Mazza
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.middleware;
import android.app.IntentService;
import android.content.*;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import android.util.Log;
import it.reyboz.bustorino.ActivityMain;
import it.reyboz.bustorino.R;
import it.reyboz.bustorino.backend.Fetcher;
import it.reyboz.bustorino.backend.FiveTAPIFetcher;
import it.reyboz.bustorino.backend.Route;
import it.reyboz.bustorino.backend.Stop;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicReference;
import static it.reyboz.bustorino.middleware.NextGenDB.Contract.*;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
*/
public class DatabaseUpdateService extends IntentService {
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_UPDATE = "it.reyboz.bustorino.middleware.action.UPDATE_DB";
private static final String DB_VERSION = "NextGenDB.GTTVersion";
private static final String DEBUG_TAG = "DatabaseService_BusTO";
// TODO: Rename parameters
private static final String TRIAL = "it.reyboz.bustorino.middleware.extra.TRIAL";
private static final String COMPULSORY = "compulsory_update";
private static final int MAX_TRIALS = 5;
private static final int VERSION_UNAIVALABLE = -2;
public DatabaseUpdateService() {
super("DatabaseUpdateService");
}
private boolean isRunning;
private int updateTrial;
/**
* Starts this service to perform action Foo with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
public static void startDBUpdate(Context con, int trial, @Nullable Boolean mustUpdate){
Intent intent = new Intent(con, DatabaseUpdateService.class);
intent.setAction(ACTION_UPDATE);
intent.putExtra(TRIAL,trial);
if(mustUpdate!=null){
intent.putExtra(COMPULSORY,mustUpdate);
}
con.startService(intent);
}
public static void startDBUpdate(Context con) {
startDBUpdate(con, 0, false);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_UPDATE.equals(action)) {
Log.d(DEBUG_TAG,"Started action update");
SharedPreferences shPr = getSharedPreferences(getString(R.string.mainSharedPreferences),MODE_PRIVATE);
int versionDB = shPr.getInt(DB_VERSION,-1);
final int trial = intent.getIntExtra(TRIAL,-1);
updateTrial = trial;
UpdateRequestParams params = new UpdateRequestParams(intent);
int newVersion = getNewVersion(params);
if(newVersion==VERSION_UNAIVALABLE){
//NOTHING LEFT TO DO
return;
}
Log.d(DEBUG_TAG,"newDBVersion: "+newVersion+" oldVersion: "+versionDB);
if(params.mustUpdate || versionDB==-1 || newVersion>versionDB){
final SharedPreferences.Editor editor = shPr.edit();
editor.putBoolean(getString(R.string.databaseUpdatingPref),true);
editor.commit();
Log.d(DEBUG_TAG,"Downloading the bus stops info");
final AtomicReference<Fetcher.result> gres = new AtomicReference<>();
if(!performDBUpdate(gres))
restartDBUpdateifPossible(params,gres);
else {
editor.putInt(DB_VERSION,newVersion);
// BY COMMENTING THIS, THE APP WILL CONTINUOUSLY UPDATE THE DATABASE
editor.apply();
}
} else {
Log.d(DEBUG_TAG,"No update needed");
}
Log.d(DEBUG_TAG,"Finished update");
final SharedPreferences.Editor editor = shPr.edit();
editor.putBoolean(getString(R.string.databaseUpdatingPref),false);
editor.commit();
}
}
}
private boolean performDBUpdate(AtomicReference<Fetcher.result> gres){
final FiveTAPIFetcher f = new FiveTAPIFetcher();
final ArrayList<Stop> stops = f.getAllStopsFromGTT(gres);
//final ArrayList<ContentProviderOperation> cpOp = new ArrayList<>();
if(gres.get()!= Fetcher.result.OK){
Log.w(DEBUG_TAG,"Something went wrong downloading");
return false;
}
final NextGenDB dbHelp = new NextGenDB(getApplicationContext());
final SQLiteDatabase db = dbHelp.getWritableDatabase();
//Empty the needed tables
db.beginTransaction();
//db.execSQL("DELETE FROM "+StopsTable.TABLE_NAME);
//db.delete(LinesTable.TABLE_NAME,null,null);
//put new data
long startTime = System.currentTimeMillis();
Log.d(DEBUG_TAG,"Inserting "+stops.size()+" stops");
for (final Stop s : stops) {
final ContentValues cv = new ContentValues();
cv.put(StopsTable.COL_ID, s.ID);
cv.put(StopsTable.COL_NAME, s.getStopDefaultName());
if (s.location != null)
cv.put(StopsTable.COL_LOCATION, s.location);
cv.put(StopsTable.COL_LAT, s.getLatitude());
cv.put(StopsTable.COL_LONG, s.getLongitude());
if (s.getAbsurdGTTPlaceName() != null) cv.put(StopsTable.COL_PLACE, s.getAbsurdGTTPlaceName());
cv.put(StopsTable.COL_LINES_STOPPING, s.routesThatStopHereToString());
if (s.type != null) cv.put(StopsTable.COL_TYPE, s.type.getCode());
//Log.d(DEBUG_TAG,cv.toString());
//cpOp.add(ContentProviderOperation.newInsert(uritobeused).withValues(cv).build());
//valuesArr[i] = cv;
db.replace(StopsTable.TABLE_NAME,null,cv);
}
db.setTransactionSuccessful();
db.endTransaction();
long endTime = System.currentTimeMillis();
Log.d(DEBUG_TAG,"Inserting stops took: "+((double) (endTime-startTime)/1000)+" s");
final ArrayList<Route> routes = f.getAllLinesFromGTT(gres);
if(routes==null){
Log.w(DEBUG_TAG,"Something went wrong downloading the lines");
dbHelp.close();
return false;
}
db.beginTransaction();
startTime = System.currentTimeMillis();
for (Route r: routes){
final ContentValues cv = new ContentValues();
- cv.put(LinesTable.COLUMN_NAME,r.name);
+ cv.put(LinesTable.COLUMN_NAME,r.getName());
switch (r.type){
case BUS:
cv.put(LinesTable.COLUMN_TYPE,"URBANO");
break;
case RAILWAY:
cv.put(LinesTable.COLUMN_TYPE,"FERROVIA");
break;
case LONG_DISTANCE_BUS:
cv.put(LinesTable.COLUMN_TYPE,"EXTRA");
break;
}
cv.put(LinesTable.COLUMN_DESCRIPTION,r.description);
//db.insert(LinesTable.TABLE_NAME,null,cv);
- int rows = db.update(LinesTable.TABLE_NAME,cv,LinesTable.COLUMN_NAME+" = ?",new String[]{r.name});
+ int rows = db.update(LinesTable.TABLE_NAME,cv,LinesTable.COLUMN_NAME+" = ?",new String[]{r.getName()});
if(rows<1){ //we haven't changed anything
db.insert(LinesTable.TABLE_NAME,null,cv);
}
}
db.setTransactionSuccessful();
db.endTransaction();
endTime = System.currentTimeMillis();
Log.d(DEBUG_TAG,"Inserting lines took: "+((double) (endTime-startTime)/1000)+" s");
dbHelp.close();
return true;
}
private int getNewVersion(UpdateRequestParams params){
AtomicReference<Fetcher.result> gres = new AtomicReference<>();
String networkRequest = FiveTAPIFetcher.performAPIRequest(FiveTAPIFetcher.QueryType.STOPS_VERSION,null,gres);
if(networkRequest == null){
restartDBUpdateifPossible(params,gres);
return VERSION_UNAIVALABLE;
}
boolean needed;
try {
JSONObject resp = new JSONObject(networkRequest);
return resp.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
Log.e(DEBUG_TAG,"Error: wrong JSON response\nResponse:\t"+networkRequest);
return -4;
}
}
private void restartDBUpdateifPossible(UpdateRequestParams pars, AtomicReference<Fetcher.result> res){
if (pars.trial<MAX_TRIALS && res.get()!= Fetcher.result.PARSER_ERROR){
Log.d(DEBUG_TAG,"Update failed, starting new trial ("+pars.trial+")");
startDBUpdate(getApplicationContext(),++pars.trial,pars.mustUpdate);
}
}
/**
* Private class to hold the parameters of the request
*/
private class UpdateRequestParams{
int trial;
boolean mustUpdate;
UpdateRequestParams(Intent intent){
trial = intent.getIntExtra(TRIAL,-1);
mustUpdate = intent.getBooleanExtra(COMPULSORY, false);
}
}
/**
* Probably useless
*
* Spoiler: IT IS
public class FinishedUpdateListener implements SharedPreferences.OnSharedPreferenceChangeListener{
private OnDBStatusChangedListener thingToDo;
public FinishedUpdateListener(OnDBStatusChangedListener thingToDo) {
this.thingToDo = thingToDo;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
final String Update_KEY = getString(R.string.databaseUpdatingPref);
if(key.equals(Update_KEY)){
thingToDo.onDBUpdateStatusChanged(sharedPreferences.getBoolean(Update_KEY,true));
}
}
}
public interface OnDBStatusChangedListener {
void onDBUpdateStatusChanged(boolean isUpdating);
}
*/
}
diff --git a/src/it/reyboz/bustorino/util/LocationCriteria.java b/src/it/reyboz/bustorino/util/LocationCriteria.java
index 557760a0..d0ec316c 100644
--- a/src/it/reyboz/bustorino/util/LocationCriteria.java
+++ b/src/it/reyboz/bustorino/util/LocationCriteria.java
@@ -1,36 +1,41 @@
/*
BusTO (middleware)
Copyright (C) 2019 Fabio Mazza
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.util;
/**
* Own Location Criteria, because it's fun
*/
public class LocationCriteria {
- private float minAccuracy;
- public LocationCriteria(float minAccuracy){
+ private final float minAccuracy;
+ private final int timeInterval;
+
+ public LocationCriteria(float minAccuracy,int timeInterval){
this.minAccuracy = minAccuracy;
+ this.timeInterval = timeInterval;
}
public float getMinAccuracy() {
return minAccuracy;
}
- public void setMinAccuracy(float minAccuracy) {
- this.minAccuracy = minAccuracy;
+
+ public int getTimeInterval() {
+ return timeInterval;
}
+
}

File Metadata

Mime Type
text/x-diff
Expires
Thu, Nov 19, 02:53 (4 h, 59 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2263954
Default Alt Text
(222 KB)

Event Timeline