Changeset View
Changeset View
Standalone View
Standalone View
src/it/reyboz/bustorino/ActivityMain.java
Show First 20 Lines • Show All 70 Lines • ▼ Show 20 Lines | public class ActivityMain extends GeneralActivity implements FragmentListener { | ||||
/* | /* | ||||
* Search mode | * Search mode | ||||
*/ | */ | ||||
private static final int SEARCH_BY_NAME = 0; | private static final int SEARCH_BY_NAME = 0; | ||||
private static final int SEARCH_BY_ID = 1; | private static final int SEARCH_BY_ID = 1; | ||||
private static final int SEARCH_BY_ROUTE = 2; // TODO: implement this -- https://gitpull.it/T12 | private static final int SEARCH_BY_ROUTE = 2; // TODO: implement this -- https://gitpull.it/T12 | ||||
private int searchMode; | private int searchMode; | ||||
private ImageButton addToFavorites; | |||||
/* | /* | ||||
* Options | * Options | ||||
*/ | */ | ||||
private final String OPTION_SHOW_LEGEND = "show_legend"; | private final String OPTION_SHOW_LEGEND = "show_legend"; | ||||
private final String LOCATION_PERMISSION_GIVEN = "loc_permission"; | private final String LOCATION_PERMISSION_GIVEN = "loc_permission"; | ||||
/* | /* | ||||
* Status | * Status | ||||
*/ | */ | ||||
private DBStatusManager prefsManager; | private DBStatusManager prefsManager; | ||||
private DBStatusManager.OnDBUpdateStatusChangeListener updatelistener; | private DBStatusManager.OnDBUpdateStatusChangeListener updatelistener; | ||||
private static final String DEBUG_TAG="BusTO - MainActivity"; | private static final String DEBUG_TAG = "BusTO - MainActivity"; | ||||
/* // useful for testing: | /* // useful for testing: | ||||
public class MockFetcher implements ArrivalsFetcher { | public class MockFetcher implements ArrivalsFetcher { | ||||
@Override | @Override | ||||
public Palina ReadArrivalTimesAll(String routeID, AtomicReference<result> res) { | public Palina ReadArrivalTimesAll(String routeID, AtomicReference<result> res) { | ||||
SystemClock.sleep(5000); | SystemClock.sleep(5000); | ||||
res.set(result.SERVER_ERROR); | res.set(result.SERVER_ERROR); | ||||
return new Palina(); | return new Palina(); | ||||
} | } | ||||
} | } | ||||
private ArrivalsFetcher[] ArrivalFetchers = {new MockFetcher(), new MockFetcher(), new MockFetcher(), new MockFetcher(), new MockFetcher()};*/ | private ArrivalsFetcher[] ArrivalFetchers = {new MockFetcher(), new MockFetcher(), new MockFetcher(), new MockFetcher(), new MockFetcher()};*/ | ||||
private RecursionHelper<ArrivalsFetcher> ArrivalFetchersRecursionHelper = new RecursionHelper<>(new ArrivalsFetcher[] {new GTTJSONFetcher(), new FiveTScraperFetcher()}); | private RecursionHelper<ArrivalsFetcher> ArrivalFetchersRecursionHelper = new RecursionHelper<>(new ArrivalsFetcher[]{new GTTJSONFetcher(), new FiveTScraperFetcher()}); | ||||
private RecursionHelper<StopsFinderByName> StopsFindersByNameRecursionHelper = new RecursionHelper<>(new StopsFinderByName[] {new GTTStopsFetcher(), new FiveTStopsFetcher()}); | private RecursionHelper<StopsFinderByName> StopsFindersByNameRecursionHelper = new RecursionHelper<>(new StopsFinderByName[]{new GTTStopsFetcher(), new FiveTStopsFetcher()}); | ||||
/* | /* | ||||
* Position | * Position | ||||
*/ | */ | ||||
//Fine location criteria | //Fine location criteria | ||||
private final Criteria cr = new Criteria(); | private final Criteria cr = new Criteria(); | ||||
private boolean pendingNearbyStopsRequest = false; | private boolean pendingNearbyStopsRequest = false; | ||||
private LocationManager locmgr; | private LocationManager locmgr; | ||||
/* | /* | ||||
* Database Access | * Database Access | ||||
*/ | */ | ||||
private StopsDB stopsDB; | private StopsDB stopsDB; | ||||
private UserDB userDB; | private UserDB userDB; | ||||
private FragmentHelper fh; | private FragmentHelper fh; | ||||
///////////////////////////////// EVENT HANDLERS /////////////////////////////////////////////// | ///////////////////////////////// EVENT HANDLERS /////////////////////////////////////////////// | ||||
/* | /* | ||||
* @see swipeRefreshLayout | * @see swipeRefreshLayout | ||||
*/ | */ | ||||
private Handler handler = new Handler(); | private Handler handler = new Handler(); | ||||
private final Runnable refreshing = new Runnable() { | private final Runnable refreshing = new Runnable() { | ||||
public void run() { | public void run() { | ||||
if(framan.findFragmentById(R.id.resultFrame) instanceof ArrivalsFragment){ | if (framan.findFragmentById(R.id.resultFrame) instanceof ArrivalsFragment) { | ||||
ArrivalsFragment fragment = (ArrivalsFragment) framan.findFragmentById(R.id.resultFrame); | ArrivalsFragment fragment = (ArrivalsFragment) framan.findFragmentById(R.id.resultFrame); | ||||
String stopName = fragment.getStopID(); | String stopName = fragment.getStopID(); | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(stopName); | new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS, fh).execute(stopName); | ||||
} else | } else | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(); | new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS, fh).execute(); | ||||
} | } | ||||
}; | }; | ||||
//// MAIN METHOD /// | //// MAIN METHOD /// | ||||
@Override | @Override | ||||
protected void onCreate(Bundle savedInstanceState) { | protected void onCreate(Bundle savedInstanceState) { | ||||
super.onCreate(savedInstanceState); | super.onCreate(savedInstanceState); | ||||
▲ Show 20 Lines • Show All 52 Lines • ▼ Show 20 Lines | protected void onCreate(Bundle savedInstanceState) { | ||||
handler.post(refreshing); | handler.post(refreshing); | ||||
} | } | ||||
}); | }); | ||||
/** | /** | ||||
* @author Marco Gagino!!! | * @author Marco Gagino!!! | ||||
*/ | */ | ||||
//swipeRefreshLayout.setColorSchemeColors(R.color.blue_500, R.color.orange_500); // setColorScheme is deprecated, setColorSchemeColors isn't | //swipeRefreshLayout.setColorSchemeColors(R.color.blue_500, R.color.orange_500); // setColorScheme is deprecated, setColorSchemeColors isn't | ||||
swipeRefreshLayout.setColorSchemeResources(R.color.blue_500,R.color.orange_500); | swipeRefreshLayout.setColorSchemeResources(R.color.blue_500, R.color.orange_500); | ||||
fh = new FragmentHelper(this,R.id.listRefreshLayout,R.id.resultFrame); | fh = new FragmentHelper(this, R.id.listRefreshLayout, R.id.resultFrame); | ||||
setSearchModeBusStopID(); | setSearchModeBusStopID(); | ||||
//---------------------------- START INTENT CHECK QUEUE ------------------------------------ | //---------------------------- START INTENT CHECK QUEUE ------------------------------------ | ||||
// Intercept calls from URL intent | // Intercept calls from URL intent | ||||
boolean tryedFromIntent = false; | boolean tryedFromIntent = false; | ||||
String busStopID = null; | String busStopID = null; | ||||
▲ Show 20 Lines • Show All 49 Lines • ▼ Show 20 Lines | protected void onCreate(Bundle savedInstanceState) { | ||||
createFragmentForStop(busStopID); | createFragmentForStop(busStopID); | ||||
} | } | ||||
//Try (hopefully) database update | //Try (hopefully) database update | ||||
//TODO: Start the service in foreground, check last time it ran before | //TODO: Start the service in foreground, check last time it ran before | ||||
DatabaseUpdateService.startDBUpdate(getApplicationContext()); | DatabaseUpdateService.startDBUpdate(getApplicationContext()); | ||||
/* | /* | ||||
Set database update | Set database update | ||||
*/ | */ | ||||
updatelistener = new DBStatusManager.OnDBUpdateStatusChangeListener(){ | updatelistener = new DBStatusManager.OnDBUpdateStatusChangeListener() { | ||||
@Override | @Override | ||||
public boolean defaultStatusValue() { | public boolean defaultStatusValue() { | ||||
return true; | return true; | ||||
} | } | ||||
@Override | @Override | ||||
public void onDBStatusChanged(boolean updating) { | public void onDBStatusChanged(boolean updating) { | ||||
if(updating){ | if (updating) { | ||||
createDefaultSnackbar(); | createDefaultSnackbar(); | ||||
} | } else if (snackbar != null) { | ||||
else if(snackbar!=null){ | |||||
snackbar.dismiss(); | snackbar.dismiss(); | ||||
snackbar = null; | snackbar = null; | ||||
} | } | ||||
} | } | ||||
}; | }; | ||||
prefsManager = new DBStatusManager(getApplicationContext(),updatelistener); | prefsManager = new DBStatusManager(getApplicationContext(), updatelistener); | ||||
prefsManager.registerListener(); | prefsManager.registerListener(); | ||||
//locationHandler = new GPSLocationAdapter(getApplicationContext()); | //locationHandler = new GPSLocationAdapter(getApplicationContext()); | ||||
//--------- NEARBY STOPS--------// | //--------- NEARBY STOPS--------// | ||||
//SETUP LOCATION | //SETUP LOCATION | ||||
locmgr = (LocationManager) getSystemService(LOCATION_SERVICE); | locmgr = (LocationManager) getSystemService(LOCATION_SERVICE); | ||||
cr.setAccuracy(Criteria.ACCURACY_FINE); | cr.setAccuracy(Criteria.ACCURACY_FINE); | ||||
cr.setAltitudeRequired(false); | cr.setAltitudeRequired(false); | ||||
cr.setBearingRequired(false); | cr.setBearingRequired(false); | ||||
cr.setCostAllowed(true); | cr.setCostAllowed(true); | ||||
cr.setPowerRequirement(Criteria.NO_REQUIREMENT); | cr.setPowerRequirement(Criteria.NO_REQUIREMENT); | ||||
//We want the nearby bus stops! | //We want the nearby bus stops! | ||||
handler.post(new NearbyStopsRequester()); | handler.post(new NearbyStopsRequester()); | ||||
//If there are no providers available, then, wait for them | //If there are no providers available, then, wait for them | ||||
Log.d("MainActivity", "Created"); | Log.d("MainActivity", "Created"); | ||||
} | } | ||||
/** | /** | ||||
* Reload bus stop timetable when it's fulled resumed from background. | * Reload bus stop timetable when it's fulled resumed from background. | ||||
*/ | */ | ||||
/** | /** | ||||
@Override | * @Override protected void onPostResume() { | ||||
protected void onPostResume() { | * super.onPostResume(); | ||||
super.onPostResume(); | * Log.d("ActivityMain", "onPostResume fired. Last successfully bus stop ID: " + fh.getLastSuccessfullySearchedBusStop()); | ||||
Log.d("ActivityMain", "onPostResume fired. Last successfully bus stop ID: " + fh.getLastSuccessfullySearchedBusStop()); | * if (searchMode == SEARCH_BY_ID && fh.getLastSuccessfullySearchedBusStop() != null) { | ||||
if (searchMode == SEARCH_BY_ID && fh.getLastSuccessfullySearchedBusStop() != null) { | * setBusStopSearchByIDEditText(fh.getLastSuccessfullySearchedBusStop().ID); | ||||
setBusStopSearchByIDEditText(fh.getLastSuccessfullySearchedBusStop().ID); | * //new asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStop.ID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); | ||||
//new asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStop.ID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); | * new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(); | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(); | * } else { | ||||
} else { | * //we have new activity or we don't have a new searched stop. | ||||
//we have new activity or we don't have a new searched stop. | * //Let's search stops nearby | ||||
//Let's search stops nearby | * LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE); | ||||
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE); | * Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.resultFrame); | ||||
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.resultFrame); | * <p> | ||||
* <p> | |||||
* } | |||||
} | * //show the FAB since it remains hidden | ||||
//show the FAB since it remains hidden | * floatingActionButton.show(); | ||||
floatingActionButton.show(); | * <p> | ||||
* } | |||||
} | |||||
**/ | **/ | ||||
@Override | @Override | ||||
protected void onPause() { | protected void onPause() { | ||||
super.onPause(); | super.onPause(); | ||||
fh.stopLastRequestIfNeeded(); | fh.stopLastRequestIfNeeded(); | ||||
fh.setBlockAllActivities(true); | fh.setBlockAllActivities(true); | ||||
if(updatelistener!=null && prefsManager!=null) prefsManager.unregisterListener(); | if (updatelistener != null && prefsManager != null) prefsManager.unregisterListener(); | ||||
locmgr.removeUpdates(locListener); | locmgr.removeUpdates(locListener); | ||||
} | } | ||||
@Override | @Override | ||||
protected void onResume() { | protected void onResume() { | ||||
super.onResume(); | super.onResume(); | ||||
fh.setBlockAllActivities(false); | fh.setBlockAllActivities(false); | ||||
if(updatelistener!=null && prefsManager!=null) { | if (updatelistener != null && prefsManager != null) { | ||||
prefsManager.registerListener(); | prefsManager.registerListener(); | ||||
if(prefsManager.isDBUpdating(true)){ | if (prefsManager.isDBUpdating(true)) { | ||||
createDefaultSnackbar(); | createDefaultSnackbar(); | ||||
} | } | ||||
} | } | ||||
if(pendingNearbyStopsRequest) | if (pendingNearbyStopsRequest) | ||||
handler.post(new NearbyStopsRequester()); | handler.post(new NearbyStopsRequester()); | ||||
} | } | ||||
@Override | @Override | ||||
public boolean onCreateOptionsMenu(Menu menu) { | public boolean onCreateOptionsMenu(Menu menu) { | ||||
// Inflate the menu; this adds items to the action bar if it is present. | // Inflate the menu; this adds items to the action bar if it is present. | ||||
getMenuInflater().inflate(R.menu.main, menu); | getMenuInflater().inflate(R.menu.main, menu); | ||||
Show All 34 Lines | public boolean onOptionsItemSelected(MenuItem item) { | ||||
return true; | return true; | ||||
case R.id.action_source: | case R.id.action_source: | ||||
openIceweasel("https://gitpull.it/w/librebusto/#how-to-hack-busto"); | openIceweasel("https://gitpull.it/w/librebusto/#how-to-hack-busto"); | ||||
return true; | return true; | ||||
case R.id.action_licence: | case R.id.action_licence: | ||||
openIceweasel("https://www.gnu.org/licenses/gpl-3.0.html"); | openIceweasel("https://www.gnu.org/licenses/gpl-3.0.html"); | ||||
return true; | return true; | ||||
case R.id.action_settings: | case R.id.action_settings: | ||||
Log.d("MAINBusTO","Pressed button preferences"); | Log.d("MAINBusTO", "Pressed button preferences"); | ||||
startActivity(new Intent(ActivityMain.this,ActivitySettings.class)); | startActivity(new Intent(ActivityMain.this, ActivitySettings.class)); | ||||
} | } | ||||
return super.onOptionsItemSelected(item); | return super.onOptionsItemSelected(item); | ||||
} | } | ||||
/** | /** | ||||
* OK this is pure shit | * OK this is pure shit | ||||
* | * | ||||
* @param v View clicked | * @param v View clicked | ||||
*/ | */ | ||||
public void onSearchClick(View v) { | public void onSearchClick(View v) { | ||||
if (searchMode == SEARCH_BY_ID) { | if (searchMode == SEARCH_BY_ID) { | ||||
String busStopID = busStopSearchByIDEditText.getText().toString(); | String busStopID = busStopSearchByIDEditText.getText().toString(); | ||||
//OLD ASYNCTASK | //OLD ASYNCTASK | ||||
//new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); | //new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); | ||||
if(busStopID == null || busStopID.length() <= 0) { | if (busStopID == null || busStopID.length() <= 0) { | ||||
showMessage(R.string.insert_bus_stop_number_error); | showMessage(R.string.insert_bus_stop_number_error); | ||||
toggleSpinner(false); | toggleSpinner(false); | ||||
} else{ | } else { | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(busStopID); | new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS, fh).execute(busStopID); | ||||
Log.d("MainActiv","Started search for arrivals of stop "+busStopID); | Log.d("MainActiv", "Started search for arrivals of stop " + busStopID); | ||||
} | } | ||||
} else { // searchMode == SEARCH_BY_NAME | } else { // searchMode == SEARCH_BY_NAME | ||||
String query = busStopSearchByNameEditText.getText().toString(); | String query = busStopSearchByNameEditText.getText().toString(); | ||||
//new asyncWgetBusStopSuggestions(query, stopsDB, StopsFindersByNameRecursionHelper); | //new asyncWgetBusStopSuggestions(query, stopsDB, StopsFindersByNameRecursionHelper); | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.STOPS,fh).execute(query); | new AsyncDataDownload(AsyncDataDownload.RequestType.STOPS, fh).execute(query); | ||||
} | } | ||||
} | } | ||||
/** PERMISSION STUFF **/ | |||||
/** | |||||
* PERMISSION STUFF | |||||
**/ | |||||
@Override | @Override | ||||
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { | ||||
switch (requestCode){ | switch (requestCode) { | ||||
case PERMISSION_REQUEST_POSITION: | case PERMISSION_REQUEST_POSITION: | ||||
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){ | if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { | ||||
setOption(LOCATION_PERMISSION_GIVEN,true); | setOption(LOCATION_PERMISSION_GIVEN, true); | ||||
//if we sent a request for a new NearbyStopsFragment | //if we sent a request for a new NearbyStopsFragment | ||||
if(pendingNearbyStopsRequest){ | if (pendingNearbyStopsRequest) { | ||||
pendingNearbyStopsRequest=false; | pendingNearbyStopsRequest = false; | ||||
handler.post(new NearbyStopsRequester()); | handler.post(new NearbyStopsRequester()); | ||||
} | } | ||||
} else { | } else { | ||||
//permission denied | //permission denied | ||||
setOption(LOCATION_PERMISSION_GIVEN,false); | setOption(LOCATION_PERMISSION_GIVEN, false); | ||||
} | } | ||||
//add other cases for permissions | //add other cases for permissions | ||||
} | } | ||||
} | } | ||||
@Override | @Override | ||||
public void createFragmentForStop(String ID) { | public void createFragmentForStop(String ID) { | ||||
//new asyncWgetBusStopFromBusStopID(ID, ArrivalFetchersRecursionHelper,lastSuccessfullySearchedBusStop); | //new asyncWgetBusStopFromBusStopID(ID, ArrivalFetchersRecursionHelper,lastSuccessfullySearchedBusStop); | ||||
if(ID == null || ID.length() <= 0) { | if (ID == null || ID.length() <= 0) { | ||||
// we're still in UI thread, no need to mess with Progress | // we're still in UI thread, no need to mess with Progress | ||||
showMessage(R.string.insert_bus_stop_number_error); | showMessage(R.string.insert_bus_stop_number_error); | ||||
toggleSpinner(false); | toggleSpinner(false); | ||||
} else { | } else { | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(ID); | new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS, fh).execute(ID); | ||||
Log.d("MainActiv","Started search for arrivals of stop "+ID); | Log.d("MainActiv", "Started search for arrivals of stop " + ID); | ||||
} | } | ||||
} | } | ||||
/** | /** | ||||
* QR scan button clicked | * QR scan button clicked | ||||
* | * | ||||
* @param v View QRButton clicked | * @param v View QRButton clicked | ||||
*/ | */ | ||||
public void onQRButtonClick(View v) { | public void onQRButtonClick(View v) { | ||||
IntentIntegrator integrator = new IntentIntegrator(this); | IntentIntegrator integrator = new IntentIntegrator(this); | ||||
integrator.initiateScan(); | integrator.initiateScan(); | ||||
} | } | ||||
/** | /** | ||||
* Receive the Barcode Scanner Intent | * Receive the Barcode Scanner Intent | ||||
* | |||||
*/ | */ | ||||
public void onActivityResult(int requestCode, int resultCode, Intent intent) { | public void onActivityResult(int requestCode, int resultCode, Intent intent) { | ||||
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); | IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); | ||||
Uri uri; | Uri uri; | ||||
try { | try { | ||||
uri = Uri.parse(scanResult != null ? scanResult.getContents() : null); // this apparently prevents NullPointerException. Somehow. | uri = Uri.parse(scanResult != null ? scanResult.getContents() : null); // this apparently prevents NullPointerException. Somehow. | ||||
} catch (NullPointerException e) { | } catch (NullPointerException e) { | ||||
Show All 20 Lines | public void onToggleKeyboardLayout(View v) { | ||||
} | } | ||||
} else { // searchMode == SEARCH_BY_ID | } else { // searchMode == SEARCH_BY_ID | ||||
setSearchModeBusStopName(); | setSearchModeBusStopName(); | ||||
if (busStopSearchByNameEditText.requestFocus()) { | if (busStopSearchByNameEditText.requestFocus()) { | ||||
showKeyboard(); | showKeyboard(); | ||||
} | } | ||||
} | } | ||||
} | } | ||||
private void createDefaultSnackbar(){ | private void createDefaultSnackbar() { | ||||
if(snackbar==null){ | if (snackbar == null) { | ||||
snackbar = Snackbar.make(findViewById(R.id.searchButton),R.string.database_update_message,Snackbar.LENGTH_INDEFINITE); | snackbar = Snackbar.make(findViewById(R.id.searchButton), R.string.database_update_message, Snackbar.LENGTH_INDEFINITE); | ||||
} | } | ||||
snackbar.show(); | snackbar.show(); | ||||
} | } | ||||
///////////////////////////////// POSITION STUFF////////////////////////////////////////////// | ///////////////////////////////// POSITION STUFF////////////////////////////////////////////// | ||||
private void resolveStopRequest(String provider){ | private void resolveStopRequest(String provider) { | ||||
Log.d(DEBUG_TAG,"Provider "+provider+" got enabled"); | Log.d(DEBUG_TAG, "Provider " + provider + " got enabled"); | ||||
if(locmgr!=null && pendingNearbyStopsRequest && locmgr.getProvider(provider).meetsCriteria(cr)){ | if (locmgr != null && pendingNearbyStopsRequest && locmgr.getProvider(provider).meetsCriteria(cr)) { | ||||
pendingNearbyStopsRequest = false; | pendingNearbyStopsRequest = false; | ||||
handler.post(new NearbyStopsRequester()); | handler.post(new NearbyStopsRequester()); | ||||
} | } | ||||
} | } | ||||
final LocationListener locListener = new LocationListener() { | final LocationListener locListener = new LocationListener() { | ||||
@Override | @Override | ||||
public void onLocationChanged(Location location) { | public void onLocationChanged(Location location) { | ||||
Log.d(DEBUG_TAG,"Location changed"); | Log.d(DEBUG_TAG, "Location changed"); | ||||
} | } | ||||
@Override | @Override | ||||
public void onStatusChanged(String provider, int status, Bundle extras) { | public void onStatusChanged(String provider, int status, Bundle extras) { | ||||
Log.d(DEBUG_TAG,"Location provider status: "+status); | Log.d(DEBUG_TAG, "Location provider status: " + status); | ||||
if(status== LocationProvider.AVAILABLE){ | if (status == LocationProvider.AVAILABLE) { | ||||
resolveStopRequest(provider); | resolveStopRequest(provider); | ||||
} | } | ||||
} | } | ||||
@Override | @Override | ||||
public void onProviderEnabled(String provider) { | public void onProviderEnabled(String provider) { | ||||
resolveStopRequest(provider); | resolveStopRequest(provider); | ||||
} | } | ||||
@Override | @Override | ||||
public void onProviderDisabled(String provider) { | public void onProviderDisabled(String provider) { | ||||
} | } | ||||
}; | }; | ||||
class NearbyStopsRequester implements Runnable{ | class NearbyStopsRequester implements Runnable { | ||||
@SuppressLint("MissingPermission") | @SuppressLint("MissingPermission") | ||||
@Override | @Override | ||||
public void run() { | public void run() { | ||||
final boolean canRunPosition = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || getOption(LOCATION_PERMISSION_GIVEN, false); | final boolean canRunPosition = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || getOption(LOCATION_PERMISSION_GIVEN, false); | ||||
if(!canRunPosition){ | if (!canRunPosition) { | ||||
pendingNearbyStopsRequest = true; | pendingNearbyStopsRequest = true; | ||||
assertLocationPermissions(); | assertLocationPermissions(); | ||||
return; | return; | ||||
} else setOption(LOCATION_PERMISSION_GIVEN,true); | } else setOption(LOCATION_PERMISSION_GIVEN, true); | ||||
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE); | LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE); | ||||
if(locManager == null) { | if (locManager == null) { | ||||
Log.e(DEBUG_TAG, "location manager is nihil, cannot create NearbyStopsFragment"); | Log.e(DEBUG_TAG, "location manager is nihil, cannot create NearbyStopsFragment"); | ||||
return; | return; | ||||
} | } | ||||
if(anyLocationProviderMatchesCriteria(locManager,cr,true) && fh.getLastSuccessfullySearchedBusStop()==null) { | if (anyLocationProviderMatchesCriteria(locManager, cr, true) && fh.getLastSuccessfullySearchedBusStop() == null) { | ||||
//Go ahead with the request | //Go ahead with the request | ||||
Log.d("mainActivity","Recreating stop fragment"); | Log.d("mainActivity", "Recreating stop fragment"); | ||||
swipeRefreshLayout.setVisibility(View.VISIBLE); | swipeRefreshLayout.setVisibility(View.VISIBLE); | ||||
NearbyStopsFragment fragment = NearbyStopsFragment.newInstance(NearbyStopsFragment.TYPE_STOPS); | NearbyStopsFragment fragment = NearbyStopsFragment.newInstance(NearbyStopsFragment.TYPE_STOPS); | ||||
Fragment oldFrag = framan.findFragmentById(R.id.resultFrame); | Fragment oldFrag = framan.findFragmentById(R.id.resultFrame); | ||||
FragmentTransaction ft = framan.beginTransaction(); | FragmentTransaction ft = framan.beginTransaction(); | ||||
if(oldFrag!=null) | if (oldFrag != null) | ||||
ft.remove(oldFrag); | ft.remove(oldFrag); | ||||
ft.add(R.id.resultFrame,fragment,"nearbyStop_correct"); | ft.add(R.id.resultFrame, fragment, "nearbyStop_correct"); | ||||
ft.commit(); | ft.commit(); | ||||
framan.executePendingTransactions(); | framan.executePendingTransactions(); | ||||
pendingNearbyStopsRequest = false; | pendingNearbyStopsRequest = false; | ||||
} else if(!anyLocationProviderMatchesCriteria(locManager,cr,true)){ | } else if (!anyLocationProviderMatchesCriteria(locManager, cr, true)) { | ||||
//Wait for the providers | //Wait for the providers | ||||
Log.d(DEBUG_TAG,"Queuing position request"); | Log.d(DEBUG_TAG, "Queuing position request"); | ||||
pendingNearbyStopsRequest = true; | pendingNearbyStopsRequest = true; | ||||
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10,0.1f,locListener); | locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 0.1f, locListener); | ||||
} | } | ||||
} | } | ||||
} | } | ||||
private boolean anyLocationProviderMatchesCriteria(LocationManager mng, Criteria cr, boolean enabled){ | private boolean anyLocationProviderMatchesCriteria(LocationManager mng, Criteria cr, boolean enabled) { | ||||
List<String> providers = mng.getProviders(cr,enabled); | List<String> providers = mng.getProviders(cr, enabled); | ||||
Log.d(DEBUG_TAG,"Getting enabled location providers: "); | Log.d(DEBUG_TAG, "Getting enabled location providers: "); | ||||
for(String s: providers){ | for (String s : providers) { | ||||
Log.d(DEBUG_TAG,"Provider "+s); | Log.d(DEBUG_TAG, "Provider " + s); | ||||
} | } | ||||
return providers.size()>0; | return providers.size() > 0; | ||||
} | } | ||||
///////////////////////////////// OTHER STUFF ////////////////////////////////////////////////// | ///////////////////////////////// OTHER STUFF ////////////////////////////////////////////////// | ||||
/** | /** | ||||
* Get the last successfully searched bus stop or NULL | * Get the last successfully searched bus stop or NULL | ||||
* | * | ||||
* @return | * @return | ||||
*/ | */ | ||||
@Override | @Override | ||||
Show All 12 Lines | public String getLastSuccessfullySearchedBusStopID() { | ||||
return stop == null ? null : stop.ID; | return stop == null ? null : stop.ID; | ||||
} | } | ||||
/** | /** | ||||
* Update the star "Add to favorite" icon | * Update the star "Add to favorite" icon | ||||
*/ | */ | ||||
@Override | @Override | ||||
public void updateStarIconFromLastBusStop() { | public void updateStarIconFromLastBusStop() { | ||||
// no favorites no party! | |||||
addToFavorites = (ImageButton) findViewById(R.id.addToFavorites); | |||||
if (addToFavorites == null) { | |||||
Log.d("MainActivity", "Why the fuck the star is not here?!"); | |||||
return; | |||||
} | |||||
// check if there is a last Stop | // check if there is a last Stop | ||||
String stopID = getLastSuccessfullySearchedBusStopID(); | String stopID = getLastSuccessfullySearchedBusStopID(); | ||||
if(stopID == null) { | if (stopID == null) { | ||||
// TODO: hide the star | addToFavorites.setVisibility(View.INVISIBLE); | ||||
} else { | } else { | ||||
// filled or outline? | // filled or outline? | ||||
if(isStopInFavorites(stopID)) { | if (isStopInFavorites(stopID)) { | ||||
// TODO: fill star | addToFavorites.setImageResource(R.drawable.ic_star_filled); | ||||
} else { | } else { | ||||
// TODO: outline star | addToFavorites.setImageResource(R.drawable.ic_star_outline); | ||||
} | } | ||||
// TODO: show the star | addToFavorites.setVisibility(View.VISIBLE); | ||||
} | } | ||||
} | } | ||||
/** | /** | ||||
* Check if the last Bus Stop is in the favorites | * Check if the last Bus Stop is in the favorites | ||||
* | * | ||||
* @return | * @return | ||||
*/ | */ | ||||
public boolean isStopInFavorites(String busStopId) { | public boolean isStopInFavorites(String busStopId) { | ||||
boolean found = false; | boolean found = false; | ||||
// no stop no party | // no stop no party | ||||
if(busStopId != null) { | if (busStopId != null) { | ||||
SQLiteDatabase userDB = new UserDB(getApplicationContext()).getReadableDatabase(); | SQLiteDatabase userDB = new UserDB(getApplicationContext()).getReadableDatabase(); | ||||
found = UserDB.isStopInFavorites(userDB, busStopId); | found = UserDB.isStopInFavorites(userDB, busStopId); | ||||
} | } | ||||
return found; | return found; | ||||
} | } | ||||
/** | /** | ||||
* Add the last Stop to favorites | * Add the last Stop to favorites | ||||
*/ | */ | ||||
@Override | @Override | ||||
public void toggleLastStopToFavorites() { | public void toggleLastStopToFavorites() { | ||||
Stop stop = getLastSuccessfullySearchedBusStop(); | Stop stop = getLastSuccessfullySearchedBusStop(); | ||||
if(stop != null) { | if (stop != null) { | ||||
// toggle the status in background | // toggle the status in background | ||||
new AsyncStopFavoriteAction(getApplicationContext(), AsyncStopFavoriteAction.Action.TOGGLE) { | new AsyncStopFavoriteAction(getApplicationContext(), AsyncStopFavoriteAction.Action.TOGGLE) { | ||||
/** | /** | ||||
* Callback fired when the Stop is saved in the favorites | * Callback fired when the Stop is saved in the favorites | ||||
* @param result | * @param result | ||||
*/ | */ | ||||
@Override | @Override | ||||
protected void onPostExecute(Boolean result) { | protected void onPostExecute(Boolean result) { | ||||
super.onPostExecute(result); | super.onPostExecute(result); | ||||
// update the star icon | // update the star icon | ||||
updateStarIconFromLastBusStop(); | updateStarIconFromLastBusStop(); | ||||
} | } | ||||
}.execute(stop); | }.execute(stop); | ||||
} else { | } else { | ||||
// this case have no sense, but just immediately update the favorite icon | // this case have no sense, but just immediately update the favorite icon | ||||
updateStarIconFromLastBusStop(); | updateStarIconFromLastBusStop(); | ||||
} | } | ||||
} | } | ||||
@Override | @Override | ||||
public void showFloatingActionButton(boolean yes) { | public void showFloatingActionButton(boolean yes) { | ||||
if(yes) floatingActionButton.show(); | if (yes) floatingActionButton.show(); | ||||
else floatingActionButton.hide(); | else floatingActionButton.hide(); | ||||
} | } | ||||
@Override | @Override | ||||
public void enableRefreshLayout(boolean yes) { | public void enableRefreshLayout(boolean yes) { | ||||
swipeRefreshLayout.setEnabled(yes); | swipeRefreshLayout.setEnabled(yes); | ||||
} | } | ||||
Show All 23 Lines | private void setSearchModeBusStopName() { | ||||
busStopSearchByIDEditText.setVisibility(View.GONE); | busStopSearchByIDEditText.setVisibility(View.GONE); | ||||
busStopSearchByIDEditText.setText(""); | busStopSearchByIDEditText.setText(""); | ||||
busStopSearchByNameEditText.setVisibility(View.VISIBLE); | busStopSearchByNameEditText.setVisibility(View.VISIBLE); | ||||
floatingActionButton.setImageResource(R.drawable.numeric); | floatingActionButton.setImageResource(R.drawable.numeric); | ||||
} | } | ||||
/** | /** | ||||
* Having that cursor at the left of the edit text makes me cancer. | * Having that cursor at the left of the edit text makes me cancer. | ||||
* | |||||
* @param busStopID bus stop ID | * @param busStopID bus stop ID | ||||
*/ | */ | ||||
private void setBusStopSearchByIDEditText(String busStopID) { | private void setBusStopSearchByIDEditText(String busStopID) { | ||||
busStopSearchByIDEditText.setText(busStopID); | busStopSearchByIDEditText.setText(busStopID); | ||||
busStopSearchByIDEditText.setSelection(busStopID.length()); | busStopSearchByIDEditText.setSelection(busStopID.length()); | ||||
} | } | ||||
private void showHints() { | private void showHints() { | ||||
Show All 32 Lines | private void prepareGUIForBusStops() { | ||||
swipeRefreshLayout.setVisibility(View.VISIBLE); | swipeRefreshLayout.setVisibility(View.VISIBLE); | ||||
actionHelpMenuItem.setVisible(false); | actionHelpMenuItem.setVisible(false); | ||||
} | } | ||||
/** | /** | ||||
* This provides a temporary fix to make the transition | * This provides a temporary fix to make the transition | ||||
* to a single asynctask go smoother | * to a single asynctask go smoother | ||||
* | |||||
* @param fragmentType the type of fragment created | * @param fragmentType the type of fragment created | ||||
*/ | */ | ||||
@Override | @Override | ||||
public void readyGUIfor(FragmentKind fragmentType) { | public void readyGUIfor(FragmentKind fragmentType) { | ||||
hideKeyboard(); | hideKeyboard(); | ||||
//if we are getting results, already, stop waiting for nearbyStops | //if we are getting results, already, stop waiting for nearbyStops | ||||
if(pendingNearbyStopsRequest && (fragmentType==FragmentKind.ARRIVALS || fragmentType==FragmentKind.STOPS)) { | if (pendingNearbyStopsRequest && (fragmentType == FragmentKind.ARRIVALS || fragmentType == FragmentKind.STOPS)) { | ||||
locmgr.removeUpdates(locListener); | locmgr.removeUpdates(locListener); | ||||
pendingNearbyStopsRequest = false; | pendingNearbyStopsRequest = false; | ||||
} | } | ||||
if(fragmentType==null) Log.e("ActivityMain","Problem with fragmentType"); | if (fragmentType == null) Log.e("ActivityMain", "Problem with fragmentType"); | ||||
else | else | ||||
switch (fragmentType){ | switch (fragmentType) { | ||||
case ARRIVALS: | case ARRIVALS: | ||||
prepareGUIForBusLines(); | prepareGUIForBusLines(); | ||||
if (getOption(OPTION_SHOW_LEGEND, true)) { | if (getOption(OPTION_SHOW_LEGEND, true)) { | ||||
showHints(); | showHints(); | ||||
} | } | ||||
break; | break; | ||||
case STOPS: | case STOPS: | ||||
prepareGUIForBusStops(); | prepareGUIForBusStops(); | ||||
break; | break; | ||||
default: | default: | ||||
Log.e("BusTO Activity","Called readyGUI with unsupported type of Fragment"); | Log.e("BusTO Activity", "Called readyGUI with unsupported type of Fragment"); | ||||
return; | return; | ||||
} | } | ||||
// Shows hints | // Shows hints | ||||
} | } | ||||
/** | /** | ||||
* Open an URL in the default browser. | * Open an URL in the default browser. | ||||
* | * | ||||
* @param url URL | * @param url URL | ||||
Show All 11 Lines | public class ActivityMain extends GeneralActivity implements FragmentListener { | ||||
* @param uri The URL | * @param uri The URL | ||||
* @return bus stop ID or null | * @return bus stop ID or null | ||||
*/ | */ | ||||
public static String getBusStopIDFromUri(Uri uri) { | public static String getBusStopIDFromUri(Uri uri) { | ||||
String busStopID; | String busStopID; | ||||
// everithing catches fire when passing null to a switch. | // everithing catches fire when passing null to a switch. | ||||
String host = uri.getHost(); | String host = uri.getHost(); | ||||
if(host == null) { | if (host == null) { | ||||
Log.e("ActivityMain", "Not an URL: " + uri); | Log.e("ActivityMain", "Not an URL: " + uri); | ||||
return null; | return null; | ||||
} | } | ||||
switch(host) { | switch (host) { | ||||
case "m.gtt.to.it": | case "m.gtt.to.it": | ||||
// http://m.gtt.to.it/m/it/arrivi.jsp?n=1254 | // http://m.gtt.to.it/m/it/arrivi.jsp?n=1254 | ||||
busStopID = uri.getQueryParameter("n"); | busStopID = uri.getQueryParameter("n"); | ||||
if (busStopID == null) { | if (busStopID == null) { | ||||
Log.e("ActivityMain", "Expected ?n from: " + uri); | Log.e("ActivityMain", "Expected ?n from: " + uri); | ||||
} | } | ||||
break; | break; | ||||
case "www.gtt.to.it": | case "www.gtt.to.it": | ||||
case "gtt.to.it": | case "gtt.to.it": | ||||
// http://www.gtt.to.it/cms/percorari/arrivi?palina=1254 | // http://www.gtt.to.it/cms/percorari/arrivi?palina=1254 | ||||
busStopID = uri.getQueryParameter("palina"); | busStopID = uri.getQueryParameter("palina"); | ||||
if (busStopID == null) { | if (busStopID == null) { | ||||
Log.e("ActivityMain", "Expected ?palina from: " + uri); | Log.e("ActivityMain", "Expected ?palina from: " + uri); | ||||
} | } | ||||
break; | break; | ||||
default: | default: | ||||
Log.e("ActivityMain", "Unexpected intent URL: " + uri); | Log.e("ActivityMain", "Unexpected intent URL: " + uri); | ||||
busStopID = null; | busStopID = null; | ||||
} | } | ||||
return busStopID; | return busStopID; | ||||
} | } | ||||
public void changeStarType(String stopID) { | |||||
if (isStopInFavorites(stopID)) { | |||||
changeStarFilled(); | |||||
} else { | |||||
changeStarOutline(); | |||||
} | |||||
} | |||||
public void changeStarFilled() { | |||||
addToFavorites.setImageResource(R.drawable.ic_star_filled); | |||||
} | |||||
public void changeStarOutline() { | |||||
addToFavorites.setImageResource(R.drawable.ic_star_outline); | |||||
} | |||||
} | } | ||||
No newline at end of file | No newline at end of file |
Public contents are in Creative Commons Attribution-ShareAlike 4.0 (CC-BY-SA) or GNU Free Documentation License (at your option) unless otherwise noted. · Contact / Register