diff --git a/.idea/misc.xml b/.idea/misc.xml
index d127c77..59436c9 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -1,7 +1,10 @@
+
+
+
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index bd72745..7b566ef 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -1,43 +1,43 @@
diff --git a/build.gradle b/build.gradle
index fe6eb55..95834c4 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,53 +1,53 @@
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.0-rc2'
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
- buildToolsVersion '21.1.1'
+ buildToolsVersion '21.1.2'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
lintOptions {
abortOnError false
}
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
compile 'com.android.support:support-v4:21.0.+'
compile 'com.android.support:appcompat-v7:21.0.+'
compile 'com.melnykov:floatingactionbutton:1.1.0'
}
}
\ No newline at end of file
diff --git a/bus-torino.iml b/bus-torino.iml
index acd73f6..bd6d355 100644
--- a/bus-torino.iml
+++ b/bus-torino.iml
@@ -1,89 +1,89 @@
-
-
+
+
+
-
diff --git a/proguard-project.txt b/proguard-project.txt
deleted file mode 100644
index f2fe155..0000000
--- a/proguard-project.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-# To enable ProGuard in your project, edit project.properties
-# to define the proguard.config property as described in that file.
-#
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in ${sdk.dir}/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the ProGuard
-# include property in project.properties.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
diff --git a/project.properties b/project.properties
deleted file mode 100644
index b3da295..0000000
--- a/project.properties
+++ /dev/null
@@ -1,15 +0,0 @@
-# This file is automatically generated by Android Tools.
-# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
-#
-# This file must be checked in Version Control Systems.
-#
-# To customize properties used by the Ant build system edit
-# "ant.properties", and override values to adapt the script to your
-# project structure.
-#
-# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
-#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
-
-# Project target.
-target=android-21
-android.library.reference.1=../../EclipseWorkspace/android-support-v7-appcompat
diff --git a/res/layout/activity_about.xml b/res/layout/activity_about.xml
index 65e214f..d5fcb80 100644
--- a/res/layout/activity_about.xml
+++ b/res/layout/activity_about.xml
@@ -1,16 +1,16 @@
+ tools:context="it.reyboz.bustorino.ActivityAbout" >
\ No newline at end of file
diff --git a/res/layout/activity_favorites.xml b/res/layout/activity_favorites.xml
index f6238f2..0bcd9aa 100644
--- a/res/layout/activity_favorites.xml
+++ b/res/layout/activity_favorites.xml
@@ -1,27 +1,27 @@
+ tools:context="it.reyboz.bustorino.ActivityFavorites" >
\ No newline at end of file
diff --git a/res/layout/activity_main.xml b/res/layout/activity_main.xml
index 2d7945c..7a776e9 100644
--- a/res/layout/activity_main.xml
+++ b/res/layout/activity_main.xml
@@ -1,170 +1,170 @@
+ tools:context="it.reyboz.bustorino.ActivityMain" >
-
-
+
\ No newline at end of file
diff --git a/res/layout/bus_line_passage_entry.xml b/res/layout/entry_bus_line_passage.xml
similarity index 100%
rename from res/layout/bus_line_passage_entry.xml
rename to res/layout/entry_bus_line_passage.xml
diff --git a/res/layout/bus_stop_entry.xml b/res/layout/entry_bus_stop.xml
similarity index 100%
rename from res/layout/bus_stop_entry.xml
rename to res/layout/entry_bus_stop.xml
diff --git a/res/menu/main.xml b/res/menu/main.xml
index 19d2ceb..09efe55 100644
--- a/res/menu/main.xml
+++ b/res/menu/main.xml
@@ -1,23 +1,23 @@
\ No newline at end of file
diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml
index 844f1b0..2f13b0a 100644
--- a/res/values-it/strings.xml
+++ b/res/values-it/strings.xml
@@ -1,72 +1,72 @@
Stai utilizzando l\'ultimo ritrovato in materia di rispetto della tua privacy.CercaNumero fermataNome fermataInserisci il numero della fermataAlcuni caratteri non sono stati riconosciutiVerifica l\'accesso ad Internet!Nessun arrivo previsto per questa fermataFermata: %1$sLinee: %1$s
- Risultati…
+ Scegli la fermata…Nessun passaggioInformazioniPreferitiFermata aggiunta ai preferitiPreferitiPremi sul nome di una fermata per inserirla in questa listaRimuoviInformazioni- Premi sul nome della fermata per aggiungerla ai preferiti.\n- Come leggere gli orari:\n 12:56* Orario in tempo reale\n 12:56 Orario programmato\n- Trascina giù per aggiornare l\'orario.OK !Aiuto
Benvenuto!
Grazie per aver scelto BusTO, un\'app indipendente nata dalla necessità di spostarsi a Torino attraverso software libero:
Perchè usare BusTO?
- Non sei monitorato
- Non ci sono pubblicità
- La tua privacy è al sicuro
- Inoltre l\'app è molto leggera!
Come Funziona?
Quest\'app ottiene i passaggi dei bus in tempo reale filtrando i dati forniti pubblicamente sul sito www.5t.torino.it «per uso personale».
Ingredienti:
- Valerio Bozzolan come sviluppatore principale.
- Marco Gagino come intenso collaboratore.
- Paolo Alloatti per l\'idea dell\'icona.
- JSoup libreria per "web scaping".
- makovkastar per i floating button.
- - Google per le icone Material Design.
+ - Google per le icone Material Design.
E tutti i contributori!
Licenze
L\'app e il relativo codice sorgente sono distribuiti sotto doppia licenza:
GNU GPL e CC By-Sa.
Ciò significa che puoi usare, studiare, migliorare e ricondividere quest\'app con qualunque mezzo e per qualsiasi scopo: a patto di mantenere sempre questi diritti a tua volta e di attribuire sempre a Valerio Bozzolan gli \"sforzi\" per il codice sorgente.
Note
Quest\'applicazione è rilasciata nella speranza che sia utile a tutti ma senza alcuna garanzia.
]]>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 3be1d0c..fbc609b 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1,70 +1,70 @@
BusTOStai utilizzando l\'ultimo ritrovato in materia di rispetto della tua privacy.SearchBus stop numberBus stop nameInsert bus stop numberSorry but you are using not allowed charactersVerify the state of your Internet connection!No bus is supposed to arrive at this stopArrivals at: %1$s
- Search results…
+ Choose the bus stop…Lines: %1$sNo passagesAboutFavoritesBus stop is now in your favoritesFavoritesPress on a bus stop name to populate this listDeleteAbout- Press on the bus stop name above to add it to the favourites.\n- How to read timelines:\n 12:56* Real time arrival\n 12:56 Scheduled time of arrival\n- Pull down to refresh the timetable.GOT IT!Help
Welcome!
Thanks for using BusTO, an indipendent app useful to move around Torino using a Free/Libre and Open Source software.
Why using this app?
- You\'ll never be tracked
- You\'ll never see boring ads
- We\'ll always respect your privacy
- Moreover, it\'s lightweight!
How does it work?
This app will show you the timetable of the buses using the information published on the site http://www.5t.torino.it.
Who worked on BusTO:
- Valerio Bozzolan, the main developer.
- Marco Gagino, contributor.
- Paolo Alloatti, the concept of the icon.
- JSoup for the web scraper library.
- makovkastar for the floating buttons.
- Google for Material Design icons.
Thanks to all the contributors!
Licenses
The app and the related source code are released by Valerio Bozzolan under the terms of two different licences:
the Gnu General Public License v3+ (GNU GPLv3+) and the Creative Commons Attribution - Share alike 4.0 International (CC 4.0 By-Sa).
So everyone is allowed to use, to study, to improve and to share this app by any kind of means and for any purpose: under the conditions of manteining this rights and of attributing the original source code to Valerio Bozzolan.
Notes
This app has been developed hoping to be useful to everyone but without any warranty (such as commercial warranties). If you discover some bugs or if you have some idea, please report them.
This translation is kindly provided by Riccardo Caniato and Marco Gagino.
]]>
diff --git a/src/it/reyboz/bustorino/AboutActivity.java b/src/it/reyboz/bustorino/ActivityAbout.java
similarity index 97%
rename from src/it/reyboz/bustorino/AboutActivity.java
rename to src/it/reyboz/bustorino/ActivityAbout.java
index e2dc48c..2189750 100644
--- a/src/it/reyboz/bustorino/AboutActivity.java
+++ b/src/it/reyboz/bustorino/ActivityAbout.java
@@ -1,52 +1,52 @@
/*
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 .
*/
package it.reyboz.bustorino;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.os.Bundle;
import android.widget.TextView;
-public class AboutActivity extends ActionBarActivity {
+public class ActivityAbout extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
Spanned htmlText = Html.fromHtml(getResources().getString(
R.string.about_history));
TextView aboutTextView = (TextView) findViewById(R.id.aboutTextView);
aboutTextView.setText(htmlText);
aboutTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
/*
* @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
* menu; this adds items to the action bar if it is present. //
* getMenuInflater().inflate(R.menu.about, menu); 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. //int id = item.getItemId(); //if (id ==
* R.id.action_settings) { // return true; //} return
* super.onOptionsItemSelected(item); }
*/
}
diff --git a/src/it/reyboz/bustorino/FavoritesActivity.java b/src/it/reyboz/bustorino/ActivityFavorites.java
similarity index 94%
rename from src/it/reyboz/bustorino/FavoritesActivity.java
rename to src/it/reyboz/bustorino/ActivityFavorites.java
index 3e3c706..16fe331 100644
--- a/src/it/reyboz/bustorino/FavoritesActivity.java
+++ b/src/it/reyboz/bustorino/ActivityFavorites.java
@@ -1,185 +1,185 @@
/*
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 .
*/
package it.reyboz.bustorino;
-import it.reyboz.bustorino.MyDB.BusLine;
-import it.reyboz.bustorino.MyDB.BusStop;
-import it.reyboz.bustorino.MyDB.BusStopServeLine;
+import it.reyboz.bustorino.lab.MyDB;
+import it.reyboz.bustorino.lab.MyDB.BusLine;
+import it.reyboz.bustorino.lab.MyDB.BusStop;
+import it.reyboz.bustorino.lab.MyDB.BusStopServeLine;
import java.util.ArrayList;
import java.util.HashMap;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
-import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
-public class FavoritesActivity extends ActionBarActivity {
+public class ActivityFavorites extends ActionBarActivity {
private ListView favoriteListView;
private MyDB mDbHelper;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
mDbHelper = new MyDB(this);
db = mDbHelper.getWritableDatabase();
favoriteListView = (ListView) findViewById(R.id.favoriteListView);
createFavoriteList();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.favoriteListView) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_favourites_entry, menu);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
String busStopID = ((TextView) (info.targetView)
.findViewById(R.id.busStopID)).getText().toString();
switch (item.getItemId()) {
case R.id.action_favourite_entry_delete:
db.delete(BusStop.TABLE_NAME,
MyDB.somethingEqualsInt(BusStop.COLUMN_NAME_BUSSTOP_ID),
new String[] { busStopID });
createFavoriteList();
return true;
default:
return super.onContextItemSelected(item);
}
}
void createFavoriteList() {
ArrayList> data = new ArrayList>();
String query = MyDB.SELECT_ALL_FROM
+ BusStop.TABLE_NAME
+ MyDB.WHERE
+ MyDB.somethingEqualsInt(BusStop.COLUMN_NAME_BUSSTOP_ISFAVORITE)
+ MyDB.ORDER_BY + BusStop.COLUMN_NAME_BUSSTOP_NAME + MyDB.ASC;
Cursor cursor = db
.rawQuery(query, new String[] { BusStop.IS_FAVORITE });
while (cursor.moveToNext()) {
HashMap singleEntry = new HashMap();
int busStopID = cursor.getInt(cursor
.getColumnIndex(MyDB.BusStop.COLUMN_NAME_BUSSTOP_ID));
String busStopName = cursor.getString(cursor
.getColumnIndex(MyDB.BusStop.COLUMN_NAME_BUSSTOP_NAME));
// Get bus Lines
String queryLines = MyDB.SELECT
+ BusLine.COLUMN_NAME_BUSLINE_NAME
+ MyDB.FROM
+ BusStopServeLine.TABLE_NAME
+ MyDB.COMMA
+ BusLine.TABLE_NAME
+ MyDB.WHERE
+ MyDB.somethingEqualsInt(BusStopServeLine
.getColumn(BusStopServeLine.COLUMN_NAME_BUSSTOP_ID))
+ MyDB.AND
+ BusStopServeLine
.getColumn(BusStopServeLine.COLUMN_NAME_BUSLINE_ID)
+ MyDB.EQUALS
+ BusLine.getColumn(BusLine.COLUMN_NAME_BUSLINE_ID)
+ MyDB.ORDER_BY + BusLine.COLUMN_NAME_BUSLINE_NAME
+ MyDB.ASC;
Cursor cursorLines = db.rawQuery(queryLines,
new String[] { String.valueOf(busStopID) });
String busLineNames = "";
while (cursorLines.moveToNext()) {
if (busLineNames != "") {
busLineNames += ", ";
}
busLineNames += cursorLines.getString(0);
Log.d("FavoritesActivity",
"Bus line name: " + cursorLines.getString(0));
}
cursorLines.close();
singleEntry.put("bus-stop-ID", busStopID);
singleEntry.put("bus-stop-name", busStopName);
singleEntry.put("bus-line-names", String.format(getResources()
.getString(R.string.lines), busLineNames));
data.add(singleEntry);
}
cursor.close();
// If no data is found show a friendly message
if (data.isEmpty()) {
favoriteListView.setVisibility(View.INVISIBLE);
TextView favoriteTipTextView = (TextView) findViewById(R.id.favoriteTipTextView);
favoriteTipTextView.setVisibility(View.VISIBLE);
}
// Show results
String[] from = { "bus-stop-ID", "bus-stop-name", "bus-line-names" };
int[] to = { R.id.busStopID, R.id.busStopName, R.id.busLineNames };
SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),
- data, R.layout.bus_stop_entry, from, to);
+ data, R.layout.entry_bus_stop, from, to);
favoriteListView.setAdapter(adapter);
favoriteListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView> av, View view,
int i, long l) {
String busStopID = ((TextView) view
.findViewById(R.id.busStopID)).getText()
.toString();
Log.d("FavoritesActivity", "Tapped on bus stop: "
+ busStopID);
- Intent intent = new Intent(FavoritesActivity.this,
- MainActivity.class);
+ Intent intent = new Intent(ActivityFavorites.this,
+ ActivityMain.class);
Bundle b = new Bundle();
b.putString("busStopID", busStopID);
intent.putExtras(b);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
registerForContextMenu(favoriteListView);
}
}
diff --git a/src/it/reyboz/bustorino/MainActivity.java b/src/it/reyboz/bustorino/ActivityMain.java
similarity index 79%
rename from src/it/reyboz/bustorino/MainActivity.java
rename to src/it/reyboz/bustorino/ActivityMain.java
index da930d8..4abf888 100644
--- a/src/it/reyboz/bustorino/MainActivity.java
+++ b/src/it/reyboz/bustorino/ActivityMain.java
@@ -1,505 +1,457 @@
/*
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 .
*/
package it.reyboz.bustorino;
import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import it.reyboz.bustorino.GTTSiteSucker.BusLine;
-import it.reyboz.bustorino.GTTSiteSucker.BusStop;
+import it.reyboz.bustorino.lab.AsyncWget;
+import it.reyboz.bustorino.lab.GTTSiteSucker;
+import it.reyboz.bustorino.lab.GTTSiteSucker.BusLine;
+import it.reyboz.bustorino.lab.GTTSiteSucker.BusStop;
+import it.reyboz.bustorino.lab.MyDB;
+import it.reyboz.bustorino.lab.NetworkTools;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
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.AdapterView;
import android.widget.Button;
import android.widget.EditText;
-import android.widget.ImageView;
-import android.widget.ListView;
import android.widget.ProgressBar;
-import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.view.KeyEvent;
import com.melnykov.fab.FloatingActionButton;
-public class MainActivity extends ActionBarActivity {
+public class ActivityMain extends ActionBarActivity {
private final boolean DOUBLE_SPINNER = true;
private final boolean NORMAL_SPINNER = false;
/*
* Various layout elements
*/
private EditText busStopSearchByIDEditText;
private EditText busStopSearchByNameEditText;
private TextView busStopNameTextView;
private ProgressBar progressBar;
private TextView howDoesItWorkTextView;
private Button hideHintButton;
private MenuItem actionHelpMenuItem;
- private ListView resultsListView;
+ private it.reyboz.bustorino.layouts.BusListView resultsListView;
private SwipeRefreshLayout swipeRefreshLayout;
private FloatingActionButton floatingActionButton;
/*
* @see swipeRefreshLayout
*/
private Handler handler = new Handler();
private final Runnable refreshing = new Runnable() {
public void run() {
runSearchTask(String.valueOf(lastSearchedBusStopID), DOUBLE_SPINNER);
}
};
/**
* Last successfully searched bus stop ID
*/
private Integer lastSearchedBusStopID;
private final boolean SEARCH_BY_ID = true;
private final boolean SEARCH_BY_NAME = false;
private boolean searchMode;
private MyAsyncWget myAsyncWget;
private MyDB mDbHelper;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
busStopSearchByIDEditText = (EditText) findViewById(R.id.busStopSearchByIDEditText);
busStopSearchByNameEditText = (EditText) findViewById(R.id.busStopSearchByNameEditText);
busStopNameTextView = (TextView) findViewById(R.id.busStopNameTextView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
howDoesItWorkTextView = (TextView) findViewById(R.id.howDoesItWorkTextView);
hideHintButton = (Button) findViewById(R.id.hideHintButton);
- resultsListView = (ListView) findViewById(R.id.resultsListView);
+ resultsListView = (it.reyboz.bustorino.layouts.BusListView) findViewById(R.id.resultsListView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton);
myAsyncWget = new MyAsyncWget();
floatingActionButton.attachToListView(resultsListView);
// IME_ACTION_SEARCH keyboard option
busStopSearchByIDEditText
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
onSearchClick(v);
return true;
}
return false;
}
});
// IME_ACTION_SEARCH keyboard option
busStopSearchByNameEditText
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
onSearchClick(v);
return true;
}
return false;
}
});
// Get database in write mode
mDbHelper = new MyDB(this);
db = mDbHelper.getWritableDatabase();
// Called when the layout is pulled down
swipeRefreshLayout
.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
handler.post(refreshing);
}
});
/**
* Deprecated! D:
*
* @author Marco Gagino!!!
* @deprecated
* @see https://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html#setColorSchemeResources%28int...%29
*/
swipeRefreshLayout.setColorScheme(R.color.blue_500, R.color.orange_500);
searchMode = SEARCH_BY_ID;
setSearchModeBusStopID();
// Intercept calls from other activities
Bundle b = getIntent().getExtras();
if (b != null) {
String busStopID = b.getString("busStopID");
if (busStopID != null) {
busStopSearchByIDEditText.setText(busStopID);
runSearchTask(busStopID, NORMAL_SPINNER);
}
} else {
showKeyboard();
}
}
@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 R.id.action_about:
- startActivity(new Intent(MainActivity.this, AboutActivity.class));
+ startActivity(new Intent(ActivityMain.this, ActivityAbout.class));
return true;
case R.id.action_favorites:
- startActivity(new Intent(MainActivity.this, FavoritesActivity.class));
+ startActivity(new Intent(ActivityMain.this, ActivityFavorites.class));
return true;
case R.id.action_help:
showHints();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Catch the Async action!
*
* @author boz
*/
public class MyAsyncWget extends AsyncWget {
protected void onPostExecute(String htmlResponse) {
- // Network errors?
if (htmlResponse == null || exceptions != null) {
- NetworkTools.showNetworkError(MainActivity.this);
+ // Network error
+ NetworkTools.showNetworkError(ActivityMain.this);
hideSpinner();
Log.e("MainActivity", "Network error!");
return;
}
// Try parsing arrivals
BusStop[] busStops = GTTSiteSucker.getBusStopsSuckingHTML(db,
- htmlResponse);
+ htmlResponse);
- // Parse errors?
if (busStops == null || busStops.length == 0) {
+ // Parse errors
Toast.makeText(getApplicationContext(),
R.string.no_arrival_times, Toast.LENGTH_SHORT).show();
hideSpinner();
Log.e("MainActivity", "Parse error! htmlResponse: "
+ htmlResponse);
} else if(busStops.length == 1) {
// There is only one bus stop to show
+
BusStop busStop = busStops[0];
- // Order bus lines by first arrival time :D
busStop.orderBusLinesByFirstArrival();
// Remember as last successfully searched busStopID
Integer busStopID = busStop.getBusStopID();
lastSearchedBusStopID = busStopID;
// Retrieve passages
BusLine[] busLines = busStop.getBusLines();
// No passages?
if (busLines.length == 0) {
Toast.makeText(getApplicationContext(),
R.string.no_arrival_times, Toast.LENGTH_SHORT).show();
hideSpinner();
Log.d("MainActivity", "No passages!");
return;
}
String busStopName = busStop.getBusStopName();
String busStopNameDisplay;
if (busStopName == null) {
busStopNameDisplay = String.valueOf(busStopID);
} else {
busStopNameDisplay = busStopName;
}
busStopNameTextView.setText(String.format(
getString(R.string.passages), busStopNameDisplay));
// Insert GTTBusStop info in the DB
MyDB.BusStop.addBusStop(db, busStopID, busStopName);
- // Populate the stupid ListView SimpleAdapter
- ArrayList> entries = new ArrayList>();
- for (BusLine busLine : busLines) {
- HashMap entry = new HashMap();
- String passages = busLine.getTimePassagesString();
- if (passages == null) {
- passages = getString(R.string.no_passages);
- }
- entry.put("icon", busLine.getBusLineName());
- entry.put("passages", passages);
- entries.add(entry);
- }
-
- // Hide the keyboard before showing passages
hideKeyboard();
// Shows hints
if (getOption("show_legend", true)) {
showHints();
} else {
hideHints();
}
+
busStopNameTextView.setVisibility(View.VISIBLE);
swipeRefreshLayout.setEnabled(true);
swipeRefreshLayout.setVisibility(View.VISIBLE);
resultsListView.setVisibility(View.VISIBLE);
- // Stops spinner
- hideSpinner();
-
- // Show results using the stupid SimpleAdapter
- String[] from = { "icon", "passages" };
- int[] to = { R.id.busLineIcon, R.id.busLineNames };
- SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),
- entries, R.layout.bus_line_passage_entry, from, to);
- resultsListView.setAdapter(adapter);
- resultsListView.invalidate();
- resultsListView
- .setOnItemClickListener(new AdapterView.OnItemClickListener() {
- public void onItemClick(AdapterView> av, View view,
- int i, long l) {
- String busLine = ((TextView) av.getChildAt(i)
- .findViewById(R.id.busLineIcon)).getText()
- .toString();
- Log.d("MainActivity", "Tapped busLine: " + busLine);
- }
- });
+ resultsListView.showBusLines(busLines, getApplicationContext());
+ resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ public void onItemClick(AdapterView> av, View view,
+ int i, long l) {
+ String busLine = ((TextView) av.getChildAt(i)
+ .findViewById(R.id.busLineIcon)).getText()
+ .toString();
+ Log.d("MainActivity", "Tapped busLine: " + busLine);
+ }
+ });
+
+ hideSpinner();
} else {
// Show a list of bus stops
- // Populate the stupid ListView SimpleAdapter
- ArrayList> data = new ArrayList>();
- for(int i=0; i singleEntry = new HashMap();
-
- busStops[i].orderBusLinesByName();
-
- int busStopID = busStops[i].getBusStopID();
- String busStopName = busStops[i].getBusStopName();
- String busLineNames = busStops[i].toString();
-
- singleEntry.put("bus-stop-ID", busStopID);
- singleEntry.put("bus-stop-name", busStopName);
- singleEntry.put("bus-line-names", String.format(getResources()
- .getString(R.string.lines), "\n" + busLineNames));
- data.add(singleEntry);
- }
-
- // Hide the keyboard before showing bus stops
hideKeyboard();
- /* busStopNameTextView.setText(getString(R.string.results));
- * con questo non funziona piu' il salvataggio delle fermate nei preferiti
- * (e' scomparso per un altro motivo, in activity_main.xml)
- * */
- busStopNameTextView.setVisibility(View.GONE);
+ busStopNameTextView.setText(getString(R.string.results));
+ busStopNameTextView.setVisibility(View.VISIBLE);
swipeRefreshLayout.setEnabled(false);
swipeRefreshLayout.setVisibility(View.VISIBLE);
resultsListView.setVisibility(View.VISIBLE);
- // Stops spinner
- hideSpinner();
-
// Show results
- String[] from = { "bus-stop-ID", "bus-stop-name", "bus-line-names" };
- int[] to = { R.id.busStopID, R.id.busStopName, R.id.busLineNames };
- SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),
- data, R.layout.bus_stop_entry, from, to);
- resultsListView.setAdapter(adapter);
+ resultsListView.showBusStops(busStops, getApplicationContext());
resultsListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView> av, View view,
int i, long l) {
String busStopID = ((TextView) view
.findViewById(R.id.busStopID)).getText()
.toString();
Log.d("MainActivity", "Tapped on bus stop ID: "
+ busStopID);
setSearchModeBusStopID();
busStopSearchByIDEditText.setText(busStopID);
+
runSearchTask(busStopID, NORMAL_SPINNER);
}
});
+
+ hideSpinner();
}
}
}
public void onSearchClick(View v) {
String query;
if (searchMode == SEARCH_BY_ID) {
query = busStopSearchByIDEditText.getText().toString();
} else {
query = busStopSearchByNameEditText.getText().toString();
}
runSearchTask(query, NORMAL_SPINNER);
}
public void onHideHint(View v) {
hideHints();
setOption("show_legend", false);
}
public void onToggleKeyboardLayout(View v) {
searchMode = !searchMode;
if(searchMode == SEARCH_BY_ID) {
setSearchModeBusStopID();
if (busStopSearchByIDEditText.requestFocus()) {
showKeyboard();
}
} else {
setSearchModeBusStopName();
if (busStopSearchByNameEditText.requestFocus()) {
showKeyboard();
}
}
}
public void runSearchTask(String busStopQuery, boolean spinnerType) {
if (busStopQuery.isEmpty()) {
Toast.makeText(getApplicationContext(),
R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT)
.show();
return;
} else if (!NetworkTools.isConnected(this)) {
NetworkTools.showNetworkError(this);
return;
} else {
showSpinner(spinnerType);
myAsyncWget.cancel(true);
myAsyncWget = new MyAsyncWget();
try {
myAsyncWget.execute(GTTSiteSucker
.busLinesByQuery(busStopQuery));
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),
R.string.encoding_error, Toast.LENGTH_SHORT).show();
}
}
}
public void addInFavorites(View v) {
if (lastSearchedBusStopID != null) {
ContentValues newValues = new ContentValues();
newValues.put(MyDB.BusStop.COLUMN_NAME_BUSSTOP_ISFAVORITE, 1);
db.update(MyDB.BusStop.TABLE_NAME, newValues, MyDB
.somethingEqualsInt(MyDB.BusStop.COLUMN_NAME_BUSSTOP_ID),
new String[] { String.valueOf(lastSearchedBusStopID) });
Toast.makeText(getApplicationContext(),
R.string.added_in_favorites, Toast.LENGTH_SHORT).show();
}
}
private void setOption(String optionName, boolean value) {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putBoolean(optionName, value);
editor.commit();
}
private boolean getOption(String optionName, boolean optDefault) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
return preferences.getBoolean(optionName, optDefault);
}
private void showKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(busStopSearchByNameEditText,
InputMethodManager.SHOW_IMPLICIT);
}
private void hideKeyboard() {
View view = getCurrentFocus();
if (view != null) {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
private void setSearchModeBusStopID() {
busStopSearchByNameEditText.setVisibility(View.GONE);
busStopSearchByIDEditText.setVisibility(View.VISIBLE);
floatingActionButton.setImageResource(R.drawable.ic_keyboard_white_24dp);
}
private void setSearchModeBusStopName() {
busStopSearchByIDEditText.setVisibility(View.GONE);
busStopSearchByNameEditText.setVisibility(View.VISIBLE);
floatingActionButton.setImageResource(R.drawable.ic_looks_one_white_24dp);
}
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);
}
private void showSpinner(boolean swipeSpinner) {
if (swipeSpinner == DOUBLE_SPINNER) {
swipeRefreshLayout.setRefreshing(true);
}
progressBar.setVisibility(View.VISIBLE);
}
private void hideSpinner() {
swipeRefreshLayout.setRefreshing(false);
progressBar.setVisibility(View.INVISIBLE);
}
}
\ No newline at end of file
diff --git a/src/it/reyboz/bustorino/AsyncWget.java b/src/it/reyboz/bustorino/lab/AsyncWget.java
similarity index 98%
rename from src/it/reyboz/bustorino/AsyncWget.java
rename to src/it/reyboz/bustorino/lab/AsyncWget.java
index 274839e..15d2cf5 100644
--- a/src/it/reyboz/bustorino/AsyncWget.java
+++ b/src/it/reyboz/bustorino/lab/AsyncWget.java
@@ -1,79 +1,79 @@
/*
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 .
*/
-package it.reyboz.bustorino;
+package it.reyboz.bustorino.lab;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
import android.util.Log;
public class AsyncWget extends AsyncTask {
protected Exception exceptions;
protected String doInBackground(String... uri) {
exceptions = null;
Log.d("AsyncWget", "Catching URL in background: " + uri[0]);
HttpURLConnection urlConnection = null;
StringBuilder result = null;
try {
URL url = new URL(uri[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("AsyncWget", e.getMessage());
exceptions = e;
} finally {
urlConnection.disconnect();
}
if (result == null) {
return null;
}
return result.toString();
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
protected void onCancelled() {
this.cancel(true);
}
protected void onError() {
}
}
diff --git a/src/it/reyboz/bustorino/GTTSiteSucker.java b/src/it/reyboz/bustorino/lab/GTTSiteSucker.java
similarity index 87%
rename from src/it/reyboz/bustorino/GTTSiteSucker.java
rename to src/it/reyboz/bustorino/lab/GTTSiteSucker.java
index 4b659d5..591cc57 100644
--- a/src/it/reyboz/bustorino/GTTSiteSucker.java
+++ b/src/it/reyboz/bustorino/lab/GTTSiteSucker.java
@@ -1,508 +1,563 @@
/*
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 .
*/
-package it.reyboz.bustorino;
+package it.reyboz.bustorino.lab;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* «BusTO, because sucking happens»
*
* @author boz
*/
public class GTTSiteSucker {
/**
*
* @deprecated
*/
public static String arrivalTimesByLineQuery(String busStop) {
return "http://www.5t.torino.it/5t/trasporto/arrival-times-byline.jsp?action=getTransitsByLine&shortName="
+ busStop;
}
public static String busLinesByQuery(String busLineName)
throws UnsupportedEncodingException {
return "http://m.gtt.to.it/m/it/arrivi.jsp?n="
+ URLEncoder.encode(busLineName, "UTF-8");
}
/**
* Execute regexes.
*
* @param needle Regex
* @param haystack Entire string
* @return Matched string
*/
public static String grep(String needle, String haystack) {
String matched = null;
Matcher matcher = Pattern.compile(
needle).matcher(haystack);
if (matcher.find()) {
matched = matcher.group(1);
}
return matched;
}
/**
* Javammerda! Lasciami null senza suicidarti!
*/
public static Integer string2Integer(String str) {
try {
return Integer.parseInt(str);
} catch(NumberFormatException e) {
return null;
}
}
/**
* Helps comparing times
*
* @author boz
*/
public static class Time {
private int mm;
private int hh;
public Time(int hh, int mm) {
this.hh = hh;
this.mm = mm;
}
public boolean isMajorThan(Time time) {
if (hh == time.getHH()) {
return mm >= time.getMM();
} else if (hh > time.getHH() || hh == 0 && time.getHH() == 23) {
return true;
}
return false;
}
public int getHH() {
return hh;
}
public int getMM() {
return mm;
}
}
/**
* A time passage is a time with the answer of: Is this in real time?
*
* @author boz
*/
public static class TimePassage {
private String time;
private boolean isInRealTime;
public TimePassage(String time, boolean isInRealTime) {
this.time = time;
this.isInRealTime = isInRealTime;
}
public String getTime() {
return time;
}
public boolean isInRealTime() {
return isInRealTime;
}
/**
* @return null if can't be converted into a time
*/
public Time getComparableTime() {
int hh, mm;
String[] parts = time.split(":");
if (parts.length != 2) {
return null;
}
try {
hh = Integer.valueOf(parts[0]);
mm = Integer.valueOf(parts[1]);
} catch (NumberFormatException e) {
return null;
}
return new Time(hh, mm);
}
}
/**
* Passages (at a bus line) (like line numbers)
*
* @author boz
*/
public static class BusLine {
private Integer busLineID;
private String busLineName;
private ArrayList timesPassages;
public BusLine() {
this(null, null);
}
public BusLine(Integer busLineID) {
this(busLineID, null);
}
public BusLine(String busLineName) {
this(null, busLineName);
}
public BusLine(Integer busLineID, String busLineName) {
this.busLineID = busLineID;
this.busLineName = busLineName;
timesPassages = new ArrayList();
}
public void addTimePassage(String time, boolean isInRealTime) {
timesPassages.add(new TimePassage(time, isInRealTime));
}
public ArrayList getTimePassages() {
return timesPassages;
}
public String getTimePassagesString() {
if (timesPassages == null || timesPassages.size() == 0) {
return null;
}
String out = "";
for (TimePassage timePassage : timesPassages) {
out += timePassage.getTime()
+ (timePassage.isInRealTime() ? "*" : " ") + " ";
}
return out;
}
public String getBusLineName() {
return busLineName;
}
public void setBusLineName(String busLineName) {
this.busLineName = busLineName;
}
public Integer getBusLineID() {
return busLineID;
}
public void setBusLineID(Integer busLineID) {
this.busLineID = busLineID;
}
public String toString() {
return getTimePassagesString();
}
public Time getFirstPassageComparableTime() {
if(timesPassages == null || timesPassages.size() == 0) {
return null;
}
return timesPassages.get(0).getComparableTime();
}
/**
* Help sorting
*
* @param busLineName
* @return boolean -1/0/1 if this is minor/equal/major than busLineName arg (First 0-9, than A-Z)
*/
public boolean isMajorThan(String busLineName) {
final String regex = "^([0-9]+)";
Integer nThis = string2Integer(grep(regex, this.busLineName));
Integer nOther = string2Integer(grep(regex, busLineName));
//Log.d("GTTSiteSucker", "\"" + this.busLineName + "\" (" + nThis + ") | \"" + busLineName + "\" (" + nOther + ")");
if(nThis != null) {
if(nOther != null) {
int res = nThis.compareTo(nOther);
if(res != 0) {
return res > 0; // 0-9 <=> 0-9
}
}
return false; // 0-9 < A-Z
}
if(nOther != null) {
return true; // A-Z > 0-9
}
return this.busLineName.compareTo(busLineName) > 0; // A-Z <=> A-Z || 0-9 == 0-9
}
}
/**
* A BusStop has information on the bus stop (bus stop name) and of all the
* buses that pass through it
*
* @author boz
*/
public static class BusStop {
private Integer busStopID; // Es: 1254 (always Integer)
private String busStopName; // Es: MARCONI
+ private String latitude;
+ private String longitude;
private BusLine[] busLines;
BusStop(Integer busStopID, String busStopName, BusLine[] busLines) {
- this.busStopID = busStopID;
- this.busStopName = busStopName;
- this.busLines = busLines;
+ this(busStopID, busStopName, busLines, null, null);
}
+ BusStop(Integer busStopID, String busStopName, BusLine[] busLines, String latitude, String longitude) {
+ this.busStopID = busStopID;
+ this.busStopName = busStopName;
+ this.busLines = busLines;
+ this.latitude = latitude;
+ this.longitude = longitude;
+ }
+
public void setGTTBusStopName(String busStopName) {
this.busStopName = busStopName;
}
public String getBusStopName() {
return busStopName;
}
public Integer getBusStopID() {
return busStopID;
}
public void setBusStopName(String busStopName) {
this.busStopName = busStopName;
}
public BusLine[] getBusLines() {
return busLines;
}
public void orderBusLinesByFirstArrival() {
for (int i = 0; i < busLines.length - 1; i++) {
for (int j = i + 1; j < busLines.length; j++) {
BusLine a = busLines[i];
BusLine b = busLines[j];
Time aTime = a.getFirstPassageComparableTime();
Time bTime = b.getFirstPassageComparableTime();
if (aTime != null && bTime != null
&& aTime.isMajorThan(bTime)) {
BusLine tmp = a;
busLines[i] = b;
busLines[j] = tmp;
}
}
}
}
public void orderBusLinesByName() {
for (int i = 0; i < busLines.length - 1; i++) {
for (int j = i + 1; j < busLines.length; j++) {
BusLine a = busLines[i];
BusLine b = busLines[j];
// Log.d("GTTSiteSucker", "Comparing " + a.getBusLineName() + (a.isMajorThan(b.getBusLineName()) ? " major than " : " minor or equal than ") + b.getBusLineName());
if (a.isMajorThan(b.getBusLineName())) {
BusLine tmp = a;
busLines[i] = b;
busLines[j] = tmp;
}
}
}
}
+ public void setCoordinate(String latitude, String longitude) {
+ this.latitude = latitude;
+ this.longitude = longitude;
+ }
+
+ public String getLatitude() {
+ return latitude;
+ }
+
+ public String getLongitude() {
+ return longitude;
+ }
+
/**
* @return Bus line list
*/
public String toString() {
String busLineNames = "";
for(int i=0; i busStops = new ArrayList();
Document doc = Jsoup.parse(html);
String title = doc.title().trim();
if (title.substring(1).equals("Elenco fermate")) {
// Find bus stops
Elements lis = doc.getElementsByTag("li");
for (Element li : lis) {
String liContent = li.html();
if (liContent.isEmpty()) {
continue;
}
// Sucking bus stop ID (e.g.: 1254)
String href;
try {
href = li.getElementsByTag("a").first().attr("href");
} catch (NullPointerException e) {
Log.e("GTTSiteSucker",
"Parse error: busStopID can't be found!");
continue;
}
Integer busStopID = string2Integer(grep("([0-9]+)", href));
if (busStopID == null) {
Log.e("GTTSiteSucker", "Parse error: busStopID is null!");
continue;
}
// Sucking bus stop name (e.g.: POZZO STRADA)
String busStopName = grep("- (.+) busLines = new ArrayList();
Element span = null;
try {
span = li.getElementsByTag("span").last();
} catch (NullPointerException e) {
Log.d("GTTSiteSucker", "Can't retrieve span element");
}
if(span == null) {
Log.d("GTTSiteSucker", "Span element is null!" + li.html());
continue;
}
String spanContent = grep("Linee: (.+)", span.html());
if (spanContent != null) {
String[] busLineNames = spanContent.split(", ");
for (int i = 0; i < busLineNames.length; i++) {
busLines.add(new BusLine(busLineNames[i]));
}
}
Log.d("GTTSiteSucker", "busStopID: " + busStopID);
Log.d("GTTSiteSucker", "busStopName:" + busStopName);
Log.d("GTTSiteSucker", "busLines: " + busLines.size());
busStops.add(new BusStop(busStopID, busStopName, busLines
.toArray((new BusLine[] {}))));
}
} else if (title.equals("Arrivi in fermata")) {
// Find bus lines
String p = null;
try {
p = doc.getElementsByTag("p").first().html();
} catch (NullPointerException e) {
Log.e("GTTSiteSucker",
"Parse error: busStopID and busStopName can't be found!");
}
if(p == null) {
return null;
}
// Sucking bus stop ID (e.g. 1254)
Integer busStopID = string2Integer(grep("([0-9]+) -", p)); // arrivi.jsp?n=(1254)
if (busStopID == null) {
Log.e("GTTSiteSucker", "Parse error: busStopID is null: " + p);
return null;
}
// Sucking bus stop name (e.g.: POZZO STRADA)
String busStopName = grep("- (.+) busLines = new ArrayList();
Elements lis = doc.getElementsByTag("li");
for (Element li : lis) {
String liContent = li.html();
if (liContent.isEmpty()) {
continue;
}
// Sucking bus line name (e.g.: 17 /)
String h3 = null;
try {
h3 = li.getElementsByTag("h3").first().html();
} catch (NullPointerException e) {
Log.e("GTTSiteSucker",
"Parse error: busLineName can't be found!");
}
if(h3 == null) {
continue;
}
String busLineName = grep("Linea (.+)", h3);
if(busLineName == null) {
Log.e("GTTSiteSucker", "Parse error: busLineName is null: " + h3);
continue;
}
BusLine busLine = new BusLine(busLineName);
// Sucking bus passages
Elements spans = li.parent().select("li > span");
for (Element span : spans) {
String spanContent = span.html();
if (spanContent.isEmpty()) {
continue;
}
String busLinePassage = grep("([0-9]+:[0-9]+)", spanContent);
if(busLinePassage == null) {
Log.e("GTTSiteSucker", "Parse error: busLinePassage is null: " + spanContent);
continue;
}
String busLinePassageInRealTime = grep("(span)", spanContent);
busLine.addTimePassage(busLinePassage, busLinePassageInRealTime == null ? false : true);
}
busLines.add(busLine);
}
return new BusStop[] {new BusStop(busStopID, busStopName, busLines
.toArray((new BusLine[] {})))};
} else {
Log.e("GTTSiteSucker", "Title does not recognized: «" + title + "»");
return null;
}
return busStops.toArray((new BusStop[] {}));
}
+
+ /**
+ * Return geographical infos about a bus stop
+ * @return BusStop
+ */
+ public BusStop getBusStopInfos(SQLiteDatabase db,
+ String json) {
+ // Yes, it's JSON, but I don't want to import org.json
+
+ String line = null;
+ while((line=bufReader.readLine()) != null) {
+ Integer busStopID = String2Integer(grep("shortName[\s]*:[\s]*\"([0-9]+)\"", line));
+
+ if(line=bufReader.readLine()) == null) {
+ return false;
+ }
+
+ String busStopName = grep("name[\s]*:[\s]*\"(.+)\"", line);
+
+ if(line=bufReader.readLine()) == null) {
+ return false;
+ }
+
+ String latitude = grep("lat[\s]*:[\s]*(.+),", line);
+
+ if(line=bufReader.readLine()) == null) {
+ return false;
+ }
+
+ String longitude = grep("lon[\s]*:[\s]*(.+),", line);
+
+ return new BusStop(busStopID, busStopName, null, latitude, longitude);
+ }
+ }
}
diff --git a/src/it/reyboz/bustorino/MyDB.java b/src/it/reyboz/bustorino/lab/MyDB.java
similarity index 99%
rename from src/it/reyboz/bustorino/MyDB.java
rename to src/it/reyboz/bustorino/lab/MyDB.java
index 381a9af..498b3a0 100644
--- a/src/it/reyboz/bustorino/MyDB.java
+++ b/src/it/reyboz/bustorino/lab/MyDB.java
@@ -1,238 +1,238 @@
/*
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 .
*/
-package it.reyboz.bustorino;
+package it.reyboz.bustorino.lab;
import android.provider.BaseColumns;
import android.util.Log;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.ContentValues;
import android.content.Context;
/**
* Manage SQLite
*
* @author boz
*/
public class MyDB extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database
// version.
public static final int DATABASE_VERSION = 7;
public static final String DATABASE_NAME = "bustorino.db";
public static String COMMA = ", ";
public static String DOT = ".";
public static final String EQUALS = " = ";
public static final String CREATE_TABLE_IF_NOT_EXISTS = "CREATE TABLE IF NOT EXISTS ";
public static final String DROP_TABLE = "DROP TABLE IF EXISTS ";
public static final String TEXT_TYPE = " TEXT";
public static final String INTEGER_TYPE = " INTEGER";
public static final String PRIMARY_KEY = " PRIMARY KEY";
public static final String NOT_NULL = " NOT NULL";
public static final String UPDATE = "UPDATE ";
public static final String WHERE = " WHERE ";
public static final String AND = " AND ";
public static final String SELECT = "SELECT ";
public static final String FROM = " FROM ";
public static final String SELECT_ALL_FROM = "SELECT * FROM ";
public static final String ORDER_BY = " ORDER BY ";
public static final String ASC = " ASC";
public static final String DESC = " DESC";
public static String getDefault(int i) {
return " DEFAULT " + String.valueOf(i);
}
public static String somethingEqualsString(String tableName) {
return " " + tableName + "=\"?\"";
}
public static String somethingEqualsInt(String tableName) {
return " " + tableName + "=?";
}
public MyDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(BusStop.SQL_CREATE_ENTRIES);
db.execSQL(BusLine.SQL_CREATE_ENTRIES);
db.execSQL(BusStopServeLine.SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 6 && newVersion == 7) {
// Added two tables, its all OK
oldVersion = 7;
} else {
// This probably is never done, but it discard the data and start
// over strange DB versions
db.execSQL(BusStop.SQL_DELETE_ENTRIES);
db.execSQL(BusLine.SQL_DELETE_ENTRIES);
db.execSQL(BusStopServeLine.SQL_DELETE_ENTRIES);
}
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
/**
* Store bus stops.
*
* @author boz
*/
public static abstract class BusStop implements BaseColumns {
public static final String TABLE_NAME = "busstop";
public static final String COLUMN_NAME_BUSSTOP_ID = "busstop_ID";
public static final String COLUMN_NAME_BUSSTOP_NAME = "busstop_name";
public static final String COLUMN_NAME_BUSSTOP_ISFAVORITE = "busstop_isfavorite";
public static final String IS_FAVORITE = "1";
public static final String IS_NOT_FAVORITE = "0";
private static final String SQL_CREATE_ENTRIES = CREATE_TABLE_IF_NOT_EXISTS
+ TABLE_NAME
+ " ("
+ COLUMN_NAME_BUSSTOP_ID
+ INTEGER_TYPE
+ PRIMARY_KEY
+ NOT_NULL
+ COMMA
+ COLUMN_NAME_BUSSTOP_NAME
+ TEXT_TYPE
+ NOT_NULL
+ COMMA
+ COLUMN_NAME_BUSSTOP_ISFAVORITE
+ INTEGER_TYPE + NOT_NULL + getDefault(0) + ")";
private static final String SQL_DELETE_ENTRIES = DROP_TABLE
+ TABLE_NAME;
public static long addBusStop(SQLiteDatabase db, Integer ID, String name) {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_BUSSTOP_ID, ID);
values.put(COLUMN_NAME_BUSSTOP_NAME, name);
long lastInserted = db.insertWithOnConflict(TABLE_NAME, null,
values, SQLiteDatabase.CONFLICT_IGNORE);
Log.d("DBBusTo", "last busStopID inserted: " + lastInserted);
return lastInserted;
}
public static String getColumn(String columnName) {
return TABLE_NAME + DOT + columnName;
}
}
/**
* Store bus lines.
*
* @author boz
*/
public static abstract class BusLine implements BaseColumns {
public static final String TABLE_NAME = "busline";
public static final String COLUMN_NAME_BUSLINE_ID = "busline_ID";
public static final String COLUMN_NAME_BUSLINE_NAME = "busline_name"; // Is
// there
// one?
public static final String COLUMN_NAME_BUSLINE_ISFAVORITE = "busline_isfavorite";
private static final String SQL_CREATE_ENTRIES = CREATE_TABLE_IF_NOT_EXISTS
+ TABLE_NAME
+ " ("
+ COLUMN_NAME_BUSLINE_ID
+ INTEGER_TYPE
+ PRIMARY_KEY
+ NOT_NULL
+ COMMA
+ COLUMN_NAME_BUSLINE_NAME
+ TEXT_TYPE
+ NOT_NULL
+ COMMA
+ COLUMN_NAME_BUSLINE_ISFAVORITE
+ INTEGER_TYPE + NOT_NULL + getDefault(0) + ")";
private static final String SQL_DELETE_ENTRIES = DROP_TABLE
+ TABLE_NAME;
public static String getColumn(String columnName) {
return TABLE_NAME + DOT + columnName;
}
public static long addBusLine(SQLiteDatabase db, Integer busLineID,
String busLineName) {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_BUSLINE_ID, busLineID);
values.put(COLUMN_NAME_BUSLINE_NAME, busLineName);
return db.insertWithOnConflict(TABLE_NAME, null, values,
SQLiteDatabase.CONFLICT_IGNORE);
}
}
/**
* Associate every bus stop on every bus line served
*
* @author boz
*
*/
public static abstract class BusStopServeLine {
public static final String TABLE_NAME = "busstopserveline";
public static final String COLUMN_NAME_BUSSTOP_ID = "busstop_ID";
public static final String COLUMN_NAME_BUSLINE_ID = "busline_ID";
private static final String SQL_CREATE_ENTRIES = CREATE_TABLE_IF_NOT_EXISTS
+ TABLE_NAME
+ " ("
+ COLUMN_NAME_BUSSTOP_ID
+ INTEGER_TYPE
+ NOT_NULL
+ COMMA
+ COLUMN_NAME_BUSLINE_ID
+ INTEGER_TYPE
+ NOT_NULL
+ COMMA
+ PRIMARY_KEY
+ " ("
+ COLUMN_NAME_BUSSTOP_ID
+ COMMA
+ COLUMN_NAME_BUSLINE_ID
+ "))"; // Add primary key on two columns
private static final String SQL_DELETE_ENTRIES = DROP_TABLE
+ TABLE_NAME;
public static void addBusStopServeLine(SQLiteDatabase db,
Integer busStopID, Integer busLineID) {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_BUSSTOP_ID, busStopID);
values.put(COLUMN_NAME_BUSLINE_ID, busLineID);
long inserted = db.insertWithOnConflict(TABLE_NAME, null, values,
SQLiteDatabase.CONFLICT_IGNORE);
Log.d("MySB", "Last inserted busStopServeLine: " + inserted);
}
public static String getColumn(String columnName) {
return TABLE_NAME + DOT + columnName;
}
}
}
diff --git a/src/it/reyboz/bustorino/NetworkTools.java b/src/it/reyboz/bustorino/lab/NetworkTools.java
similarity index 95%
rename from src/it/reyboz/bustorino/NetworkTools.java
rename to src/it/reyboz/bustorino/lab/NetworkTools.java
index 52812e3..bf1e774 100644
--- a/src/it/reyboz/bustorino/NetworkTools.java
+++ b/src/it/reyboz/bustorino/lab/NetworkTools.java
@@ -1,39 +1,41 @@
/*
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 .
*/
-package it.reyboz.bustorino;
+package it.reyboz.bustorino.lab;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;
+import it.reyboz.bustorino.R;
+
public class NetworkTools {
// Check network connection
public static boolean isConnected(Context c) {
ConnectivityManager connMgr = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
// «Turn on WiFi!»
public static void showNetworkError(Context c) {
Toast.makeText(c, R.string.network_error, Toast.LENGTH_SHORT).show();
}
}
\ No newline at end of file
diff --git a/src/it/reyboz/bustorino/layouts/BusListView.java b/src/it/reyboz/bustorino/layouts/BusListView.java
new file mode 100644
index 0000000..98955cc
--- /dev/null
+++ b/src/it/reyboz/bustorino/layouts/BusListView.java
@@ -0,0 +1,94 @@
+/*
+ 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 .
+ */
+package it.reyboz.bustorino.layouts;
+import android.content.Context;
+import android.util.AttributeSet;
+import android.widget.ListView;
+import android.widget.SimpleAdapter;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import it.reyboz.bustorino.lab.GTTSiteSucker.BusLine;
+import it.reyboz.bustorino.lab.GTTSiteSucker.BusStop;
+import it.reyboz.bustorino.R;
+
+public class BusListView extends ListView {
+
+ public BusListView(Context context) {
+ super(context);
+ }
+
+ public BusListView(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ }
+
+ public BusListView(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public void showBusLines(BusLine[] busLines, Context c) {
+ // Populate the stupid ListView SimpleAdapter
+ ArrayList> entries = new ArrayList>();
+ for (BusLine busLine : busLines) {
+ HashMap entry = new HashMap();
+ String passages = busLine.getTimePassagesString();
+ if (passages == null) {
+ passages = c.getString(R.string.no_passages);
+ }
+ entry.put("icon", busLine.getBusLineName());
+ entry.put("passages", passages);
+ entries.add(entry);
+ }
+
+ // Show results using the stupid SimpleAdapter
+ String[] from = { "icon", "passages" };
+ int[] to = { R.id.busLineIcon, R.id.busLineNames };
+ SimpleAdapter adapter = new SimpleAdapter(c,
+ entries, R.layout.entry_bus_line_passage, from, to);
+ setAdapter(adapter);
+
+ invalidate();
+ }
+
+ public void showBusStops(BusStop[] busStops, Context c) {
+ // Populate the stupid ListView SimpleAdapter
+ ArrayList> data = new ArrayList>();
+ for(int i=0; i singleEntry = new HashMap();
+
+ busStops[i].orderBusLinesByName();
+
+ int busStopID = busStops[i].getBusStopID();
+ String busStopName = busStops[i].getBusStopName();
+ String busLineNames = busStops[i].toString();
+
+ singleEntry.put("bus-stop-ID", busStopID);
+ singleEntry.put("bus-stop-name", busStopName);
+ singleEntry.put("bus-line-names", String.format(c.getResources()
+ .getString(R.string.lines), "\n" + busLineNames));
+ data.add(singleEntry);
+ }
+ String[] from = { "bus-stop-ID", "bus-stop-name", "bus-line-names" };
+ int[] to = { R.id.busStopID, R.id.busStopName, R.id.busLineNames };
+ SimpleAdapter adapter = new SimpleAdapter(c,
+ data, R.layout.entry_bus_stop, from, to);
+ setAdapter(adapter);
+ }
+
+}