Changeset View
Changeset View
Standalone View
Standalone View
src/it/reyboz/bustorino/ActivityMain.java
/* | /* | ||||
BusTO - Arrival times for Turin public transports. | BusTO - Arrival times for Turin public transports. | ||||
Copyright (C) 2014 Valerio Bozzolan | Copyright (C) 2014 Valerio Bozzolan | ||||
This program is free software: you can redistribute it and/or modify | 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 | it under the terms of the GNU General Public License as published by | ||||
the Free Software Foundation, either version 3 of the License, or | the Free Software Foundation, either version 3 of the License, or | ||||
(at your option) any later version. | (at your option) any later version. | ||||
This program is distributed in the hope that it will be useful, | This program is distributed in the hope that it will be useful, | ||||
but WITHOUT ANY WARRANTY; without even the implied warranty of | but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||||
GNU General Public License for more details. | GNU General Public License for more details. | ||||
You should have received a copy of the GNU General Public License | You should have received a copy of the GNU General Public License | ||||
along with this program. If not, see <http://www.gnu.org/licenses/>. | along with this program. If not, see <http://www.gnu.org/licenses/>. | ||||
*/ | */ | ||||
package it.reyboz.bustorino; | package it.reyboz.bustorino; | ||||
import android.annotation.SuppressLint; | import android.annotation.SuppressLint; | ||||
import android.content.Context; | import android.content.Context; | ||||
import android.content.Intent; | import android.content.Intent; | ||||
import android.content.pm.PackageManager; | import android.content.pm.PackageManager; | ||||
import android.database.sqlite.SQLiteDatabase; | import android.database.sqlite.SQLiteDatabase; | ||||
import android.location.*; | import android.location.*; | ||||
import android.net.Uri; | import android.net.Uri; | ||||
import android.os.Build; | import android.os.Build; | ||||
import android.os.Bundle; | import android.os.Bundle; | ||||
import android.os.Handler; | import android.os.Handler; | ||||
import android.support.annotation.NonNull; | import android.support.annotation.NonNull; | ||||
import android.support.design.widget.Snackbar; | import android.support.design.widget.Snackbar; | ||||
import android.support.v4.app.Fragment; | import android.support.v4.app.Fragment; | ||||
import android.support.v4.app.FragmentManager; | import android.support.v4.app.FragmentManager; | ||||
import android.support.v4.app.FragmentTransaction; | import android.support.v4.app.FragmentTransaction; | ||||
import android.support.v4.app.NavUtils; | import android.support.v4.app.NavUtils; | ||||
import android.support.v4.widget.SwipeRefreshLayout; | import android.support.v4.widget.SwipeRefreshLayout; | ||||
import android.util.Log; | import android.util.Log; | ||||
import android.view.KeyEvent; | import android.view.KeyEvent; | ||||
import android.view.Menu; | import android.view.Menu; | ||||
import android.view.MenuItem; | import android.view.MenuItem; | ||||
import android.view.View; | import android.view.View; | ||||
import android.view.inputmethod.EditorInfo; | import android.view.inputmethod.EditorInfo; | ||||
import android.view.inputmethod.InputMethodManager; | import android.view.inputmethod.InputMethodManager; | ||||
import android.widget.*; | import android.widget.*; | ||||
import com.google.zxing.integration.android.IntentIntegrator; | import com.google.zxing.integration.android.IntentIntegrator; | ||||
import com.google.zxing.integration.android.IntentResult; | import com.google.zxing.integration.android.IntentResult; | ||||
import android.support.design.widget.FloatingActionButton; | import android.support.design.widget.FloatingActionButton; | ||||
import it.reyboz.bustorino.backend.*; | import it.reyboz.bustorino.backend.*; | ||||
import it.reyboz.bustorino.fragments.*; | import it.reyboz.bustorino.fragments.*; | ||||
import it.reyboz.bustorino.middleware.*; | import it.reyboz.bustorino.middleware.*; | ||||
import java.util.List; | import java.util.List; | ||||
public class ActivityMain extends GeneralActivity implements FragmentListener { | public class ActivityMain extends GeneralActivity implements FragmentListener { | ||||
/* | /* | ||||
* Layout elements | * Layout elements | ||||
*/ | */ | ||||
private EditText busStopSearchByIDEditText; | private EditText busStopSearchByIDEditText; | ||||
private EditText busStopSearchByNameEditText; | private EditText busStopSearchByNameEditText; | ||||
private ProgressBar progressBar; | private ProgressBar progressBar; | ||||
private TextView howDoesItWorkTextView; | private TextView howDoesItWorkTextView; | ||||
private Button hideHintButton; | private Button hideHintButton; | ||||
private MenuItem actionHelpMenuItem; | private MenuItem actionHelpMenuItem; | ||||
private SwipeRefreshLayout swipeRefreshLayout; | private SwipeRefreshLayout swipeRefreshLayout; | ||||
private FloatingActionButton floatingActionButton; | private FloatingActionButton floatingActionButton; | ||||
private FragmentManager framan; | private FragmentManager framan; | ||||
private Snackbar snackbar; | private Snackbar snackbar; | ||||
/* | /* | ||||
* 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 LOCATION_PERMISSION_GIVEN = "loc_permission"; | private final String OPTION_SHOW_LEGEND = "show_legend"; | ||||
/* | private final String LOCATION_PERMISSION_GIVEN = "loc_permission"; | ||||
* Status | /* | ||||
*/ | * Status | ||||
private DBStatusManager prefsManager; | */ | ||||
private DBStatusManager.OnDBUpdateStatusChangeListener updatelistener; | private DBStatusManager prefsManager; | ||||
private static final String DEBUG_TAG="BusTO - MainActivity"; | private DBStatusManager.OnDBUpdateStatusChangeListener updatelistener; | ||||
/* // useful for testing: | private static final String DEBUG_TAG="BusTO - MainActivity"; | ||||
public class MockFetcher implements ArrivalsFetcher { | /* // useful for testing: | ||||
@Override | public class MockFetcher implements ArrivalsFetcher { | ||||
public Palina ReadArrivalTimesAll(String routeID, AtomicReference<result> res) { | @Override | ||||
SystemClock.sleep(5000); | public Palina ReadArrivalTimesAll(String routeID, AtomicReference<result> res) { | ||||
res.set(result.SERVER_ERROR); | SystemClock.sleep(5000); | ||||
return new Palina(); | res.set(result.SERVER_ERROR); | ||||
} | 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<StopsFinderByName> StopsFindersByNameRecursionHelper = new RecursionHelper<>(new StopsFinderByName[] {new GTTStopsFetcher(), new FiveTStopsFetcher()}); | private RecursionHelper<ArrivalsFetcher> ArrivalFetchersRecursionHelper = new RecursionHelper<>(new ArrivalsFetcher[] {new GTTJSONFetcher(), new FiveTScraperFetcher()}); | ||||
/* | private RecursionHelper<StopsFinderByName> StopsFindersByNameRecursionHelper = new RecursionHelper<>(new StopsFinderByName[] {new GTTStopsFetcher(), new FiveTStopsFetcher()}); | ||||
* Position | /* | ||||
*/ | * Position | ||||
//Fine location criteria | */ | ||||
private final Criteria cr = new Criteria(); | //Fine location criteria | ||||
private boolean pendingNearbyStopsRequest = false; | private final Criteria cr = new Criteria(); | ||||
private LocationManager locmgr; | private boolean pendingNearbyStopsRequest = false; | ||||
/* | private LocationManager locmgr; | ||||
* Database Access | /* | ||||
*/ | * Database Access | ||||
private StopsDB stopsDB; | */ | ||||
private UserDB userDB; | private StopsDB stopsDB; | ||||
private FragmentHelper fh; | private UserDB userDB; | ||||
private FragmentHelper fh; | |||||
///////////////////////////////// EVENT HANDLERS /////////////////////////////////////////////// | |||||
///////////////////////////////// EVENT HANDLERS /////////////////////////////////////////////// | |||||
/* | |||||
* @see swipeRefreshLayout | /* | ||||
*/ | * @see swipeRefreshLayout | ||||
private Handler handler = new Handler(); | */ | ||||
private final Runnable refreshing = new Runnable() { | private Handler handler = new Handler(); | ||||
public void run() { | private final Runnable refreshing = new Runnable() { | ||||
if(framan.findFragmentById(R.id.resultFrame) instanceof ArrivalsFragment){ | public void run() { | ||||
ArrivalsFragment fragment = (ArrivalsFragment) framan.findFragmentById(R.id.resultFrame); | if(framan.findFragmentById(R.id.resultFrame) instanceof ArrivalsFragment){ | ||||
String stopName = fragment.getStopID(); | ArrivalsFragment fragment = (ArrivalsFragment) framan.findFragmentById(R.id.resultFrame); | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(stopName); | String stopName = fragment.getStopID(); | ||||
} else | new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(stopName); | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(); | } else | ||||
} | new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(); | ||||
}; | } | ||||
}; | |||||
//// MAIN METHOD /// | |||||
//// MAIN METHOD /// | |||||
@Override | |||||
protected void onCreate(Bundle savedInstanceState) { | @Override | ||||
super.onCreate(savedInstanceState); | protected void onCreate(Bundle savedInstanceState) { | ||||
framan = getSupportFragmentManager(); | super.onCreate(savedInstanceState); | ||||
this.stopsDB = new StopsDB(getApplicationContext()); | framan = getSupportFragmentManager(); | ||||
this.userDB = new UserDB(getApplicationContext()); | this.stopsDB = new StopsDB(getApplicationContext()); | ||||
setContentView(R.layout.activity_main); | this.userDB = new UserDB(getApplicationContext()); | ||||
busStopSearchByIDEditText = (EditText) findViewById(R.id.busStopSearchByIDEditText); | setContentView(R.layout.activity_main); | ||||
busStopSearchByNameEditText = (EditText) findViewById(R.id.busStopSearchByNameEditText); | busStopSearchByIDEditText = (EditText) findViewById(R.id.busStopSearchByIDEditText); | ||||
progressBar = (ProgressBar) findViewById(R.id.progressBar); | busStopSearchByNameEditText = (EditText) findViewById(R.id.busStopSearchByNameEditText); | ||||
howDoesItWorkTextView = (TextView) findViewById(R.id.howDoesItWorkTextView); | progressBar = (ProgressBar) findViewById(R.id.progressBar); | ||||
hideHintButton = (Button) findViewById(R.id.hideHintButton); | howDoesItWorkTextView = (TextView) findViewById(R.id.howDoesItWorkTextView); | ||||
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.listRefreshLayout); | hideHintButton = (Button) findViewById(R.id.hideHintButton); | ||||
floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton); | swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.listRefreshLayout); | ||||
floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton); | |||||
framan.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { | |||||
@Override | framan.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { | ||||
public void onBackStackChanged() { | @Override | ||||
Log.d("MainActivity, BusTO", "BACK STACK CHANGED"); | public void onBackStackChanged() { | ||||
} | Log.d("MainActivity, BusTO", "BACK STACK CHANGED"); | ||||
}); | } | ||||
}); | |||||
busStopSearchByIDEditText.setSelectAllOnFocus(true); | |||||
busStopSearchByIDEditText | busStopSearchByIDEditText.setSelectAllOnFocus(true); | ||||
.setOnEditorActionListener(new TextView.OnEditorActionListener() { | busStopSearchByIDEditText | ||||
@Override | .setOnEditorActionListener(new TextView.OnEditorActionListener() { | ||||
public boolean onEditorAction(TextView v, int actionId, | @Override | ||||
KeyEvent event) { | public boolean onEditorAction(TextView v, int actionId, | ||||
// IME_ACTION_SEARCH alphabetical option | KeyEvent event) { | ||||
if (actionId == EditorInfo.IME_ACTION_SEARCH) { | // IME_ACTION_SEARCH alphabetical option | ||||
onSearchClick(v); | if (actionId == EditorInfo.IME_ACTION_SEARCH) { | ||||
return true; | onSearchClick(v); | ||||
} | return true; | ||||
return false; | } | ||||
} | return false; | ||||
}); | } | ||||
busStopSearchByNameEditText | }); | ||||
.setOnEditorActionListener(new TextView.OnEditorActionListener() { | busStopSearchByNameEditText | ||||
@Override | .setOnEditorActionListener(new TextView.OnEditorActionListener() { | ||||
public boolean onEditorAction(TextView v, int actionId, | @Override | ||||
KeyEvent event) { | public boolean onEditorAction(TextView v, int actionId, | ||||
// IME_ACTION_SEARCH alphabetical option | KeyEvent event) { | ||||
if (actionId == EditorInfo.IME_ACTION_SEARCH) { | // IME_ACTION_SEARCH alphabetical option | ||||
onSearchClick(v); | if (actionId == EditorInfo.IME_ACTION_SEARCH) { | ||||
return true; | onSearchClick(v); | ||||
} | return true; | ||||
return false; | } | ||||
} | return false; | ||||
}); | } | ||||
}); | |||||
// Called when the layout is pulled down | |||||
swipeRefreshLayout | // Called when the layout is pulled down | ||||
.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { | swipeRefreshLayout | ||||
@Override | .setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { | ||||
public void onRefresh() { | @Override | ||||
handler.post(refreshing); | public void onRefresh() { | ||||
} | 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.setColorSchemeResources(R.color.blue_500,R.color.orange_500); | //swipeRefreshLayout.setColorSchemeColors(R.color.blue_500, R.color.orange_500); // setColorScheme is deprecated, setColorSchemeColors isn't | ||||
fh = new FragmentHelper(this,R.id.listRefreshLayout,R.id.resultFrame); | swipeRefreshLayout.setColorSchemeResources(R.color.blue_500,R.color.orange_500); | ||||
setSearchModeBusStopID(); | fh = new FragmentHelper(this,R.id.listRefreshLayout,R.id.resultFrame); | ||||
setSearchModeBusStopID(); | |||||
//---------------------------- START INTENT CHECK QUEUE ------------------------------------ | |||||
//---------------------------- START INTENT CHECK QUEUE ------------------------------------ | |||||
// Intercept calls from URL intent | |||||
boolean tryedFromIntent = false; | // Intercept calls from URL intent | ||||
boolean tryedFromIntent = false; | |||||
String busStopID = null; | |||||
String busStopDisplayName = null; | String busStopID = null; | ||||
Uri data = getIntent().getData(); | String busStopDisplayName = null; | ||||
if (data != null) { | Uri data = getIntent().getData(); | ||||
busStopID = getBusStopIDFromUri(data); | if (data != null) { | ||||
tryedFromIntent = true; | busStopID = getBusStopIDFromUri(data); | ||||
} | tryedFromIntent = true; | ||||
} | |||||
// Intercept calls from other activities | |||||
if (!tryedFromIntent) { | // Intercept calls from other activities | ||||
Bundle b = getIntent().getExtras(); | if (!tryedFromIntent) { | ||||
if (b != null) { | Bundle b = getIntent().getExtras(); | ||||
busStopID = b.getString("bus-stop-ID"); | if (b != null) { | ||||
busStopDisplayName = b.getString("bus-stop-display-name"); | busStopID = b.getString("bus-stop-ID"); | ||||
busStopDisplayName = b.getString("bus-stop-display-name"); | |||||
/** | |||||
* I'm not very sure if you are coming from an Intent. | /** | ||||
* Some launchers work in strange ways. | * I'm not very sure if you are coming from an Intent. | ||||
*/ | * Some launchers work in strange ways. | ||||
tryedFromIntent = busStopID != null; | */ | ||||
} | tryedFromIntent = busStopID != null; | ||||
} | } | ||||
} | |||||
//---------------------------- END INTENT CHECK QUEUE -------------------------------------- | |||||
//---------------------------- END INTENT CHECK QUEUE -------------------------------------- | |||||
if (busStopID == null) { | |||||
// Show keyboard if can't start from intent | if (busStopID == null) { | ||||
// JUST DON'T | // Show keyboard if can't start from intent | ||||
// showKeyboard(); | // JUST DON'T | ||||
// showKeyboard(); | |||||
// You haven't obtained anything... from an intent? | |||||
if (tryedFromIntent) { | // You haven't obtained anything... from an intent? | ||||
if (tryedFromIntent) { | |||||
// This shows a luser warning | |||||
ArrivalFetchersRecursionHelper.reset(); | // This shows a luser warning | ||||
Toast.makeText(getApplicationContext(), | ArrivalFetchersRecursionHelper.reset(); | ||||
R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show(); | Toast.makeText(getApplicationContext(), | ||||
} | R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show(); | ||||
} else { | } | ||||
// If you are here an intent has worked successfully | } else { | ||||
setBusStopSearchByIDEditText(busStopID); | // If you are here an intent has worked successfully | ||||
/* | setBusStopSearchByIDEditText(busStopID); | ||||
//THIS PART SHOULDN'T BE NECESSARY SINCE THE LAST SUCCESSFULLY SEARCHED BUS | /* | ||||
// STOP IS ADDED AUTOMATICALLY | //THIS PART SHOULDN'T BE NECESSARY SINCE THE LAST SUCCESSFULLY SEARCHED BUS | ||||
Stop nextStop = new Stop(busStopID); | // STOP IS ADDED AUTOMATICALLY | ||||
// forcing it as user name even though it could be standard name, it doesn't really matter | Stop nextStop = new Stop(busStopID); | ||||
nextStop.setStopUserName(busStopDisplayName); | // forcing it as user name even though it could be standard name, it doesn't really matter | ||||
//set stop as last succe | nextStop.setStopUserName(busStopDisplayName); | ||||
fh.setLastSuccessfullySearchedBusStop(nextStop); | //set stop as last succe | ||||
*/ | fh.setLastSuccessfullySearchedBusStop(nextStop); | ||||
createFragmentForStop(busStopID); | */ | ||||
} | createFragmentForStop(busStopID); | ||||
//Try (hopefully) database update | } | ||||
//TODO: Start the service in foreground, check last time it ran before | //Try (hopefully) database update | ||||
DatabaseUpdateService.startDBUpdate(getApplicationContext()); | //TODO: Start the service in foreground, check last time it ran before | ||||
/* | DatabaseUpdateService.startDBUpdate(getApplicationContext()); | ||||
Set database update | /* | ||||
*/ | Set database update | ||||
updatelistener = new DBStatusManager.OnDBUpdateStatusChangeListener(){ | */ | ||||
@Override | updatelistener = new DBStatusManager.OnDBUpdateStatusChangeListener(){ | ||||
public boolean defaultStatusValue() { | @Override | ||||
return true; | public boolean defaultStatusValue() { | ||||
} | return true; | ||||
} | |||||
@Override | |||||
public void onDBStatusChanged(boolean updating) { | @Override | ||||
public void onDBStatusChanged(boolean updating) { | |||||
if(updating){ | |||||
createDefaultSnackbar(); | if(updating){ | ||||
} | createDefaultSnackbar(); | ||||
else if(snackbar!=null){ | } | ||||
snackbar.dismiss(); | else if(snackbar!=null){ | ||||
snackbar = null; | snackbar.dismiss(); | ||||
} | snackbar = null; | ||||
} | |||||
} | |||||
}; | } | ||||
prefsManager = new DBStatusManager(getApplicationContext(),updatelistener); | }; | ||||
prefsManager.registerListener(); | prefsManager = new DBStatusManager(getApplicationContext(),updatelistener); | ||||
prefsManager.registerListener(); | |||||
//locationHandler = new GPSLocationAdapter(getApplicationContext()); | |||||
//--------- NEARBY STOPS--------// | //locationHandler = new GPSLocationAdapter(getApplicationContext()); | ||||
//SETUP LOCATION | //--------- NEARBY STOPS--------// | ||||
locmgr = (LocationManager) getSystemService(LOCATION_SERVICE); | //SETUP LOCATION | ||||
cr.setAccuracy(Criteria.ACCURACY_FINE); | locmgr = (LocationManager) getSystemService(LOCATION_SERVICE); | ||||
cr.setAltitudeRequired(false); | cr.setAccuracy(Criteria.ACCURACY_FINE); | ||||
cr.setBearingRequired(false); | cr.setAltitudeRequired(false); | ||||
cr.setCostAllowed(true); | cr.setBearingRequired(false); | ||||
cr.setPowerRequirement(Criteria.NO_REQUIREMENT); | cr.setCostAllowed(true); | ||||
//We want the nearby bus stops! | cr.setPowerRequirement(Criteria.NO_REQUIREMENT); | ||||
handler.post(new NearbyStopsRequester()); | //We want the nearby bus stops! | ||||
//If there are no providers available, then, wait for them | handler.post(new NearbyStopsRequester()); | ||||
//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 | /** | ||||
protected void onPostResume() { | @Override | ||||
super.onPostResume(); | protected void onPostResume() { | ||||
Log.d("ActivityMain", "onPostResume fired. Last successfully bus stop ID: " + fh.getLastSuccessfullySearchedBusStop()); | super.onPostResume(); | ||||
if (searchMode == SEARCH_BY_ID && fh.getLastSuccessfullySearchedBusStop() != null) { | Log.d("ActivityMain", "onPostResume fired. Last successfully bus stop ID: " + fh.getLastSuccessfullySearchedBusStop()); | ||||
setBusStopSearchByIDEditText(fh.getLastSuccessfullySearchedBusStop().ID); | if (searchMode == SEARCH_BY_ID && fh.getLastSuccessfullySearchedBusStop() != null) { | ||||
//new asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStop.ID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); | setBusStopSearchByIDEditText(fh.getLastSuccessfullySearchedBusStop().ID); | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(); | //new asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStop.ID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); | ||||
} else { | new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(); | ||||
//we have new activity or we don't have a new searched stop. | } else { | ||||
//Let's search stops nearby | //we have new activity or we don't have a new searched stop. | ||||
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE); | //Let's search stops nearby | ||||
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.resultFrame); | LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE); | ||||
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.resultFrame); | |||||
} | |||||
//show the FAB since it remains hidden | } | ||||
floatingActionButton.show(); | //show the FAB since it remains hidden | ||||
floatingActionButton.show(); | |||||
} | |||||
**/ | } | ||||
**/ | |||||
@Override | |||||
protected void onPause() { | @Override | ||||
super.onPause(); | protected void onPause() { | ||||
fh.stopLastRequestIfNeeded(); | super.onPause(); | ||||
fh.setBlockAllActivities(true); | fh.stopLastRequestIfNeeded(); | ||||
if(updatelistener!=null && prefsManager!=null) prefsManager.unregisterListener(); | fh.setBlockAllActivities(true); | ||||
locmgr.removeUpdates(locListener); | if(updatelistener!=null && prefsManager!=null) prefsManager.unregisterListener(); | ||||
} | locmgr.removeUpdates(locListener); | ||||
} | |||||
@Override | |||||
protected void onResume() { | @Override | ||||
super.onResume(); | protected void onResume() { | ||||
fh.setBlockAllActivities(false); | super.onResume(); | ||||
if(updatelistener!=null && prefsManager!=null) { | fh.setBlockAllActivities(false); | ||||
prefsManager.registerListener(); | if(updatelistener!=null && prefsManager!=null) { | ||||
if(prefsManager.isDBUpdating(true)){ | prefsManager.registerListener(); | ||||
createDefaultSnackbar(); | if(prefsManager.isDBUpdating(true)){ | ||||
} | createDefaultSnackbar(); | ||||
} | } | ||||
if(pendingNearbyStopsRequest) | } | ||||
handler.post(new NearbyStopsRequester()); | if(pendingNearbyStopsRequest) | ||||
} | handler.post(new NearbyStopsRequester()); | ||||
} | |||||
@Override | |||||
public boolean onCreateOptionsMenu(Menu menu) { | @Override | ||||
// Inflate the menu; this adds items to the action bar if it is present. | public boolean onCreateOptionsMenu(Menu menu) { | ||||
getMenuInflater().inflate(R.menu.main, 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; | actionHelpMenuItem = menu.findItem(R.id.action_help); | ||||
} | return true; | ||||
} | |||||
/** | |||||
* Callback fired when a MenuItem is selected | /** | ||||
* | * Callback fired when a MenuItem is selected | ||||
* @param item | * | ||||
* @return | * @param item | ||||
*/ | * @return | ||||
@Override | */ | ||||
public boolean onOptionsItemSelected(MenuItem item) { | @Override | ||||
// Handle action bar item clicks here. The action bar will | public boolean onOptionsItemSelected(MenuItem item) { | ||||
// automatically handle clicks on the Home/Up button, so long | // Handle action bar item clicks here. The action bar will | ||||
// as you specify a parent activity in AndroidManifest.xml. | // automatically handle clicks on the Home/Up button, so long | ||||
switch (item.getItemId()) { | // as you specify a parent activity in AndroidManifest.xml. | ||||
case android.R.id.home: | switch (item.getItemId()) { | ||||
// Respond to the action bar's Up/Home button | case android.R.id.home: | ||||
NavUtils.navigateUpFromSameTask(this); | // Respond to the action bar's Up/Home button | ||||
return true; | NavUtils.navigateUpFromSameTask(this); | ||||
case R.id.action_help: | return true; | ||||
showHints(); | case R.id.action_help: | ||||
return true; | showHints(); | ||||
case R.id.action_favorites: | return true; | ||||
startActivity(new Intent(ActivityMain.this, ActivityFavorites.class)); | case R.id.action_favorites: | ||||
return true; | startActivity(new Intent(ActivityMain.this, ActivityFavorites.class)); | ||||
case R.id.action_about: | return true; | ||||
startActivity(new Intent(ActivityMain.this, ActivityAbout.class)); | case R.id.action_about: | ||||
return true; | startActivity(new Intent(ActivityMain.this, ActivityAbout.class)); | ||||
case R.id.action_news: | return true; | ||||
openIceweasel("https://gitpull.it/w/librebusto/#how-to-get-news"); | case R.id.action_news: | ||||
return true; | openIceweasel("https://gitpull.it/w/librebusto/#how-to-get-news"); | ||||
case R.id.action_bugs: | return true; | ||||
openIceweasel("https://gitpull.it/w/librebusto/#how-to-create-a-bug-feature"); | case R.id.action_bugs: | ||||
return true; | openIceweasel("https://gitpull.it/w/librebusto/#how-to-create-a-bug-feature"); | ||||
case R.id.action_source: | return true; | ||||
openIceweasel("https://gitpull.it/w/librebusto/#how-to-hack-busto"); | case R.id.action_source: | ||||
return true; | openIceweasel("https://gitpull.it/w/librebusto/#how-to-hack-busto"); | ||||
case R.id.action_licence: | return true; | ||||
openIceweasel("https://www.gnu.org/licenses/gpl-3.0.html"); | case R.id.action_licence: | ||||
return true; | openIceweasel("https://www.gnu.org/licenses/gpl-3.0.html"); | ||||
case R.id.action_settings: | return true; | ||||
Log.d("MAINBusTO","Pressed button preferences"); | case R.id.action_settings: | ||||
startActivity(new Intent(ActivityMain.this,ActivitySettings.class)); | Log.d("MAINBusTO","Pressed button preferences"); | ||||
} | 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) { | */ | ||||
if (searchMode == SEARCH_BY_ID) { | public void onSearchClick(View v) { | ||||
String busStopID = busStopSearchByIDEditText.getText().toString(); | if (searchMode == SEARCH_BY_ID) { | ||||
//OLD ASYNCTASK | String busStopID = busStopSearchByIDEditText.getText().toString(); | ||||
//new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); | //OLD ASYNCTASK | ||||
//new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); | |||||
if(busStopID == null || busStopID.length() <= 0) { | |||||
showMessage(R.string.insert_bus_stop_number_error); | if(busStopID == null || busStopID.length() <= 0) { | ||||
toggleSpinner(false); | showMessage(R.string.insert_bus_stop_number_error); | ||||
} else{ | toggleSpinner(false); | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(busStopID); | } else{ | ||||
Log.d("MainActiv","Started search for arrivals of stop "+busStopID); | new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(busStopID); | ||||
} | Log.d("MainActiv","Started search for arrivals of stop "+busStopID); | ||||
} else { // searchMode == SEARCH_BY_NAME | } | ||||
String query = busStopSearchByNameEditText.getText().toString(); | } else { // searchMode == SEARCH_BY_NAME | ||||
//new asyncWgetBusStopSuggestions(query, stopsDB, StopsFindersByNameRecursionHelper); | String query = busStopSearchByNameEditText.getText().toString(); | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.STOPS,fh).execute(query); | //new asyncWgetBusStopSuggestions(query, stopsDB, StopsFindersByNameRecursionHelper); | ||||
} | new AsyncDataDownload(AsyncDataDownload.RequestType.STOPS,fh).execute(query); | ||||
} | } | ||||
/** PERMISSION STUFF **/ | } | ||||
@Override | /** PERMISSION STUFF **/ | ||||
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { | @Override | ||||
switch (requestCode){ | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { | ||||
case PERMISSION_REQUEST_POSITION: | switch (requestCode){ | ||||
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){ | case PERMISSION_REQUEST_POSITION: | ||||
setOption(LOCATION_PERMISSION_GIVEN,true); | if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){ | ||||
//if we sent a request for a new NearbyStopsFragment | setOption(LOCATION_PERMISSION_GIVEN,true); | ||||
if(pendingNearbyStopsRequest){ | //if we sent a request for a new NearbyStopsFragment | ||||
pendingNearbyStopsRequest=false; | if(pendingNearbyStopsRequest){ | ||||
handler.post(new NearbyStopsRequester()); | pendingNearbyStopsRequest=false; | ||||
} | handler.post(new NearbyStopsRequester()); | ||||
} | |||||
} else { | |||||
//permission denied | } else { | ||||
setOption(LOCATION_PERMISSION_GIVEN,false); | //permission denied | ||||
} | setOption(LOCATION_PERMISSION_GIVEN,false); | ||||
//add other cases for permissions | } | ||||
} | //add other cases for permissions | ||||
} | |||||
} | |||||
} | |||||
@Override | |||||
public void createFragmentForStop(String ID) { | @Override | ||||
//new asyncWgetBusStopFromBusStopID(ID, ArrivalFetchersRecursionHelper,lastSuccessfullySearchedBusStop); | public void createFragmentForStop(String ID) { | ||||
if(ID == null || ID.length() <= 0) { | //new asyncWgetBusStopFromBusStopID(ID, ArrivalFetchersRecursionHelper,lastSuccessfullySearchedBusStop); | ||||
// we're still in UI thread, no need to mess with Progress | if(ID == null || ID.length() <= 0) { | ||||
showMessage(R.string.insert_bus_stop_number_error); | // we're still in UI thread, no need to mess with Progress | ||||
toggleSpinner(false); | showMessage(R.string.insert_bus_stop_number_error); | ||||
} else { | toggleSpinner(false); | ||||
new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(ID); | } else { | ||||
Log.d("MainActiv","Started search for arrivals of stop "+ID); | new AsyncDataDownload(AsyncDataDownload.RequestType.ARRIVALS,fh).execute(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) { | */ | ||||
IntentIntegrator integrator = new IntentIntegrator(this); | public void onQRButtonClick(View v) { | ||||
integrator.initiateScan(); | IntentIntegrator integrator = new IntentIntegrator(this); | ||||
} | integrator.initiateScan(); | ||||
} | |||||
/** | |||||
* Receive the Barcode Scanner Intent | /** | ||||
* | * Receive the Barcode Scanner Intent | ||||
*/ | * | ||||
public void onActivityResult(int requestCode, int resultCode, Intent intent) { | */ | ||||
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); | public void onActivityResult(int requestCode, int resultCode, Intent intent) { | ||||
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); | |||||
Uri uri; | |||||
try { | Uri uri; | ||||
uri = Uri.parse(scanResult != null ? scanResult.getContents() : null); // this apparently prevents NullPointerException. Somehow. | try { | ||||
} catch (NullPointerException e) { | uri = Uri.parse(scanResult != null ? scanResult.getContents() : null); // this apparently prevents NullPointerException. Somehow. | ||||
Toast.makeText(getApplicationContext(), | } catch (NullPointerException e) { | ||||
R.string.no_qrcode, Toast.LENGTH_SHORT).show(); | Toast.makeText(getApplicationContext(), | ||||
return; | R.string.no_qrcode, Toast.LENGTH_SHORT).show(); | ||||
} | return; | ||||
} | |||||
String busStopID = getBusStopIDFromUri(uri); | |||||
busStopSearchByIDEditText.setText(busStopID); | String busStopID = getBusStopIDFromUri(uri); | ||||
createFragmentForStop(busStopID); | busStopSearchByIDEditText.setText(busStopID); | ||||
} | createFragmentForStop(busStopID); | ||||
} | |||||
public void onHideHint(View v) { | |||||
hideHints(); | public void onHideHint(View v) { | ||||
setOption(OPTION_SHOW_LEGEND, false); | hideHints(); | ||||
} | setOption(OPTION_SHOW_LEGEND, false); | ||||
} | |||||
public void onToggleKeyboardLayout(View v) { | |||||
if (searchMode == SEARCH_BY_NAME) { | public void onToggleKeyboardLayout(View v) { | ||||
setSearchModeBusStopID(); | if (searchMode == SEARCH_BY_NAME) { | ||||
if (busStopSearchByIDEditText.requestFocus()) { | setSearchModeBusStopID(); | ||||
showKeyboard(); | if (busStopSearchByIDEditText.requestFocus()) { | ||||
} | showKeyboard(); | ||||
} else { // searchMode == SEARCH_BY_ID | } | ||||
setSearchModeBusStopName(); | } else { // searchMode == SEARCH_BY_ID | ||||
if (busStopSearchByNameEditText.requestFocus()) { | setSearchModeBusStopName(); | ||||
showKeyboard(); | if (busStopSearchByNameEditText.requestFocus()) { | ||||
} | showKeyboard(); | ||||
} | } | ||||
} | } | ||||
private void createDefaultSnackbar(){ | } | ||||
if(snackbar==null){ | private void createDefaultSnackbar(){ | ||||
snackbar = Snackbar.make(findViewById(R.id.searchButton),R.string.database_update_message,Snackbar.LENGTH_INDEFINITE); | if(snackbar==null){ | ||||
} | 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){ | |||||
Log.d(DEBUG_TAG,"Provider "+provider+" got enabled"); | private void resolveStopRequest(String provider){ | ||||
if(locmgr!=null && pendingNearbyStopsRequest && locmgr.getProvider(provider).meetsCriteria(cr)){ | Log.d(DEBUG_TAG,"Provider "+provider+" got enabled"); | ||||
pendingNearbyStopsRequest = false; | if(locmgr!=null && pendingNearbyStopsRequest && locmgr.getProvider(provider).meetsCriteria(cr)){ | ||||
handler.post(new NearbyStopsRequester()); | pendingNearbyStopsRequest = false; | ||||
} | handler.post(new NearbyStopsRequester()); | ||||
} | } | ||||
final LocationListener locListener = new LocationListener() { | } | ||||
@Override | final LocationListener locListener = new LocationListener() { | ||||
public void onLocationChanged(Location location) { | @Override | ||||
Log.d(DEBUG_TAG,"Location changed"); | public void onLocationChanged(Location location) { | ||||
} | Log.d(DEBUG_TAG,"Location changed"); | ||||
} | |||||
@Override | |||||
public void onStatusChanged(String provider, int status, Bundle extras) { | @Override | ||||
Log.d(DEBUG_TAG,"Location provider status: "+status); | public void onStatusChanged(String provider, int status, Bundle extras) { | ||||
if(status== LocationProvider.AVAILABLE){ | Log.d(DEBUG_TAG,"Location provider status: "+status); | ||||
resolveStopRequest(provider); | if(status== LocationProvider.AVAILABLE){ | ||||
} | resolveStopRequest(provider); | ||||
} | } | ||||
} | |||||
@Override | |||||
public void onProviderEnabled(String provider) { | @Override | ||||
resolveStopRequest(provider); | public void onProviderEnabled(String provider) { | ||||
} | resolveStopRequest(provider); | ||||
} | |||||
@Override | |||||
public void onProviderDisabled(String provider) { | @Override | ||||
public void onProviderDisabled(String provider) { | |||||
} | |||||
}; | } | ||||
}; | |||||
class NearbyStopsRequester implements Runnable{ | |||||
@SuppressLint("MissingPermission") | class NearbyStopsRequester implements Runnable{ | ||||
@Override | @SuppressLint("MissingPermission") | ||||
public void run() { | @Override | ||||
final boolean canRunPosition = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || getOption(LOCATION_PERMISSION_GIVEN, false); | public void run() { | ||||
final boolean canRunPosition = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || getOption(LOCATION_PERMISSION_GIVEN, false); | |||||
if(!canRunPosition){ | |||||
pendingNearbyStopsRequest = true; | if(!canRunPosition){ | ||||
assertLocationPermissions(); | pendingNearbyStopsRequest = true; | ||||
return; | assertLocationPermissions(); | ||||
} else setOption(LOCATION_PERMISSION_GIVEN,true); | return; | ||||
} else setOption(LOCATION_PERMISSION_GIVEN,true); | |||||
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE); | |||||
if(locManager == null) { | LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE); | ||||
Log.e(DEBUG_TAG, "location manager is nihil, cannot create NearbyStopsFragment"); | if(locManager == null) { | ||||
return; | Log.e(DEBUG_TAG, "location manager is nihil, cannot create NearbyStopsFragment"); | ||||
} | return; | ||||
if(anyLocationProviderMatchesCriteria(locManager,cr,true) && fh.getLastSuccessfullySearchedBusStop()==null) { | } | ||||
//Go ahead with the request | if(anyLocationProviderMatchesCriteria(locManager,cr,true) && fh.getLastSuccessfullySearchedBusStop()==null) { | ||||
Log.d("mainActivity","Recreating stop fragment"); | //Go ahead with the request | ||||
swipeRefreshLayout.setVisibility(View.VISIBLE); | Log.d("mainActivity","Recreating stop fragment"); | ||||
NearbyStopsFragment fragment = NearbyStopsFragment.newInstance(NearbyStopsFragment.TYPE_STOPS); | swipeRefreshLayout.setVisibility(View.VISIBLE); | ||||
Fragment oldFrag = framan.findFragmentById(R.id.resultFrame); | NearbyStopsFragment fragment = NearbyStopsFragment.newInstance(NearbyStopsFragment.TYPE_STOPS); | ||||
FragmentTransaction ft = framan.beginTransaction(); | Fragment oldFrag = framan.findFragmentById(R.id.resultFrame); | ||||
if(oldFrag!=null) | FragmentTransaction ft = framan.beginTransaction(); | ||||
ft.remove(oldFrag); | if(oldFrag!=null) | ||||
ft.add(R.id.resultFrame,fragment,"nearbyStop_correct"); | ft.remove(oldFrag); | ||||
ft.commit(); | ft.add(R.id.resultFrame,fragment,"nearbyStop_correct"); | ||||
framan.executePendingTransactions(); | ft.commit(); | ||||
pendingNearbyStopsRequest = false; | framan.executePendingTransactions(); | ||||
} else if(!anyLocationProviderMatchesCriteria(locManager,cr,true)){ | pendingNearbyStopsRequest = false; | ||||
//Wait for the providers | } else if(!anyLocationProviderMatchesCriteria(locManager,cr,true)){ | ||||
Log.d(DEBUG_TAG,"Queuing position request"); | //Wait for the providers | ||||
pendingNearbyStopsRequest = true; | Log.d(DEBUG_TAG,"Queuing position request"); | ||||
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10,0.1f,locListener); | pendingNearbyStopsRequest = true; | ||||
} | locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10,0.1f,locListener); | ||||
} | |||||
} | |||||
} | } | ||||
} | |||||
private boolean anyLocationProviderMatchesCriteria(LocationManager mng, Criteria cr, boolean enabled){ | |||||
List<String> providers = mng.getProviders(cr,enabled); | private boolean anyLocationProviderMatchesCriteria(LocationManager mng, Criteria cr, boolean enabled){ | ||||
Log.d(DEBUG_TAG,"Getting enabled location providers: "); | List<String> providers = mng.getProviders(cr,enabled); | ||||
for(String s: providers){ | Log.d(DEBUG_TAG,"Getting enabled location providers: "); | ||||
Log.d(DEBUG_TAG,"Provider "+s); | for(String s: providers){ | ||||
} | 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 | */ | ||||
public Stop getLastSuccessfullySearchedBusStop() { | @Override | ||||
return fh.getLastSuccessfullySearchedBusStop(); | public Stop getLastSuccessfullySearchedBusStop() { | ||||
} | return fh.getLastSuccessfullySearchedBusStop(); | ||||
} | |||||
/** | |||||
* Get the last successfully searched bus stop ID or NULL | /** | ||||
* | * Get the last successfully searched bus stop ID or NULL | ||||
* @return | * | ||||
*/ | * @return | ||||
@Override | */ | ||||
public String getLastSuccessfullySearchedBusStopID() { | @Override | ||||
Stop stop = getLastSuccessfullySearchedBusStop(); | public String getLastSuccessfullySearchedBusStopID() { | ||||
return stop == null ? null : stop.ID; | Stop stop = getLastSuccessfullySearchedBusStop(); | ||||
} | return stop == null ? null : stop.ID; | ||||
} | |||||
/** | |||||
* Update the star "Add to favorite" icon | /** | ||||
*/ | * Update the star "Add to favorite" icon | ||||
@Override | */ | ||||
public void updateStarIconFromLastBusStop() { | @Override | ||||
// check if there is a last Stop | public void updateStarIconFromLastBusStop() { | ||||
String stopID = getLastSuccessfullySearchedBusStopID(); | |||||
if(stopID == null) { | // no favorites no party! | ||||
// TODO: hide the star | addToFavorites = (ImageButton) findViewById(R.id.addToFavorites); | ||||
} else { | if (addToFavorites == null) { | ||||
// filled or outline? | Log.d("MainActivity", "Why the fuck the star is not here?!"); | ||||
if(isStopInFavorites(stopID)) { | return; | ||||
// TODO: fill star | } | ||||
} else { | |||||
// TODO: outline star | // check if there is a last Stop | ||||
} | String stopID = getLastSuccessfullySearchedBusStopID(); | ||||
if(stopID == null) { | |||||
// TODO: show the star | addToFavorites.setVisibility(View.INVISIBLE); | ||||
} | } else { | ||||
} | // filled or outline? | ||||
if(isStopInFavorites(stopID)) { | |||||
/** | addToFavorites.setImageResource(R.drawable.ic_star_filled); | ||||
* Check if the last Bus Stop is in the favorites | } else { | ||||
* | addToFavorites.setImageResource(R.drawable.ic_star_outline); | ||||
* @return | } | ||||
*/ | |||||
public boolean isStopInFavorites(String busStopId) { | addToFavorites.setVisibility(View.VISIBLE); | ||||
boolean found = false; | } | ||||
} | |||||
// no stop no party | |||||
if(busStopId != null) { | /** | ||||
SQLiteDatabase userDB = new UserDB(getApplicationContext()).getReadableDatabase(); | * Check if the last Bus Stop is in the favorites | ||||
found = UserDB.isStopInFavorites(userDB, busStopId); | * | ||||
} | * @return | ||||
*/ | |||||
return found; | public boolean isStopInFavorites(String busStopId) { | ||||
} | boolean found = false; | ||||
/** | // no stop no party | ||||
* Add the last Stop to favorites | if(busStopId != null) { | ||||
*/ | SQLiteDatabase userDB = new UserDB(getApplicationContext()).getReadableDatabase(); | ||||
@Override | found = UserDB.isStopInFavorites(userDB, busStopId); | ||||
public void toggleLastStopToFavorites() { | } | ||||
Stop stop = getLastSuccessfullySearchedBusStop(); | |||||
if(stop != null) { | return found; | ||||
} | |||||
// toggle the status in background | |||||
new AsyncStopFavoriteAction(getApplicationContext(), AsyncStopFavoriteAction.Action.TOGGLE) { | /** | ||||
* Add the last Stop to favorites | |||||
/** | */ | ||||
* Callback fired when the Stop is saved in the favorites | @Override | ||||
* @param result | public void toggleLastStopToFavorites() { | ||||
*/ | Stop stop = getLastSuccessfullySearchedBusStop(); | ||||
@Override | if(stop != null) { | ||||
protected void onPostExecute(Boolean result) { | |||||
super.onPostExecute(result); | // toggle the status in background | ||||
new AsyncStopFavoriteAction(getApplicationContext(), AsyncStopFavoriteAction.Action.TOGGLE) { | |||||
// update the star icon | |||||
updateStarIconFromLastBusStop(); | /** | ||||
} | * Callback fired when the Stop is saved in the favorites | ||||
* @param result | |||||
}.execute(stop); | */ | ||||
} else { | @Override | ||||
// this case have no sense, but just immediately update the favorite icon | protected void onPostExecute(Boolean result) { | ||||
updateStarIconFromLastBusStop(); | super.onPostExecute(result); | ||||
} | |||||
} | |||||
// update the star icon | |||||
@Override | updateStarIconFromLastBusStop(); | ||||
public void showFloatingActionButton(boolean yes) { | } | ||||
if(yes) floatingActionButton.show(); | |||||
else floatingActionButton.hide(); | }.execute(stop); | ||||
} | } else { | ||||
// this case have no sense, but just immediately update the favorite icon | |||||
@Override | updateStarIconFromLastBusStop(); | ||||
public void enableRefreshLayout(boolean yes) { | } | ||||
swipeRefreshLayout.setEnabled(yes); | } | ||||
} | |||||
@Override | |||||
////////////////////////////////////// GUI HELPERS ///////////////////////////////////////////// | public void showFloatingActionButton(boolean yes) { | ||||
@Override | if(yes) floatingActionButton.show(); | ||||
public void showKeyboard() { | else floatingActionButton.hide(); | ||||
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); | } | ||||
View view = searchMode == SEARCH_BY_ID ? busStopSearchByIDEditText : busStopSearchByNameEditText; | |||||
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); | @Override | ||||
} | public void enableRefreshLayout(boolean yes) { | ||||
swipeRefreshLayout.setEnabled(yes); | |||||
@Override | } | ||||
public void showMessage(int messageID) { | |||||
Toast.makeText(getApplicationContext(), messageID, Toast.LENGTH_SHORT).show(); | ////////////////////////////////////// GUI HELPERS ///////////////////////////////////////////// | ||||
} | @Override | ||||
public void showKeyboard() { | |||||
private void setSearchModeBusStopID() { | InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); | ||||
searchMode = SEARCH_BY_ID; | View view = searchMode == SEARCH_BY_ID ? busStopSearchByIDEditText : busStopSearchByNameEditText; | ||||
busStopSearchByNameEditText.setVisibility(View.GONE); | imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); | ||||
busStopSearchByNameEditText.setText(""); | } | ||||
busStopSearchByIDEditText.setVisibility(View.VISIBLE); | |||||
floatingActionButton.setImageResource(R.drawable.alphabetical); | @Override | ||||
} | public void showMessage(int messageID) { | ||||
Toast.makeText(getApplicationContext(), messageID, Toast.LENGTH_SHORT).show(); | |||||
private void setSearchModeBusStopName() { | } | ||||
searchMode = SEARCH_BY_NAME; | |||||
busStopSearchByIDEditText.setVisibility(View.GONE); | private void setSearchModeBusStopID() { | ||||
busStopSearchByIDEditText.setText(""); | searchMode = SEARCH_BY_ID; | ||||
busStopSearchByNameEditText.setVisibility(View.VISIBLE); | busStopSearchByNameEditText.setVisibility(View.GONE); | ||||
floatingActionButton.setImageResource(R.drawable.numeric); | busStopSearchByNameEditText.setText(""); | ||||
} | busStopSearchByIDEditText.setVisibility(View.VISIBLE); | ||||
floatingActionButton.setImageResource(R.drawable.alphabetical); | |||||
/** | } | ||||
* Having that cursor at the left of the edit text makes me cancer. | |||||
* @param busStopID bus stop ID | private void setSearchModeBusStopName() { | ||||
*/ | searchMode = SEARCH_BY_NAME; | ||||
private void setBusStopSearchByIDEditText(String busStopID) { | busStopSearchByIDEditText.setVisibility(View.GONE); | ||||
busStopSearchByIDEditText.setText(busStopID); | busStopSearchByIDEditText.setText(""); | ||||
busStopSearchByIDEditText.setSelection(busStopID.length()); | busStopSearchByNameEditText.setVisibility(View.VISIBLE); | ||||
} | floatingActionButton.setImageResource(R.drawable.numeric); | ||||
} | |||||
private void showHints() { | |||||
howDoesItWorkTextView.setVisibility(View.VISIBLE); | /** | ||||
hideHintButton.setVisibility(View.VISIBLE); | * Having that cursor at the left of the edit text makes me cancer. | ||||
actionHelpMenuItem.setVisible(false); | * @param busStopID bus stop ID | ||||
} | */ | ||||
private void setBusStopSearchByIDEditText(String busStopID) { | |||||
private void hideHints() { | busStopSearchByIDEditText.setText(busStopID); | ||||
howDoesItWorkTextView.setVisibility(View.GONE); | busStopSearchByIDEditText.setSelection(busStopID.length()); | ||||
hideHintButton.setVisibility(View.GONE); | } | ||||
actionHelpMenuItem.setVisible(true); | |||||
} | private void showHints() { | ||||
howDoesItWorkTextView.setVisibility(View.VISIBLE); | |||||
//TODO: toggle spinner from mainActivity | hideHintButton.setVisibility(View.VISIBLE); | ||||
@Override | actionHelpMenuItem.setVisible(false); | ||||
public void toggleSpinner(boolean enable) { | } | ||||
if (enable) { | |||||
//already set by the RefreshListener when needed | private void hideHints() { | ||||
//swipeRefreshLayout.setRefreshing(true); | howDoesItWorkTextView.setVisibility(View.GONE); | ||||
progressBar.setVisibility(View.VISIBLE); | hideHintButton.setVisibility(View.GONE); | ||||
} else { | actionHelpMenuItem.setVisible(true); | ||||
swipeRefreshLayout.setRefreshing(false); | } | ||||
progressBar.setVisibility(View.GONE); | |||||
} | //TODO: toggle spinner from mainActivity | ||||
} | @Override | ||||
public void toggleSpinner(boolean enable) { | |||||
private void prepareGUIForBusLines() { | if (enable) { | ||||
swipeRefreshLayout.setEnabled(true); | //already set by the RefreshListener when needed | ||||
swipeRefreshLayout.setVisibility(View.VISIBLE); | //swipeRefreshLayout.setRefreshing(true); | ||||
actionHelpMenuItem.setVisible(true); | progressBar.setVisibility(View.VISIBLE); | ||||
} | } else { | ||||
swipeRefreshLayout.setRefreshing(false); | |||||
private void prepareGUIForBusStops() { | progressBar.setVisibility(View.GONE); | ||||
swipeRefreshLayout.setEnabled(false); | } | ||||
swipeRefreshLayout.setVisibility(View.VISIBLE); | } | ||||
actionHelpMenuItem.setVisible(false); | |||||
} | private void prepareGUIForBusLines() { | ||||
swipeRefreshLayout.setEnabled(true); | |||||
swipeRefreshLayout.setVisibility(View.VISIBLE); | |||||
/** | actionHelpMenuItem.setVisible(true); | ||||
* This provides a temporary fix to make the transition | } | ||||
* to a single asynctask go smoother | |||||
* @param fragmentType the type of fragment created | private void prepareGUIForBusStops() { | ||||
*/ | swipeRefreshLayout.setEnabled(false); | ||||
@Override | swipeRefreshLayout.setVisibility(View.VISIBLE); | ||||
public void readyGUIfor(FragmentKind fragmentType) { | actionHelpMenuItem.setVisible(false); | ||||
hideKeyboard(); | } | ||||
//if we are getting results, already, stop waiting for nearbyStops | |||||
if(pendingNearbyStopsRequest && (fragmentType==FragmentKind.ARRIVALS || fragmentType==FragmentKind.STOPS)) { | |||||
locmgr.removeUpdates(locListener); | /** | ||||
pendingNearbyStopsRequest = false; | * This provides a temporary fix to make the transition | ||||
} | * to a single asynctask go smoother | ||||
if(fragmentType==null) Log.e("ActivityMain","Problem with fragmentType"); | * @param fragmentType the type of fragment created | ||||
else | */ | ||||
switch (fragmentType){ | @Override | ||||
case ARRIVALS: | public void readyGUIfor(FragmentKind fragmentType) { | ||||
prepareGUIForBusLines(); | hideKeyboard(); | ||||
if (getOption(OPTION_SHOW_LEGEND, true)) { | //if we are getting results, already, stop waiting for nearbyStops | ||||
showHints(); | if(pendingNearbyStopsRequest && (fragmentType==FragmentKind.ARRIVALS || fragmentType==FragmentKind.STOPS)) { | ||||
} | locmgr.removeUpdates(locListener); | ||||
break; | pendingNearbyStopsRequest = false; | ||||
case STOPS: | } | ||||
prepareGUIForBusStops(); | if(fragmentType==null) Log.e("ActivityMain","Problem with fragmentType"); | ||||
break; | else | ||||
default: | switch (fragmentType){ | ||||
Log.e("BusTO Activity","Called readyGUI with unsupported type of Fragment"); | case ARRIVALS: | ||||
return; | prepareGUIForBusLines(); | ||||
} | if (getOption(OPTION_SHOW_LEGEND, true)) { | ||||
// Shows hints | showHints(); | ||||
} | |||||
} | break; | ||||
case STOPS: | |||||
/** | prepareGUIForBusStops(); | ||||
* Open an URL in the default browser. | break; | ||||
* | default: | ||||
* @param url URL | Log.e("BusTO Activity","Called readyGUI with unsupported type of Fragment"); | ||||
*/ | return; | ||||
public void openIceweasel(String url) { | } | ||||
Intent browserIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); | // Shows hints | ||||
startActivity(browserIntent1); | |||||
} | } | ||||
///////////////////// INTENT HELPER //////////////////////////////////////////////////////////// | /** | ||||
* Open an URL in the default browser. | |||||
/** | * | ||||
* Try to extract the bus stop ID from a URi | * @param url URL | ||||
* | */ | ||||
* @param uri The URL | public void openIceweasel(String url) { | ||||
* @return bus stop ID or null | Intent browserIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); | ||||
*/ | startActivity(browserIntent1); | ||||
public static String getBusStopIDFromUri(Uri uri) { | } | ||||
String busStopID; | |||||
///////////////////// INTENT HELPER //////////////////////////////////////////////////////////// | |||||
// everithing catches fire when passing null to a switch. | |||||
String host = uri.getHost(); | /** | ||||
if(host == null) { | * Try to extract the bus stop ID from a URi | ||||
Log.e("ActivityMain", "Not an URL: " + uri); | * | ||||
return null; | * @param uri The URL | ||||
} | * @return bus stop ID or null | ||||
*/ | |||||
switch(host) { | public static String getBusStopIDFromUri(Uri uri) { | ||||
case "m.gtt.to.it": | String busStopID; | ||||
// http://m.gtt.to.it/m/it/arrivi.jsp?n=1254 | |||||
busStopID = uri.getQueryParameter("n"); | // everithing catches fire when passing null to a switch. | ||||
if (busStopID == null) { | String host = uri.getHost(); | ||||
Log.e("ActivityMain", "Expected ?n from: " + uri); | if(host == null) { | ||||
} | Log.e("ActivityMain", "Not an URL: " + uri); | ||||
break; | return null; | ||||
case "www.gtt.to.it": | } | ||||
case "gtt.to.it": | |||||
// http://www.gtt.to.it/cms/percorari/arrivi?palina=1254 | switch(host) { | ||||
busStopID = uri.getQueryParameter("palina"); | case "m.gtt.to.it": | ||||
if (busStopID == null) { | // http://m.gtt.to.it/m/it/arrivi.jsp?n=1254 | ||||
Log.e("ActivityMain", "Expected ?palina from: " + uri); | busStopID = uri.getQueryParameter("n"); | ||||
} | if (busStopID == null) { | ||||
break; | Log.e("ActivityMain", "Expected ?n from: " + uri); | ||||
default: | } | ||||
Log.e("ActivityMain", "Unexpected intent URL: " + uri); | break; | ||||
busStopID = null; | case "www.gtt.to.it": | ||||
} | case "gtt.to.it": | ||||
return busStopID; | // http://www.gtt.to.it/cms/percorari/arrivi?palina=1254 | ||||
} | busStopID = uri.getQueryParameter("palina"); | ||||
if (busStopID == null) { | |||||
Log.e("ActivityMain", "Expected ?palina from: " + uri); | |||||
} | |||||
break; | |||||
default: | |||||
Log.e("ActivityMain", "Unexpected intent URL: " + uri); | |||||
busStopID = null; | |||||
} | |||||
return busStopID; | |||||
} | |||||
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