diff --git a/.bzrignore b/.bzrignore
index 6994efb..15d7031 100644
--- a/.bzrignore
+++ b/.bzrignore
@@ -1,12 +1,34 @@
-gen
-bin
-assets
-libs
-.settings
+# Built application files
+*.apk
+*.ap_
+
+# Files for the dex VM
+*.dex
+
+# Java class files
+*.class
+
+# Generated files
+bin/
+gen/
+
+# Local configuration file (SDK path, etc)
local.properties
+
+# Eclipse project files
+.classpath
+.project
+
+# Android Studio
+*.iml
+.idea
+#.idea/workspace.xml - remove # and delete .idea if it better suit your needs.
.gradle
-.idea/workspace.xml
-.idea/libraries
-build
-.idea/codeStyleSettings.xml
-.idea/runConfigurations.xml
+build/
+
+#NDK
+obj/
+
+# I don't want to see this shit.
+Thumbs.db
+.DS_Store
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
index 9a8b7e5..96cc43e 100644
--- a/.idea/compiler.xml
+++ b/.idea/compiler.xml
@@ -1,22 +1,22 @@
-
+
\ No newline at end of file
diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml
index c7d1c5a..e7bedf3 100644
--- a/.idea/copyright/profiles_settings.xml
+++ b/.idea/copyright/profiles_settings.xml
@@ -1,3 +1,3 @@
-
-
+
+
\ No newline at end of file
diff --git a/.idea/encodings.xml b/.idea/encodings.xml
deleted file mode 100644
index 97626ba..0000000
--- a/.idea/encodings.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
index 747f24e..288ea0b 100644
--- a/.idea/gradle.xml
+++ b/.idea/gradle.xml
@@ -1,17 +1,18 @@
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
index 6a1e020..1a3eaff 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -1,46 +1,46 @@
-
+
\ No newline at end of file
diff --git a/ic_launcher-web.png b/ic_launcher-web.png
deleted file mode 100644
index f760c08..0000000
Binary files a/ic_launcher-web.png and /dev/null differ
diff --git a/ic_launcher-web.png b/ic_launcher-web.png
new file mode 120000
index 0000000..69597d4
--- /dev/null
+++ b/ic_launcher-web.png
@@ -0,0 +1 @@
+res/drawable-xxxhdpi/ic_launcher.png
\ No newline at end of file
diff --git a/res/layout/activity_main.xml b/res/layout/activity_main.xml
index a613004..d467b02 100644
--- a/res/layout/activity_main.xml
+++ b/res/layout/activity_main.xml
@@ -1,193 +1,193 @@
\ No newline at end of file
diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml
index 7dc98fb..7fb2957 100644
--- a/res/values-it/strings.xml
+++ b/res/values-it/strings.xml
@@ -1,78 +1,79 @@
Stai utilizzando l\'ultimo ritrovato in materia di rispetto della tua privacy.CercaQR CodeNumero fermataNome fermataInserisci il numero della fermataInserisci il nome della fermataAlcuni caratteri non sono stati riconosciutiVerifica l\'accesso ad Internet!Nessun arrivo previsto per questa fermataSembra che nessuna fermata abbia questo nomeErrore di lettura del sito 5T/GTT (dannato sito!)Fermata: %1$sLinee: %1$sScegli la fermata…Nessun passaggio
+ Nessun QR codePreferitiAiutoInformazioniPiù informazioniNewsInvia bugCodice sorgenteLicenzaIncontra l\'autoreFermata aggiunta ai preferitiPreferitiTocca il nome di una fermata per aggiungerla in questa listaRimuoviRinominaRinomina fermataResetInformazioniTocca il nome della fermata per aggiungerla ai preferiti\n\nCome leggere gli orari:\n 12:56* Orario in tempo reale\n 12:56 Orario programmato\n\nTrascina giù per aggiornare l\'orario.OK !
Benvenuto!
Grazie per aver scelto BusTO, un\'app \"politicamente\" indipendente da GTT/5T, per 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 sviluppatore principale.
- Marco Gagino intenso collaboratore, creatore dell\'icona, responsabile della grafica.
- Paolo Alloatti per l\'idea dell\'icona.
- JSoup libreria per "web scaping".
- makovkastar bottone fluttuante.
- Google icone Material Design.
- Tutti i contributori!
Licenze
L\'app e il relativo codice sorgente sono distribuiti sotto la licenza GNU General Public License v3+.
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 dare credito a Valerio Bozzolan.
Note
Quest\'applicazione è rilasciata nella speranza che sia utile a tutti ma senza NESSUNA garanzia.
Buon utilizzo! :)
]]>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 8d0d117..9c4312c 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1,77 +1,78 @@
BusTOStai utilizzando l\'ultimo ritrovato in materia di rispetto della tua privacy.SearchScan QR CodeBus stop numberBus stop nameInsert bus stop numberInsert bus stop nameSorry but you are using not allowed charactersVerify the state of your Internet connection!No bus is supposed to arrive at this stopSeems that no bus stop have this nameError parsing the 5T/GTT website (damn site!)Arrivals at: %1$sChoose the bus stop…Lines: %1$sNo passages
+ No QR codeFavoritesHelpAboutMore aboutNews releasesBug submissionSource codeLicenceMeet the authorBus stop is now in your favoritesFavoritesPress on a bus stop name to populate this listDeleteRenameRename the bus stopResetAboutTap the bus stop name to add it to the favourites\n\nHow to read timelines:\n 12:56* Real time arrival\n 12:56 Scheduled time of arrival\n\nPull down to refresh the timetableGOT IT!
Welcome!
Thanks for using BusTO, a "politically" indipendent app useful to move around Torino using a Free/Libre 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 www.5t.torino.it.
Who worked on BusTO:
- Valerio Bozzolan main developer.
- Marco Gagino main contributor and icon creator.
- Paolo Alloatti original concept of the icon.
- JSoup web scraper library.
- makovkastar floating buttons.
- Google Material Design icons.
- All the contributors!
Licenses
The app and the related source code are released by Valerio Bozzolan under the terms of the GNU General Public License v3+).
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 maintaining this rights and of attributing the original work to Valerio Bozzolan.
Notes
This app has been developed hoping to be useful to everyone but without ANY warranty.
This translation is kindly provided by Riccardo Caniato and Marco Gagino.
Get involved! :)
]]>
diff --git a/src/com/google/zxing/integration/android/IntentIntegrator.java b/src/com/google/zxing/integration/android/IntentIntegrator.java
new file mode 100644
index 0000000..6660cd8
--- /dev/null
+++ b/src/com/google/zxing/integration/android/IntentIntegrator.java
@@ -0,0 +1,506 @@
+/*
+ * Copyright 2009 ZXing authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.zxing.integration.android;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Fragment;
+import android.content.ActivityNotFoundException;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+
+/**
+ *
A utility class which helps ease integration with Barcode Scanner via {@link Intent}s. This is a simple
+ * way to invoke barcode scanning and receive the result, without any need to integrate, modify, or learn the
+ * project's source code.
+ *
+ *
Initiating a barcode scan
+ *
+ *
To integrate, create an instance of {@code IntentIntegrator} and call {@link #initiateScan()} and wait
+ * for the result in your app.
+ *
+ *
It does require that the Barcode Scanner (or work-alike) application is installed. The
+ * {@link #initiateScan()} method will prompt the user to download the application, if needed.
+ *
+ *
There are a few steps to using this integration. First, your {@link Activity} must implement
+ * the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like this:
+ *
+ *
{@code
+ * public void onActivityResult(int requestCode, int resultCode, Intent intent) {
+ * IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
+ * if (scanResult != null) {
+ * // handle scan result
+ * }
+ * // else continue with any other code you need in the method
+ * ...
+ * }
+ * }
+ *
+ *
This is where you will handle a scan result.
+ *
+ *
Second, just call this in response to a user action somewhere to begin the scan process:
Note that {@link #initiateScan()} returns an {@link AlertDialog} which is non-null if the
+ * user was prompted to download the application. This lets the calling app potentially manage the dialog.
+ * In particular, ideally, the app dismisses the dialog if it's still active in its {@link Activity#onPause()}
+ * method.
+ *
+ *
You can use {@link #setTitle(String)} to customize the title of this download prompt dialog (or, use
+ * {@link #setTitleByID(int)} to set the title by string resource ID.) Likewise, the prompt message, and
+ * yes/no button labels can be changed.
+ *
+ *
Finally, you can use {@link #addExtra(String, Object)} to add more parameters to the Intent used
+ * to invoke the scanner. This can be used to set additional options not directly exposed by this
+ * simplified API.
+ *
+ *
By default, this will only allow applications that are known to respond to this intent correctly
+ * do so. The apps that are allowed to response can be set with {@link #setTargetApplications(List)}.
+ * For example, set to {@link #TARGET_BARCODE_SCANNER_ONLY} to only target the Barcode Scanner app itself.
+ *
+ *
Sharing text via barcode
+ *
+ *
To share text, encoded as a QR Code on-screen, similarly, see {@link #shareText(CharSequence)}.
+ *
+ *
Some code, particularly download integration, was contributed from the Anobiit application.
+ *
+ *
Enabling experimental barcode formats
+ *
+ *
Some formats are not enabled by default even when scanning with {@link #ALL_CODE_TYPES}, such as
+ * PDF417. Use {@link #initiateScan(java.util.Collection)} with
+ * a collection containing the names of formats to scan for explicitly, like "PDF_417", to use such
+ * formats.
+ *
+ * @author Sean Owen
+ * @author Fred Lin
+ * @author Isaac Potoczny-Jones
+ * @author Brad Drehmer
+ * @author gcstang
+ */
+public class IntentIntegrator {
+
+ public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
+ private static final String TAG = IntentIntegrator.class.getSimpleName();
+
+ public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
+ public static final String DEFAULT_MESSAGE =
+ "This application requires Barcode Scanner. Would you like to install it?";
+ public static final String DEFAULT_YES = "Yes";
+ public static final String DEFAULT_NO = "No";
+
+ private static final String BS_PACKAGE = "com.google.zxing.client.android";
+ private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
+
+ // supported barcode formats
+ public static final Collection PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
+ public static final Collection ONE_D_CODE_TYPES =
+ list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
+ "ITF", "RSS_14", "RSS_EXPANDED");
+ public static final Collection QR_CODE_TYPES = Collections.singleton("QR_CODE");
+ public static final Collection DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
+
+ public static final Collection ALL_CODE_TYPES = null;
+
+ public static final List TARGET_BARCODE_SCANNER_ONLY = Collections.singletonList(BS_PACKAGE);
+ public static final List TARGET_ALL_KNOWN = list(
+ BSPLUS_PACKAGE, // Barcode Scanner+
+ BSPLUS_PACKAGE + ".simple", // Barcode Scanner+ Simple
+ BS_PACKAGE // Barcode Scanner
+ // What else supports this intent?
+ );
+
+ private final Activity activity;
+ private final Fragment fragment;
+
+ private String title;
+ private String message;
+ private String buttonYes;
+ private String buttonNo;
+ private List targetApplications;
+ private final Map moreExtras = new HashMap(3);
+
+ /**
+ * @param activity {@link Activity} invoking the integration
+ */
+ public IntentIntegrator(Activity activity) {
+ this.activity = activity;
+ this.fragment = null;
+ initializeConfiguration();
+ }
+
+ /**
+ * @param fragment {@link Fragment} invoking the integration.
+ * {@link #startActivityForResult(Intent, int)} will be called on the {@link Fragment} instead
+ * of an {@link Activity}
+ */
+ public IntentIntegrator(Fragment fragment) {
+ this.activity = fragment.getActivity();
+ this.fragment = fragment;
+ initializeConfiguration();
+ }
+
+ private void initializeConfiguration() {
+ title = DEFAULT_TITLE;
+ message = DEFAULT_MESSAGE;
+ buttonYes = DEFAULT_YES;
+ buttonNo = DEFAULT_NO;
+ targetApplications = TARGET_ALL_KNOWN;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public void setTitleByID(int titleID) {
+ title = activity.getString(titleID);
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public void setMessageByID(int messageID) {
+ message = activity.getString(messageID);
+ }
+
+ public String getButtonYes() {
+ return buttonYes;
+ }
+
+ public void setButtonYes(String buttonYes) {
+ this.buttonYes = buttonYes;
+ }
+
+ public void setButtonYesByID(int buttonYesID) {
+ buttonYes = activity.getString(buttonYesID);
+ }
+
+ public String getButtonNo() {
+ return buttonNo;
+ }
+
+ public void setButtonNo(String buttonNo) {
+ this.buttonNo = buttonNo;
+ }
+
+ public void setButtonNoByID(int buttonNoID) {
+ buttonNo = activity.getString(buttonNoID);
+ }
+
+ public Collection getTargetApplications() {
+ return targetApplications;
+ }
+
+ public final void setTargetApplications(List targetApplications) {
+ if (targetApplications.isEmpty()) {
+ throw new IllegalArgumentException("No target applications");
+ }
+ this.targetApplications = targetApplications;
+ }
+
+ public void setSingleTargetApplication(String targetApplication) {
+ this.targetApplications = Collections.singletonList(targetApplication);
+ }
+
+ public Map getMoreExtras() {
+ return moreExtras;
+ }
+
+ public final void addExtra(String key, Object value) {
+ moreExtras.put(key, value);
+ }
+
+ /**
+ * Initiates a scan for all known barcode types with the default camera.
+ *
+ * @return the {@link AlertDialog} that was shown to the user prompting them to download the app
+ * if a prompt was needed, or null otherwise.
+ */
+ public final AlertDialog initiateScan() {
+ return initiateScan(ALL_CODE_TYPES, -1);
+ }
+
+ /**
+ * Initiates a scan for all known barcode types with the specified camera.
+ *
+ * @param cameraId camera ID of the camera to use. A negative value means "no preference".
+ * @return the {@link AlertDialog} that was shown to the user prompting them to download the app
+ * if a prompt was needed, or null otherwise.
+ */
+ public final AlertDialog initiateScan(int cameraId) {
+ return initiateScan(ALL_CODE_TYPES, cameraId);
+ }
+
+ /**
+ * Initiates a scan, using the default camera, only for a certain set of barcode types, given as strings corresponding
+ * to their names in ZXing's {@code BarcodeFormat} class like "UPC_A". You can supply constants
+ * like {@link #PRODUCT_CODE_TYPES} for example.
+ *
+ * @param desiredBarcodeFormats names of {@code BarcodeFormat}s to scan for
+ * @return the {@link AlertDialog} that was shown to the user prompting them to download the app
+ * if a prompt was needed, or null otherwise.
+ */
+ public final AlertDialog initiateScan(Collection desiredBarcodeFormats) {
+ return initiateScan(desiredBarcodeFormats, -1);
+ }
+
+ /**
+ * Initiates a scan, using the specified camera, only for a certain set of barcode types, given as strings corresponding
+ * to their names in ZXing's {@code BarcodeFormat} class like "UPC_A". You can supply constants
+ * like {@link #PRODUCT_CODE_TYPES} for example.
+ *
+ * @param desiredBarcodeFormats names of {@code BarcodeFormat}s to scan for
+ * @param cameraId camera ID of the camera to use. A negative value means "no preference".
+ * @return the {@link AlertDialog} that was shown to the user prompting them to download the app
+ * if a prompt was needed, or null otherwise
+ */
+ public final AlertDialog initiateScan(Collection desiredBarcodeFormats, int cameraId) {
+ Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
+ intentScan.addCategory(Intent.CATEGORY_DEFAULT);
+
+ // check which types of codes to scan for
+ if (desiredBarcodeFormats != null) {
+ // set the desired barcode types
+ StringBuilder joinedByComma = new StringBuilder();
+ for (String format : desiredBarcodeFormats) {
+ if (joinedByComma.length() > 0) {
+ joinedByComma.append(',');
+ }
+ joinedByComma.append(format);
+ }
+ intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
+ }
+
+ // check requested camera ID
+ if (cameraId >= 0) {
+ intentScan.putExtra("SCAN_CAMERA_ID", cameraId);
+ }
+
+ String targetAppPackage = findTargetAppPackage(intentScan);
+ if (targetAppPackage == null) {
+ return showDownloadDialog();
+ }
+ intentScan.setPackage(targetAppPackage);
+ intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+ intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
+ attachMoreExtras(intentScan);
+ startActivityForResult(intentScan, REQUEST_CODE);
+ return null;
+ }
+
+ /**
+ * Start an activity. This method is defined to allow different methods of activity starting for
+ * newer versions of Android and for compatibility library.
+ *
+ * @param intent Intent to start.
+ * @param code Request code for the activity
+ * @see android.app.Activity#startActivityForResult(Intent, int)
+ * @see android.app.Fragment#startActivityForResult(Intent, int)
+ */
+ protected void startActivityForResult(Intent intent, int code) {
+ if (fragment == null) {
+ activity.startActivityForResult(intent, code);
+ } else {
+ fragment.startActivityForResult(intent, code);
+ }
+ }
+
+ private String findTargetAppPackage(Intent intent) {
+ PackageManager pm = activity.getPackageManager();
+ List availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
+ if (availableApps != null) {
+ for (String targetApp : targetApplications) {
+ if (contains(availableApps, targetApp)) {
+ return targetApp;
+ }
+ }
+ }
+ return null;
+ }
+
+ private static boolean contains(Iterable availableApps, String targetApp) {
+ for (ResolveInfo availableApp : availableApps) {
+ String packageName = availableApp.activityInfo.packageName;
+ if (targetApp.equals(packageName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private AlertDialog showDownloadDialog() {
+ AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
+ downloadDialog.setTitle(title);
+ downloadDialog.setMessage(message);
+ downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialogInterface, int i) {
+ String packageName;
+ if (targetApplications.contains(BS_PACKAGE)) {
+ // Prefer to suggest download of BS if it's anywhere in the list
+ packageName = BS_PACKAGE;
+ } else {
+ // Otherwise, first option:
+ packageName = targetApplications.get(0);
+ }
+ Uri uri = Uri.parse("market://details?id=" + packageName);
+ Intent intent = new Intent(Intent.ACTION_VIEW, uri);
+ try {
+ if (fragment == null) {
+ activity.startActivity(intent);
+ } else {
+ fragment.startActivity(intent);
+ }
+ } catch (ActivityNotFoundException anfe) {
+ // Hmm, market is not installed
+ Log.w(TAG, "Google Play is not installed; cannot install " + packageName);
+ }
+ }
+ });
+ downloadDialog.setNegativeButton(buttonNo, null);
+ downloadDialog.setCancelable(true);
+ return downloadDialog.show();
+ }
+
+
+ /**
+ *
Call this from your {@link Activity}'s
+ * {@link Activity#onActivityResult(int, int, Intent)} method.
+ *
+ * @param requestCode request code from {@code onActivityResult()}
+ * @param resultCode result code from {@code onActivityResult()}
+ * @param intent {@link Intent} from {@code onActivityResult()}
+ * @return null if the event handled here was not related to this class, or
+ * else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
+ * the fields will be null.
+ */
+ public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
+ if (requestCode == REQUEST_CODE) {
+ if (resultCode == Activity.RESULT_OK) {
+ String contents = intent.getStringExtra("SCAN_RESULT");
+ String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
+ byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
+ int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
+ Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
+ String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
+ return new IntentResult(contents,
+ formatName,
+ rawBytes,
+ orientation,
+ errorCorrectionLevel);
+ }
+ return new IntentResult();
+ }
+ return null;
+ }
+
+
+ /**
+ * Defaults to type "TEXT_TYPE".
+ *
+ * @param text the text string to encode as a barcode
+ * @return the {@link AlertDialog} that was shown to the user prompting them to download the app
+ * if a prompt was needed, or null otherwise
+ * @see #shareText(CharSequence, CharSequence)
+ */
+ public final AlertDialog shareText(CharSequence text) {
+ return shareText(text, "TEXT_TYPE");
+ }
+
+ /**
+ * Shares the given text by encoding it as a barcode, such that another user can
+ * scan the text off the screen of the device.
+ *
+ * @param text the text string to encode as a barcode
+ * @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type} constants.
+ * @return the {@link AlertDialog} that was shown to the user prompting them to download the app
+ * if a prompt was needed, or null otherwise
+ */
+ public final AlertDialog shareText(CharSequence text, CharSequence type) {
+ Intent intent = new Intent();
+ intent.addCategory(Intent.CATEGORY_DEFAULT);
+ intent.setAction(BS_PACKAGE + ".ENCODE");
+ intent.putExtra("ENCODE_TYPE", type);
+ intent.putExtra("ENCODE_DATA", text);
+ String targetAppPackage = findTargetAppPackage(intent);
+ if (targetAppPackage == null) {
+ return showDownloadDialog();
+ }
+ intent.setPackage(targetAppPackage);
+ intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+ intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
+ attachMoreExtras(intent);
+ if (fragment == null) {
+ activity.startActivity(intent);
+ } else {
+ fragment.startActivity(intent);
+ }
+ return null;
+ }
+
+ private static List list(String... values) {
+ return Collections.unmodifiableList(Arrays.asList(values));
+ }
+
+ private void attachMoreExtras(Intent intent) {
+ for (Map.Entry entry : moreExtras.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ // Kind of hacky
+ if (value instanceof Integer) {
+ intent.putExtra(key, (Integer) value);
+ } else if (value instanceof Long) {
+ intent.putExtra(key, (Long) value);
+ } else if (value instanceof Boolean) {
+ intent.putExtra(key, (Boolean) value);
+ } else if (value instanceof Double) {
+ intent.putExtra(key, (Double) value);
+ } else if (value instanceof Float) {
+ intent.putExtra(key, (Float) value);
+ } else if (value instanceof Bundle) {
+ intent.putExtra(key, (Bundle) value);
+ } else {
+ intent.putExtra(key, value.toString());
+ }
+ }
+ }
+
+}
diff --git a/src/com/google/zxing/integration/android/IntentResult.java b/src/com/google/zxing/integration/android/IntentResult.java
new file mode 100644
index 0000000..692b2b0
--- /dev/null
+++ b/src/com/google/zxing/integration/android/IntentResult.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright 2009 ZXing authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.zxing.integration.android;
+
+/**
+ *
Encapsulates the result of a barcode scan invoked through {@link IntentIntegrator}.
+ *
+ * @author Sean Owen
+ */
+public final class IntentResult {
+
+ private final String contents;
+ private final String formatName;
+ private final byte[] rawBytes;
+ private final Integer orientation;
+ private final String errorCorrectionLevel;
+
+ IntentResult() {
+ this(null, null, null, null, null);
+ }
+
+ IntentResult(String contents,
+ String formatName,
+ byte[] rawBytes,
+ Integer orientation,
+ String errorCorrectionLevel) {
+ this.contents = contents;
+ this.formatName = formatName;
+ this.rawBytes = rawBytes;
+ this.orientation = orientation;
+ this.errorCorrectionLevel = errorCorrectionLevel;
+ }
+
+ /**
+ * @return raw content of barcode
+ */
+ public String getContents() {
+ return contents;
+ }
+
+ /**
+ * @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more format names.
+ */
+ public String getFormatName() {
+ return formatName;
+ }
+
+ /**
+ * @return raw bytes of the barcode content, if applicable, or null otherwise
+ */
+ public byte[] getRawBytes() {
+ return rawBytes;
+ }
+
+ /**
+ * @return rotation of the image, in degrees, which resulted in a successful scan. May be null.
+ */
+ public Integer getOrientation() {
+ return orientation;
+ }
+
+ /**
+ * @return name of the error correction level used in the barcode, if applicable
+ */
+ public String getErrorCorrectionLevel() {
+ return errorCorrectionLevel;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder dialogText = new StringBuilder(100);
+ dialogText.append("Format: ").append(formatName).append('\n');
+ dialogText.append("Contents: ").append(contents).append('\n');
+ int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
+ dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
+ dialogText.append("Orientation: ").append(orientation).append('\n');
+ dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
+ return dialogText.toString();
+ }
+
+}
diff --git a/src/it/reyboz/bustorino/ActivityMain.java b/src/it/reyboz/bustorino/ActivityMain.java
index 67ab548..70ef6d8 100644
--- a/src/it/reyboz/bustorino/ActivityMain.java
+++ b/src/it/reyboz/bustorino/ActivityMain.java
@@ -1,650 +1,702 @@
/*
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.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
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.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
+import com.google.zxing.integration.android.IntentIntegrator;
+import com.google.zxing.integration.android.IntentResult;
import com.melnykov.fab.FloatingActionButton;
import java.io.UnsupportedEncodingException;
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 it.reyboz.bustorino.lab.adapters.AdapterBusLines;
import it.reyboz.bustorino.lab.adapters.AdapterBusStops;
import it.reyboz.bustorino.lab.asyncwget.AsyncWgetBusStopFromBusStopID;
import it.reyboz.bustorino.lab.asyncwget.AsyncWgetBusStopSuggestions;
public class ActivityMain extends ActionBarActivity {
/*
* Layout elements
*/
private EditText busStopSearchByIDEditText;
private EditText busStopSearchByNameEditText;
private TextView busStopNameTextView;
private ProgressBar progressBar;
private TextView howDoesItWorkTextView;
private Button hideHintButton;
private MenuItem actionHelpMenuItem;
private SwipeRefreshLayout swipeRefreshLayout;
private ListView resultsListView;
private FloatingActionButton floatingActionButton;
/*
* @see swipeRefreshLayout
*/
private Handler handler = new Handler();
private final Runnable refreshing = new Runnable() {
public void run() {
showSpinner(DOUBLE_SPINNER);
asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStopID);
}
};
/*
* To toggle alphabetical
*/
private final boolean SEARCH_BY_ID = true;
private final boolean SEARCH_BY_NAME = false;
private boolean searchMode;
/*
* Options
*/
private final String OPTION_SHOW_LEGEND = "show_legend";
/**
* Last successfully searched bus stop ID
*/
private String lastSuccessfullySearchedBusStopID;
AsyncWgetBusStopSuggestions asyncWgetBusStopSuggestions;
AsyncWgetBusStopFromBusStopID asyncWgetBusStopFromBusStopID;
/**
* Last successfully searched bus stop / bus stops
*/
private BusStop[] busStopsCache;
/*
* SQLite
*/
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);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton);
floatingActionButton.attachToListView(resultsListView);
// IME_ACTION_SEARCH alphabetical 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 alphabetical 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.red_500, R.color.green_500);
setSearchModeBusStopID();
// Intercept calls from URL intent
boolean tryedFromIntent = false;
String busStopID = null;
Uri data = getIntent().getData();
if (data != null) {
- switch (data.getHost()) {
- case "m.gtt.to.it":
- // http://m.gtt.to.it/m/it/arrivi.jsp?n=1254
- busStopID = data.getQueryParameter("n");
- if (busStopID == null) {
- Log.e("ActivityMain", "Expected ?n from: " + data);
- }
- break;
- case "www.gtt.to.it":
- // http://www.gtt.to.it/cms/percorari/arrivi?palina=1254cd
- busStopID = data.getQueryParameter("palina");
- if (busStopID == null) {
- Log.e("ActivityMain", "Expected ?palina from: " + data);
- }
- default:
- Log.e("ActivityMain", "Unexpected intent URL: " + data);
- }
+ busStopID = getBusStopIDFromUri(data);
tryedFromIntent = true;
}
// ...or intercept calls from other activities
if (!tryedFromIntent) {
Bundle b = getIntent().getExtras();
if (b != null) {
busStopID = b.getString("bus-stop-ID");
tryedFromIntent = true;
}
}
if (busStopID == null) {
// Show keyboard if can't start from intent
showKeyboard();
if (tryedFromIntent) {
// Show a warning if you come from intent but can't start
asyncWgetBusStopFromBusStopID(null);
}
} else {
// Start from intent successfully
busStopSearchByIDEditText.setText(busStopID);
showSpinner();
asyncWgetBusStopFromBusStopID(busStopID);
}
}
/**
* Reload bus stop timetable when it's fulled resumed.
*
* @Override
*/
protected void onPostResume() {
super.onPostResume();
Log.d("ActivityMain", "onPostResume fired");
if (searchMode == SEARCH_BY_ID && lastSuccessfullySearchedBusStopID != null && lastSuccessfullySearchedBusStopID.length() != 0) {
showSpinner();
busStopSearchByIDEditText.setText(lastSuccessfullySearchedBusStopID);
asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStopID);
}
}
@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;
}
return super.onOptionsItemSelected(item);
}
/**
* It's pure magic <3
*
* @param query Part of the busStopName
*/
private void asyncWgetBusStopSuggestions(String query) {
if (query == null || query.length() == 0) {
Toast.makeText(getApplicationContext(),
R.string.insert_bus_stop_name_error, Toast.LENGTH_SHORT).show();
hideSpinner();
return;
}
if (!NetworkTools.isConnected(getApplicationContext())) {
NetworkTools.showNetworkError(getApplicationContext());
hideSpinner();
return;
}
if (asyncWgetBusStopSuggestions != null) {
asyncWgetBusStopSuggestions.cancel(true);
asyncWgetBusStopSuggestions = null;
}
try {
asyncWgetBusStopSuggestions = new AsyncWgetBusStopSuggestions(query) {
public void onReceivedBusStopNames(BusStop[] busStops, int status) {
hideSpinner();
switch (status) {
case AsyncWgetBusStopSuggestions.ERROR_EMPTY_DOM:
case AsyncWgetBusStopSuggestions.ERROR_DOM:
Toast.makeText(getApplicationContext(),
R.string.parsing_error, Toast.LENGTH_SHORT).show();
break;
case AsyncWgetBusStopSuggestions.ERROR_NONE:
if (busStops.length == 0) {
Toast.makeText(getApplicationContext(),
R.string.no_bus_stop_have_this_name, Toast.LENGTH_SHORT).show();
} else {
for (BusStop busStop : busStops) {
MyDB.DBBusStop.addBusStop(db, busStop);
}
populateBusStopsLayout(busStops);
}
break;
}
}
};
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),
R.string.encoding_error, Toast.LENGTH_SHORT).show();
}
}
/**
* It's pure magic <3
*
* @param busStopID
*/
private void asyncWgetBusStopFromBusStopID(String busStopID) {
if (busStopID == null || busStopID.length() == 0) {
Toast.makeText(getApplicationContext(),
R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show();
hideSpinner();
return;
}
if (!NetworkTools.isConnected(getApplicationContext())) {
NetworkTools.showNetworkError(getApplicationContext());
hideSpinner();
return;
}
if (asyncWgetBusStopFromBusStopID != null) {
asyncWgetBusStopFromBusStopID.cancel(true);
asyncWgetBusStopFromBusStopID = null;
}
asyncWgetBusStopFromBusStopID = new AsyncWgetBusStopFromBusStopID(busStopID) {
public void onReceivedBusStop(BusStop busStop, int status) {
hideSpinner();
switch (status) {
case AsyncWgetBusStopSuggestions.ERROR_EMPTY_DOM:
case AsyncWgetBusStopSuggestions.ERROR_DOM:
Toast.makeText(getApplicationContext(),
R.string.parsing_error, Toast.LENGTH_SHORT).show();
break;
case AsyncWgetBusStopFromBusStopID.ERROR_NO_PASSAGES_OR_NO_BUS_STOP:
Toast.makeText(getApplicationContext(),
R.string.no_passages, Toast.LENGTH_SHORT).show();
break;
case AsyncWgetBusStopSuggestions.ERROR_NONE:
lastSuccessfullySearchedBusStopID = busStop.getBusStopID();
MyDB.DBBusStop.addBusStop(db, busStop);
populateBusLinesLayout(busStop);
break;
}
}
};
}
private void populateBusLinesLayout(BusStop busStop) {
busStop.orderBusLinesByFirstArrival();
// Remember last successfully searched busStopID
String busStopID = busStop.getBusStopID();
// Retrieve passages
BusLine[] busLines = busStop.getBusLines();
// No passages?
if (busLines.length == 0) {
Toast.makeText(getApplicationContext(),
R.string.no_arrival_times, Toast.LENGTH_SHORT).show();
return;
}
BusStop dbBusStop = MyDB.DBBusStop.getBusStop(db, busStop.getBusStopID());
String busStopNameDisplay;
if (dbBusStop != null && dbBusStop.getBusStopUsername() != null) {
busStopNameDisplay = dbBusStop.getBusStopUsername();
} else if (busStop.getBusStopName() != null) {
busStopNameDisplay = busStop.getBusStopName();
} else {
busStopNameDisplay = String.valueOf(busStopID);
}
busStopNameTextView.setText(String.format(
getString(R.string.passages), busStopNameDisplay));
// Hide the alphabetical before showing passages
hideKeyboard();
// Shows hints
if (getOption(OPTION_SHOW_LEGEND, true)) {
showHints();
} else {
hideHints();
}
prepareGUIForBusLines();
resultsListView.setAdapter(new AdapterBusLines(this, R.layout.entry_bus_line_passage, busLines));
resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
/**
* Casting because of Javamerda
* @url http://stackoverflow.com/questions/30549485/androids-list-view-parameterized-type-in-adapterview-onitemclicklistener
*/
BusLine busLine = (BusLine) parent.getItemAtPosition(position);
Log.i("ActivityMain", "Tapped busLine " + busLine.toString());
}
});
}
private void populateBusStopsLayout(BusStop[] busStops) {
busStopNameTextView.setVisibility(View.GONE);
hideKeyboard();
prepareGUIForBusStops();
resultsListView.setAdapter(new AdapterBusStops(this, R.layout.entry_bus_stop, busStops));
resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
/**
* Casting because of Javamerda
* @url http://stackoverflow.com/questions/30549485/androids-list-view-parameterized-type-in-adapterview-onitemclicklistener
*/
BusStop busStop = (BusStop) parent.getItemAtPosition(position);
Intent intent = new Intent(ActivityMain.this,
ActivityMain.class);
Bundle b = new Bundle();
b.putString("bus-stop-ID", busStop.getBusStopID());
intent.putExtras(b);
startActivity(intent);
}
});
}
/**
* OK this is pure shit
*
* @param v View clicked
*/
public void onSearchClick(View v) {
showSpinner();
if (searchMode == SEARCH_BY_ID) {
String busStopID = busStopSearchByIDEditText.getText().toString();
asyncWgetBusStopFromBusStopID(busStopID);
} else { // searchMode == SEARCH_BY_NAME
String query = busStopSearchByNameEditText.getText().toString();
asyncWgetBusStopSuggestions(query);
}
}
+ /**
+ * QR scan Intent
+ *
+ * @param v View QRButton clicked
+ */
+ public void onQRButtonClick(View v) {
+ IntentIntegrator integrator = new IntentIntegrator(this);
+ integrator.initiateScan();
+ }
+
+ /**
+ * Receive the Barcode Scanner Intent
+ *
+ * @param requestCode
+ * @param resultCode
+ * @param intent
+ */
+ public void onActivityResult(int requestCode, int resultCode, Intent intent) {
+ IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
+ if (scanResult != null) {
+ Toast.makeText(getApplicationContext(),
+ R.string.no_qrcode, Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ String content = scanResult.getContents();
+
+ Uri uri = Uri.parse(content);
+
+ String busStopID = getBusStopIDFromUri(uri);
+
+ busStopSearchByIDEditText.setText(busStopID);
+
+ showSpinner();
+ asyncWgetBusStopFromBusStopID(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();
}
}
}
public void addInFavorites(View v) {
if (lastSuccessfullySearchedBusStopID != null) {
BusStop busStop = new BusStop(lastSuccessfullySearchedBusStopID);
busStop.setIsFavorite(true);
MyDB.DBBusStop.addBusStop(db, busStop);
BusStop dbBusStop = MyDB.DBBusStop.getBusStop(db, busStop.getBusStopID());
if (dbBusStop == null || dbBusStop.getBusStopLocality() == null) {
// This will also scrape the busStopLocality
try {
new AsyncWgetBusStopSuggestions(busStop.getBusStopID()) {
@Override
public void onReceivedBusStopNames(BusStop[] busStops, int status) {
if (status == AsyncWgetBusStopSuggestions.ERROR_NONE) {
for (BusStop busStop : busStops) {
MyDB.DBBusStop.addBusStop(db, busStop);
}
}
}
};
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
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);
View view = searchMode == SEARCH_BY_ID ? busStopSearchByIDEditText : busStopSearchByNameEditText;
imm.showSoftInput(view, 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() {
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);
}
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 final boolean DOUBLE_SPINNER = true;
private final boolean NORMAL_SPINNER = false;
private void showSpinner(boolean swipeSpinner) {
if (swipeSpinner == DOUBLE_SPINNER) {
swipeRefreshLayout.setRefreshing(true);
} else { // NORMAL_SPINNER
progressBar.setVisibility(View.VISIBLE);
}
}
private void showSpinner() {
showSpinner(NORMAL_SPINNER);
}
private void hideSpinner() {
swipeRefreshLayout.setRefreshing(false);
progressBar.setVisibility(View.INVISIBLE);
}
private void prepareGUIForBusLines() {
busStopNameTextView.setVisibility(View.VISIBLE);
busStopNameTextView.setClickable(true);
swipeRefreshLayout.setEnabled(true);
swipeRefreshLayout.setVisibility(View.VISIBLE);
resultsListView.setVisibility(View.VISIBLE);
actionHelpMenuItem.setVisible(true);
}
private void prepareGUIForBusStops() {
busStopNameTextView.setText(getString(R.string.results));
busStopNameTextView.setClickable(false);
busStopNameTextView.setVisibility(View.VISIBLE);
swipeRefreshLayout.setEnabled(false);
swipeRefreshLayout.setVisibility(View.VISIBLE);
resultsListView.setVisibility(View.VISIBLE);
actionHelpMenuItem.setVisible(false);
actionHelpMenuItem.setVisible(false);
}
/**
* 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);
}
+
+ /**
+ * Try to extract the bus stop ID from a URi
+ *
+ * @param uri The URL
+ * @return bus stop ID or null
+ */
+ public String getBusStopIDFromUri(Uri uri) {
+ String busStopID;
+ switch (uri.getHost()) {
+ 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":
+ // http://www.gtt.to.it/cms/percorari/arrivi?palina=1254cd
+ busStopID = uri.getQueryParameter("palina");
+ if (busStopID == null) {
+ Log.e("ActivityMain", "Expected ?palina from: " + uri);
+ }
+ default:
+ Log.e("ActivityMain", "Unexpected intent URL: " + uri);
+ busStopID = null;
+ }
+ return busStopID;
+ }
}
\ No newline at end of file