Page MenuHomeGitPull.it

No OneTemporary

Authored By
Unknown
Size
50 KB
Referenced Files
None
Subscribers
None
diff --git a/.classpath b/.classpath
deleted file mode 100644
index 1457e3c3..00000000
--- a/.classpath
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
- <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
- <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="src" path="gen"/>
- <classpathentry kind="output" path="bin/classes"/>
-</classpath>
diff --git a/.project b/.project
deleted file mode 100644
index 06a38f72..00000000
--- a/.project
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>BusTO</name>
- <comment>
- </comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>com.android.ide.eclipse.adt.ApkBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 13fe3204..cdcac391 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -1,108 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.reyboz.bustorino"
android:versionCode="22"
android:versionName="1.8.7">
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="23"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
- <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
+ <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
+ <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".ActivityMain"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="www.gtt.to.it"
android:pathPrefix="/cms/percorari/arrivi"
android:scheme="http"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="gtt.to.it"
android:pathPrefix="/cms/percorari/arrivi"
android:scheme="http"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="m.gtt.to.it"
android:pathPrefix="/m/it/arrivi.jsp"
android:scheme="http"/>
</intent-filter>
</activity>
<activity
android:name=".ActivityAbout"
android:label="@string/about"
android:parentActivityName=".ActivityMain"
android:theme="@style/AboutTheme">
<!-- API < 16: -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ActivityMain"/>
</activity>
<activity
android:name=".ActivityFavorites"
android:label="@string/title_activity_favorites"
android:parentActivityName=".ActivityMain"
android:theme="@style/FavTheme">
<!-- API < 16: -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ActivityMain"/>
</activity>
<provider
android:name=".middleware.AppDataProvider"
android:authorities="it.reyboz.bustorino.provider"
android:enabled="true"
android:exported="false">
</provider>
<service
android:name=".middleware.DatabaseUpdateService"
android:exported="false">
</service>
<!-- Don't show the additional frame on samsung phones -->
- <meta-data android:name="com.samsung.android.icon_container.has_icon_container"
- android:value="true" />
+ <meta-data
+ android:name="com.samsung.android.icon_container.has_icon_container"
+ android:value="true"/>
+
+ <activity
+ android:name=".ActivitySettings"
+ android:label="@string/title_activity_settings"
+ android:parentActivityName=".ActivityMain"
+ android:theme="@style/AppTheme">
+ <meta-data
+ android:name="android.support.PARENT_ACTIVITY"
+ android:value="it.reyboz.bustorino.ActivityMain"/>
+ </activity>
</application>
-</manifest>
+</manifest>
\ No newline at end of file
diff --git a/build.gradle b/build.gradle
index a3c73144..099702b1 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,62 +1,62 @@
buildscript {
repositories {
mavenCentral()
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
}
- ext{
+ ext {
support_ver = "25.3.1"
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '26.0.1'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
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 {
compile "com.android.support:support-v4:$support_ver"
compile "com.android.support:appcompat-v7:$support_ver"
compile "com.android.support:design:$support_ver"
compile "com.android.support:recyclerview-v7:$support_ver"
+ compile "com.android.support:preference-v7:$support_ver"
compile 'org.jsoup:jsoup:1.7.3'
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1'
}
}
-
diff --git a/res/menu/main.xml b/res/menu/main.xml
index fcfa2c55..0b9313db 100644
--- a/res/menu/main.xml
+++ b/res/menu/main.xml
@@ -1,52 +1,57 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="it.reyboz.bustorino.ActivityMain">
<!--suppress AndroidDomInspection --> <!-- Android Studio can't find ic_star even though it's there. -->
<item
android:id="@+id/action_favorites"
android:icon="@+drawable/ic_star"
android:orderInCategory="1"
android:title="@string/action_favorites"
app:showAsAction="ifRoom" />
<item
android:orderInCategory="2"
android:title="@string/action_about">
<menu>
<item
android:id="@+id/action_about"
android:orderInCategory="4"
android:title="@string/action_about_more" />
<item
android:id="@+id/action_news"
android:orderInCategory="5"
android:title="@string/action_news" />
<item
android:id="@+id/action_bugs"
android:orderInCategory="6"
android:title="@string/action_bugs"
app:showAsAction="never" />
<item
android:id="@+id/action_source"
android:orderInCategory="7"
android:title="@string/action_source"
app:showAsAction="never" />
<item
android:id="@+id/action_licence"
android:orderInCategory="8"
android:title="@string/action_licence"
app:showAsAction="never" />
<item
android:id="@+id/action_author"
android:orderInCategory="9"
android:title="@string/action_author"
app:showAsAction="never" />
</menu>
</item>
<item
android:id="@+id/action_help"
- android:orderInCategory="3"
+ android:orderInCategory="4"
android:title="@string/action_help"
android:visible="true" />
+ <item
+ android:id="@+id/action_settings"
+ android:orderInCategory="3"
+ android:title="@string/main_menu_pref"
+ android:visible="true" />
</menu>
\ No newline at end of file
diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml
index ff978be6..448574a9 100644
--- a/res/values-it/strings.xml
+++ b/res/values-it/strings.xml
@@ -1,86 +1,87 @@
<?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...</string>
<string name="no_stops_nearby">Nessuna fermata nei dintorni</string>
+ <string name="main_menu_pref">Preferenze</string>
</resources>
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index 55c1e590..414ebad3 100644
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -1,7 +1,8 @@
<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>
</resources>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 007ff1b1..7721a60d 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1,96 +1,101 @@
<?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...</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="pref_recents_group_title">Recent stops</string>
</resources>
diff --git a/res/values/styles.xml b/res/values/styles.xml
index 3dcb439d..8f641f20 100644
--- a/res/values/styles.xml
+++ b/res/values/styles.xml
@@ -1,25 +1,49 @@
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
<item name="colorPrimary">@color/orange_500</item>
<item name="colorPrimaryDark">@color/orange_700</item>
<item name="colorAccent">@color/teal_500</item>
+ <!-- For the preferences Fragment -->
+ <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
+
+ </style>
+ <style name="AppTheme.NoActionBar">
+ <item name="windowActionBar">false</item>
+ <item name="windowNoTitle">true</item>
+ </style>
+ <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
+ <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
+
+
+ <!-- For the preferences Fragment -->
+ <style name="PreferenceThemeOverlay.">
+ <item name="preferenceScreenStyle">@style/Preference.PreferenceScreen</item>
+ <item name="preferenceFragmentStyle">@style/PreferenceFragment</item>
+ <item name="preferenceCategoryStyle">@style/Preference.Category</item>
+ <item name="preferenceStyle">@style/Preference</item>
+ <item name="preferenceInformationStyle">@style/Preference.Information</item>
+ <item name="checkBoxPreferenceStyle">@style/Preference.CheckBoxPreference</item>
+ <item name="switchPreferenceCompatStyle">@style/Preference.SwitchPreferenceCompat</item>
+ <item name="dialogPreferenceStyle">@style/Preference.DialogPreference</item>
+ <item name="editTextPreferenceStyle">@style/Preference.DialogPreference.EditTextPreference</item>
+ <item name="preferenceFragmentListStyle">@style/PreferenceFragmentList</item>
</style>
</resources>
\ No newline at end of file
diff --git a/src/it/reyboz/bustorino/ActivityMain.java b/src/it/reyboz/bustorino/ActivityMain.java
index f7682164..01306346 100644
--- a/src/it/reyboz/bustorino/ActivityMain.java
+++ b/src/it/reyboz/bustorino/ActivityMain.java
@@ -1,632 +1,635 @@
/*
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.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
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 com.melnykov.fab.FloatingActionButton;
import android.support.design.widget.FloatingActionButton;
import it.reyboz.bustorino.backend.ArrivalsFetcher;
import it.reyboz.bustorino.backend.FiveTScraperFetcher;
import it.reyboz.bustorino.backend.FiveTStopsFetcher;
import it.reyboz.bustorino.backend.GTTJSONFetcher;
import it.reyboz.bustorino.backend.GTTStopsFetcher;
import it.reyboz.bustorino.backend.StopsFinderByName;
import it.reyboz.bustorino.fragments.*;
import it.reyboz.bustorino.middleware.*;
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;
/*
* 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";
/* // 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()});
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() {
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
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());
//locationHandler = new GPSLocationAdapter(getApplicationContext());
//--------- NEARBY STOPS--------//
//Let's search stops nearby
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && fh.getLastSuccessfullySearchedBusStop()==null && getOption(LOCATION_PERMISSION_GIVEN,false)) {
NearbyStopsFragment fr = NearbyStopsFragment.newInstance();
FragmentTransaction ft = framan.beginTransaction();
ft.add(R.id.resultFrame, fr, "Location");
ft.commitNow();
swipeRefreshLayout.setVisibility(View.VISIBLE);
swipeRefreshLayout.setEnabled(false);
} else if(!getOption(LOCATION_PERMISSION_GIVEN, false)){
assertLocationPermissions();
}
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();
}
@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("http://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("http://www.gnu.org/licenses/gpl-3.0.html");
return true;
case R.id.action_author:
openIceweasel("http://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);
}
}
@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);
handler.post(new Runnable() {
@Override
public void run() {
Log.d("mainActivity","Recreating stop fragment");
swipeRefreshLayout.setVisibility(View.VISIBLE);
NearbyStopsFragment fragment = NearbyStopsFragment.newInstance();
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();
}
});
} 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();
}
}
}
///////////////////////////////// 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(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

File Metadata

Mime Type
text/x-diff
Expires
Thu, Nov 19, 03:04 (12 h, 48 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2264035
Default Alt Text
(50 KB)

Event Timeline