diff --git a/app/src/main/java/it/reyboz/bustorino/ActivityPrincipal.java b/app/src/main/java/it/reyboz/bustorino/ActivityPrincipal.java index f9a96d7..fb88b9a 100644 --- a/app/src/main/java/it/reyboz/bustorino/ActivityPrincipal.java +++ b/app/src/main/java/it/reyboz/bustorino/ActivityPrincipal.java @@ -1,914 +1,917 @@ /* BusTO - Arrival times for Turin public transport. Copyright (C) 2021 Fabio Mazza This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.*; import android.widget.Toast; import androidx.activity.OnBackPressedCallback; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.widget.Toolbar; import androidx.core.graphics.Insets; import androidx.core.view.*; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.ViewModelProvider; import androidx.preference.PreferenceManager; import androidx.work.WorkInfo; import com.google.android.material.navigation.NavigationView; import com.google.android.material.snackbar.Snackbar; import java.util.Arrays; import java.util.Map; import java.util.concurrent.LinkedBlockingDeque; import java.util.function.Consumer; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.data.DBUpdateCheckWorker; import it.reyboz.bustorino.data.DBUpdateWorker; import it.reyboz.bustorino.data.PreferencesHolder; import it.reyboz.bustorino.fragments.*; import it.reyboz.bustorino.middleware.GeneralActivity; import it.reyboz.bustorino.viewmodels.ServiceAlertsViewModel; import static it.reyboz.bustorino.backend.utils.getBusStopIDFromUri; import static it.reyboz.bustorino.backend.utils.openIceweasel; public class ActivityPrincipal extends GeneralActivity implements FragmentListenerMain { private DrawerLayout mDrawer; private NavigationView mNavView; private ActionBarDrawerToggle drawerToggle; private final static String DEBUG_TAG="BusTO Act Principal"; private final static String TAG_FAVORITES="favorites_frag"; private Snackbar snackbar; private ServiceAlertsViewModel serviceAlertsViewModel; - private FragmentKind showingFragmentKind; + //private FragmentKind showingFragmentKind; private final Map menuActions = Map.of( R.id.drawer_action_settings, () -> { Log.d("MAINBusTO", "Pressed button preferences"); startActivity(new Intent(this, ActivitySettings.class)); }, R.id.nav_favorites_item, () -> checkAndShowFavoritesFragment(getSupportFragmentManager(), true), R.id.nav_home, this::showHomeMainFragmentFromClick, R.id.nav_map_item, () -> requestMapFragment(true), R.id.nav_lines_item, () -> showLinesFragment(getSupportFragmentManager(), true, null), R.id.drawer_action_info, () -> startActivity(new Intent(this, ActivityAbout.class)), R.id.nav_nearby, this::openNearbyStopsFragment ); private long lastClosingAttempt = -1L; private final OnBackPressedCallback backPressedCallback = new OnBackPressedCallback(false) { @Override public void handleOnBackPressed() { boolean isResolved = activityCustomBackPressed(); Log.d(DEBUG_TAG, "backpress resolved: " + isResolved); if(!isResolved){ long currentTime = System.currentTimeMillis(); if(currentTime - lastClosingAttempt < 2000){ finish(); } else{ lastClosingAttempt = currentTime; Toast.makeText(getApplicationContext(),R.string.back_again_to_close,Toast.LENGTH_SHORT).show(); } } } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(DEBUG_TAG, "onCreate, savedInstanceState is: "+savedInstanceState); setContentView(R.layout.activity_principal); serviceAlertsViewModel = new ViewModelProvider(this).get(ServiceAlertsViewModel.class); //Use LiveModel to sync fragment state /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { getWindow().setNavigationBarContrastEnforced(false); } */ //onBackPressed solution required from Android 16 backPressedCallback.setEnabled(true); this.getOnBackPressedDispatcher().addCallback(backPressedCallback); boolean showingArrivalsFromIntent = false; final Toolbar mToolbar = findViewById(R.id.default_toolbar); setSupportActionBar(mToolbar); if (getSupportActionBar()!=null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); else Log.w(DEBUG_TAG, "NO ACTION BAR"); mToolbar.setOnMenuItemClickListener(new ToolbarItemClickListener(this)); mDrawer = findViewById(R.id.drawer_layout); drawerToggle = setupDrawerToggle(mToolbar); // Setup toggle to display hamburger icon with nice animation drawerToggle.setDrawerIndicatorEnabled(true); drawerToggle.syncState(); mDrawer.addDrawerListener(drawerToggle); mDrawer.addDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(@NonNull View drawerView, float slideOffset) { } @Override public void onDrawerOpened(@NonNull View drawerView) { hideKeyboard(); } @Override public void onDrawerClosed(@NonNull View drawerView) { } @Override public void onDrawerStateChanged(int newState) { } }); mNavView = findViewById(R.id.nvView); setupDrawerContent(mNavView); /*View header = mNavView.getHeaderView(0); */ //mNavView.getMenu().findItem(R.id.versionFooter). /// LEGACY CODE //---------------------------- START INTENT CHECK QUEUE ------------------------------------ // Intercept calls from URL intent boolean tryedFromIntent = false; String busStopID = null; Uri data = getIntent().getData(); if (data != null) { busStopID = getBusStopIDFromUri(data); Log.d(DEBUG_TAG, "Opening Intent: busStopID: "+busStopID); tryedFromIntent = true; } // Intercept calls from other activities if (!tryedFromIntent) { Bundle b = getIntent().getExtras(); if (b != null) { busStopID = b.getString("bus-stop-ID"); /* * I'm not very sure if you are coming from an Intent. * Some launchers work in strange ways. */ tryedFromIntent = busStopID != null; } } //---------------------------- END INTENT CHECK QUEUE -------------------------------------- if (busStopID == null) { // Show keyboard if can't start from intent // JUST DON'T // showKeyboard(); // You haven't obtained anything... from an intent? if (tryedFromIntent) { // This shows a luser warning Toast.makeText(getApplicationContext(), R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show(); } } else { // If you are here an intent has worked successfully //setBusStopSearchByIDEditText(busStopID); //Log.d(DEBUG_TAG, "Requesting arrivals for stop "+busStopID+" from intent"); requestArrivalsForStopID(busStopID); //this shows the fragment, too showingArrivalsFromIntent = true; } //database check // DatabaseUpdate.requestDBUpdateWithWork(this, false, false); DBUpdateCheckWorker.Companion.schedulePeriodicCheck(this,false); /* Watch for database update */ DBUpdateWorker.getWorkInfoLiveData(this) .observe(this, workInfoList -> { // If there are no matching work info, do nothing if (workInfoList == null || workInfoList.isEmpty()) { return; } Log.d(DEBUG_TAG, "WorkerInfo: "+workInfoList); boolean showProgress = false; for (WorkInfo workInfo : workInfoList) { if (workInfo.getState() == WorkInfo.State.RUNNING) { showProgress = true; break; } } if (showProgress) { createDatabaseUpdateSnackbar(); } else { if(snackbar!=null) { snackbar.dismiss(); snackbar = null; } } }); // show the main fragment Fragment f = getSupportFragmentManager().findFragmentById(R.id.mainActContentFrame); Log.d(DEBUG_TAG, "OnCreate the fragment is "+f); String vl = PreferenceManager.getDefaultSharedPreferences(this).getString(SettingsFragment.PREF_KEY_STARTUP_SCREEN, ""); Log.d(DEBUG_TAG, "The default screen to open is: "+vl); if (showingArrivalsFromIntent){ //do nothing but exclude a case }else if (savedInstanceState==null) { var framan = getSupportFragmentManager(); //we are not restarting the activity from nothing switch (vl){ case "map" -> {requestMapFragment(false);} case "favorites" -> checkAndShowFavoritesFragment(framan, false); case "lines" -> showLinesFragment(framan, false, null); case "nearby" -> createShowMainFragment(framan, MainScreenFragment.makeArgsNearby(), false); default -> createShowMainFragment(framan, MainScreenFragment.makeArgsButtonsScreen(), false); } } //boolean onCreateComplete = true; //last but not least, set the good default values checkApplyDefaultSettingsValues(); // handle the device "insets" /* ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.rootRelativeLayout), (v, windowInsets) -> { Insets insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()); // Apply the insets as a margin to the view. This solution sets only the // bottom, left, and right dimensions, but you can apply whichever insets are // appropriate to your layout. You can also update the view padding if that's // more appropriate. ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) v.getLayoutParams(); mlp.leftMargin = insets.left; mlp.bottomMargin = insets.bottom; mlp.rightMargin = insets.right; v.setLayoutParams(mlp); //set for toolbar //mlp = (ViewGroup.MarginLayoutParams) mToolbar.getLayoutParams(); //mlp.topMargin = insets.top; //mToolbar.setLayoutParams(mlp); mToolbar.setPadding(0, insets.top, 0, 0); // Return CONSUMED if you don't want the window insets to keep passing // down to descendant views. return WindowInsetsCompat.CONSUMED; }); //to properly handle IME WindowInsetsControllerCompat insetsController = WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView()); if (insetsController != null) { insetsController.setSystemBarsBehavior( WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE ); } */ // Toolbar: solo inset superiore (status bar) ViewCompat.setOnApplyWindowInsetsListener(mToolbar, (v, windowInsets) -> { Insets statusBar = windowInsets.getInsets(WindowInsetsCompat.Type.statusBars()); v.setPadding(0, statusBar.top, 0, 0); return windowInsets; // NON consumare: passa gli insets ai figli }); // Content frame: insets laterali e inferiori (navigation bar) // I fragment figli riceveranno gli insets e potranno gestirli a loro volta ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.mainActContentFrame), (v, windowInsets) -> { Insets systemBars = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()); // Solo left/right, bottom lo gestisce ogni fragment v.setPadding(systemBars.left, 0, systemBars.right, 0); return windowInsets; //WindowInsetsCompat.CONSUMED; // NON consumare: passa ai fragment }); //check if first run activity (IntroActivity) has been started once or not final SharedPreferences theShPr = getMainSharedPreferences(); boolean hasIntroRun = theShPr.getBoolean(PreferencesHolder.PREF_INTRO_ACTIVITY_RUN,false); if(!hasIntroRun){ startIntroductionActivity(); } serviceAlertsViewModel.getLastTimeRunningDownload().observe(this, (timeRunning) -> { if (timeRunning != null) { Log.d(DEBUG_TAG, "requested alerts download at time: "+timeRunning); } }); serviceAlertsViewModel.launchAlertsPeriodCheck(); } private ActionBarDrawerToggle setupDrawerToggle(Toolbar toolbar) { // NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it // and will not render the hamburger icon without it. return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close); } /** * Setup drawer actions * @param navigationView the navigation view on which to set the callbacks */ private void setupDrawerContent(NavigationView navigationView) { navigationView.setNavigationItemSelectedListener( menuItem -> { int menuId = menuItem.getItemId(); if( menuActions.containsKey(menuId)){ closeDrawerIfOpen(); var runnable = menuActions.get(menuId); if(runnable!=null) runnable.run(); return true; } else{ return false; } }); } private void closeDrawerIfOpen(){ if (mDrawer.isDrawerOpen(GravityCompat.START)) mDrawer.closeDrawer(GravityCompat.START); } // `onPostCreate` called when activity start-up is complete after `onStart()` // NOTE 1: Make sure to override the method with only a single `Bundle` argument // Note 2: Make sure you implement the correct `onPostCreate(Bundle savedInstanceState)` method. // There are 2 signatures and only `onPostCreate(Bundle state)` shows the hamburger icon. @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle.syncState(); } @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.principal_menu, menu); MenuItem experimentsMenuItem = menu.findItem(R.id.action_experiments); SharedPreferences shPr = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); boolean exper_On = shPr.getBoolean(getString(R.string.pref_key_experimental), false); experimentsMenuItem.setVisible(exper_On); return super.onCreateOptionsMenu(menu); } //requesting permissions @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode==STORAGE_PERMISSION_REQ){ final String storagePerm = Manifest.permission.WRITE_EXTERNAL_STORAGE; if (permissionDoneRunnables.containsKey(storagePerm)) { Runnable toRun = permissionDoneRunnables.get(storagePerm); if (toRun != null) toRun.run(); permissionDoneRunnables.remove(storagePerm); } if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d(DEBUG_TAG, "Permissions check: " + Arrays.toString(permissions)); if (permissionDoneRunnables.containsKey(storagePerm)) { Runnable toRun = permissionDoneRunnables.get(storagePerm); if (toRun != null) toRun.run(); permissionDoneRunnables.remove(storagePerm); } } else { //permission denied showToastMessage(R.string.permission_storage_maps_msg, false); } } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { Log.d(DEBUG_TAG, "Item pressed"); if (item.getItemId() == android.R.id.home) { mDrawer.openDrawer(GravityCompat.START); return true; } if (drawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } /*@Override public void onBackPressed() { if (!activityCustomBackPressed()) super.onBackPressed(); } */ private boolean activityCustomBackPressed(){ var mainFragManager = getSupportFragmentManager(); boolean resolved = mainFragManager.getBackStackEntryCount() > 0; Fragment shownFrag = mainFragManager.findFragmentById(R.id.mainActContentFrame); if (mDrawer.isDrawerOpen(GravityCompat.START)) { mDrawer.closeDrawer(GravityCompat.START); resolved = true; } else if (shownFrag instanceof MainScreenFragment mainFrag) { //the only case when we have to pop both stacks mainFrag.cancelReloadArrivalsIfNeeded(); var chManager = mainFrag.getChildFragmentManager(); if(chManager.getBackStackEntryCount() > 0){ chManager.popBackStack(); Log.d(DEBUG_TAG, "Child back stack popped"); resolved = true; } else{ Log.d(DEBUG_TAG, "No back stack on child fragment manager"); } boolean haveToPopMainFromFragment = mainFrag.needToPopMainStackOnBack(); //mainFrag.getChildFragmentManager().popBackStack(); if(haveToPopMainFromFragment){ // pops the stack mainFragManager.popBackStack(); } } else if (getSupportFragmentManager().getBackStackEntryCount() > 0) { mainFragManager.popBackStack(); var newFrag = mainFragManager.findFragmentById(R.id.mainActContentFrame); if(newFrag != null) { int backStackCount = newFrag.getChildFragmentManager().getBackStackEntryCount(); Log.d(DEBUG_TAG, "new fragment is "+newFrag.getClass().getSimpleName() +", count of the backstack: "+backStackCount); } Log.d(DEBUG_TAG, "Popping main backstack"); } else{ resolved = false; } return resolved; } /** * Create and show the SnackBar with the message * The fragment shown points to which view to attach the snackbar */ private void createDatabaseUpdateSnackbar() { View baseView = null; boolean showSnackbar = true; final Fragment frag = getSupportFragmentManager().findFragmentById(R.id.mainActContentFrame); if (frag instanceof ScreenBaseFragment){ baseView = ((ScreenBaseFragment) frag).getBaseViewForSnackBar(); showSnackbar = ((ScreenBaseFragment) frag).showSnackbarOnDBUpdate(); } if (baseView == null) baseView = findViewById(R.id.mainActContentFrame); //if (baseView == null) Log.e(DEBUG_TAG, "baseView null for default snackbar, probably exploding now"); if (baseView !=null && showSnackbar) { snackbar = Snackbar.make(baseView, R.string.database_update_msg_inapp, Snackbar.LENGTH_INDEFINITE); snackbar.setTextColor(getColor(android.R.color.white)); snackbar.setBackgroundTint(getColor(R.color.grey_800)); if (frag instanceof ScreenBaseFragment){ ((ScreenBaseFragment) frag).setSnackbarPropertiesBeforeShowing(snackbar); } snackbar.show(); } else{ Log.e(DEBUG_TAG, "Asked to show the snackbar but the baseView is null"); } } + /* private void updateShowingFragmentKindInternal(@NonNull FragmentKind newKind){ if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Updating fragment kind, new: "+newKind+", current: "+showingFragmentKind); boolean showingMainFragmentFromOther = false; if(showingFragmentKind == null){ showingFragmentKind = newKind; showingMainFragmentFromOther = false; } else if(newKind != showingFragmentKind) { showingMainFragmentFromOther = ( FragmentKind.getSuperKind(newKind) != FragmentKind.getSuperKind(showingFragmentKind)); showingFragmentKind = newKind; } } + */ + /** * Show the actual fragment by adding it to the backstack * @param fraMan the fragmentManager * @param fragment the fragment */ private static void showMainFragment(FragmentManager fraMan, MainScreenFragment fragment, boolean addToBackStack){ FragmentTransaction ft = fraMan.beginTransaction() .replace(R.id.mainActContentFrame, fragment, MainScreenFragment.FRAGMENT_TAG) .setReorderingAllowed(false) /*.setCustomAnimations( R.anim.slide_in, // enter R.anim.fade_out, // exit R.anim.fade_in, // popEnter R.anim.slide_out // popExit )*/ .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); if (addToBackStack) { ft.addToBackStack(null); } ft.commit(); } /** * Create a new MainFragment for the arguments provided and show it in the layout * @param fraMan the fragmentManager * @param arguments args for the fragment */ private static void createShowMainFragment(FragmentManager fraMan,@Nullable Bundle arguments, boolean addToBackStack){ FragmentTransaction ft = fraMan.beginTransaction() .replace(R.id.mainActContentFrame, MainScreenFragment.class, arguments, MainScreenFragment.FRAGMENT_TAG) .setReorderingAllowed(false) /*.setCustomAnimations( R.anim.slide_in, // enter R.anim.fade_out, // exit R.anim.fade_in, // popEnter R.anim.slide_out // popExit )*/ .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); if (addToBackStack) ft.addToBackStack(null); ft.commit(); } private void showHomeMainFragmentFromClick(){ FragmentManager fraMan = getSupportFragmentManager(); var fragment = fraMan.findFragmentByTag(MainScreenFragment.FRAGMENT_TAG); if(fragment instanceof MainScreenFragment mainFrag){ var visible = mainFrag.isVisible(); if(!mainFrag.isVisible()){ showMainFragment(fraMan, mainFrag, true); } mainFrag.showButtonsFragmentIfNotNearby(true); } else{ createShowMainFragment(fraMan, MainScreenFragment.makeArgsButtonsScreen(), true); } } private void requestMapFragment(final boolean allowReturn){ // starting from Android 11, we don't need to have the STORAGE permission anymore for the map cache FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.mainActContentFrame); if(fragment instanceof MapLibreFragment){ Log.d(DEBUG_TAG, "Requested map fragment, but it is already open"); } else { fragment = fm.findFragmentByTag(MapLibreFragment.FRAGMENT_TAG); if(fragment != null){ Log.d(DEBUG_TAG, "Found map fragment, reopening it"); var ft = fm.beginTransaction(); ft.replace(R.id.mainActContentFrame,fragment, MapLibreFragment.FRAGMENT_TAG); if(allowReturn) ft.addToBackStack(null); ft.commit(); } else { //create from scratch //The permissions are handled in the MapLibreFragment instead createAndShowMapFragment(null, allowReturn); } } } private void checkAndShowFavoritesFragment(FragmentManager fragmentManager, boolean addToBackStack){ if(getSupportFragmentManager().findFragmentById(R.id.mainActContentFrame) instanceof FavoritesFragment){ Log.d(DEBUG_TAG, "Requested favorites fragment, but it is already open"); return; } FragmentTransaction ft = fragmentManager.beginTransaction(); Fragment fragment = fragmentManager.findFragmentByTag(TAG_FAVORITES); if(fragment!=null){ ft.replace(R.id.mainActContentFrame, fragment, TAG_FAVORITES); }else{ //use new method ft.replace(R.id.mainActContentFrame,FavoritesFragment.class,null,TAG_FAVORITES); } if (addToBackStack) ft.addToBackStack("favorites_main"); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .setReorderingAllowed(false); ft.commit(); } private void showLinesFragment(@NonNull FragmentManager fragmentManager, boolean addToBackStack, @Nullable Bundle fragArgs){ if(getSupportFragmentManager().findFragmentById(R.id.mainActContentFrame) instanceof LinesGridShowingFragment){ Log.d(DEBUG_TAG, "Requested lines grid fragment, but it is already open"); return; } FragmentTransaction ft = fragmentManager.beginTransaction(); Fragment f = fragmentManager.findFragmentByTag(LinesGridShowingFragment.FRAGMENT_TAG); if(f!=null){ ft.replace(R.id.mainActContentFrame, f, LinesGridShowingFragment.FRAGMENT_TAG); }else{ //use new method ft.replace(R.id.mainActContentFrame,LinesGridShowingFragment.class,fragArgs, LinesGridShowingFragment.FRAGMENT_TAG); } if (addToBackStack) ft.addToBackStack("linesGrid"); ft.setReorderingAllowed(true) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); } @Nullable private MainScreenFragment getMainFragmentIfVisible(){ FragmentManager fraMan = getSupportFragmentManager(); Fragment fragment = fraMan.findFragmentByTag(MainScreenFragment.FRAGMENT_TAG); if (fragment!= null && fragment.isVisible()) return (MainScreenFragment) fragment; else return null; } @Override public void showFloatingActionButton(boolean yes) { var frag = getMainFragmentIfVisible(); if(frag!=null){ frag.showFloatingActionButton(yes); } } /* public void setDrawerSelectedItem(String fragmentTag){ switch (fragmentTag){ case MainScreenFragment.FRAGMENT_TAG: mNavView.setCheckedItem(R.id.nav_arrivals); break; case MapFragment.FRAGMENT_TAG: break; case FavoritesFragment.FRAGMENT_TAG: mNavView.setCheckedItem(R.id.nav_favorites_item); break; } }*/ @Override public void readyGUIfor(FragmentKind fragmentType) { - - updateShowingFragmentKindInternal(fragmentType); + //updateShowingFragmentKindInternal(fragmentType); + if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "readyGUIfor fragment kind: " + fragmentType); Integer titleResId = null; switch (fragmentType){ case MAP: mNavView.setCheckedItem(R.id.nav_map_item); titleResId = R.string.map; break; case FAVORITES: mNavView.setCheckedItem(R.id.nav_favorites_item); titleResId = R.string.nav_favorites_text; break; case ARRIVALS: titleResId = R.string.nav_arrivals_text; mNavView.setCheckedItem(R.id.nav_home); //TODO: Figure out way to change title //mNavView.getCheckedItem().setTitle(R.string.nav_arrivals_text); break; case STOPS: titleResId = R.string.stop_search_view_title; mNavView.setCheckedItem(R.id.nav_home); break; case MAIN_SCREEN_FRAGMENT: case HOME_BUTTONS: titleResId=R.string.app_name_full; mNavView.setCheckedItem(R.id.nav_home); //mNavView.getCheckedItem().setTitle(R.string.nav_home_text); break; case NEARBY_STOPS: case NEARBY_ARRIVALS: titleResId=R.string.app_name_full; mNavView.setCheckedItem(R.id.nav_nearby); break; case LINES: titleResId=R.string.lines; mNavView.setCheckedItem(R.id.nav_lines_item); break; } if(getSupportActionBar()!=null && titleResId!=null) getSupportActionBar().setTitle(titleResId); MainScreenFragment mainFragmentIfVisible = getMainFragmentIfVisible(); if (mainFragmentIfVisible!=null){ mainFragmentIfVisible.readyGUIfor(fragmentType); } } @Override public void requestArrivalsForStopID(String ID) { Consumer consumer = fragment -> { fragment.setSuppressArrivalsReload(true); fragment.requestArrivalsForStopID(ID); }; boolean done = getMainFragmentAndDoStuff(consumer); if(!done){ //create the fragment final Bundle args = MainScreenFragment.makeArgsArrivals(ID); createShowMainFragment(getSupportFragmentManager(), args ,true); } } @Override public void openLineFromStop(String routeGtfsId, @Nullable String stopIDFrom){ FragmentTransaction tr = getSupportFragmentManager().beginTransaction(); tr.replace(R.id.mainActContentFrame, LinesDetailFragment.class, LinesDetailFragment.Companion.makeArgs(routeGtfsId, stopIDFrom)); tr.addToBackStack("LineFromStop-"+routeGtfsId); tr.commit(); } private boolean getMainFragmentAndDoStuff(Consumer consumer){ FragmentManager fraMan = getSupportFragmentManager(); var frag = fraMan.findFragmentByTag(MainScreenFragment.FRAGMENT_TAG); if( frag instanceof MainScreenFragment mainFrag){ if(!mainFrag.isVisible()) { showMainFragment(fraMan, mainFrag, true); mainFrag.setMainFragmentManagerTransition(true); } else{ mainFrag.setMainFragmentManagerTransition(false); } consumer.accept(mainFrag); return true; } else{ return false; } } @Override public void openLineFromVehicle(String routeGtfsId, @Nullable String optionalPatternId, @Nullable Bundle args) { FragmentTransaction tr = getSupportFragmentManager().beginTransaction(); tr.replace(R.id.mainActContentFrame, LinesDetailFragment.class, LinesDetailFragment.Companion.makeArgsPattern(routeGtfsId, optionalPatternId, args)); tr.addToBackStack("LineFromOther-"+routeGtfsId); tr.commit(); } @Override public void openNearbyStopsFragment() { boolean done = getMainFragmentAndDoStuff(MainScreenFragment::openNearbyStopsFragment); if(!done){ createShowMainFragment(getSupportFragmentManager(), MainScreenFragment.makeArgsNearby(), true); } } @Override public void openLinesFragment() { showLinesFragment(getSupportFragmentManager(), true, null); } @Override public void openFavoritesFragment() { checkAndShowFavoritesFragment(getSupportFragmentManager(), true); } @Override public void toggleSpinner(boolean state) { MainScreenFragment probableFragment = getMainFragmentIfVisible(); if (probableFragment!=null){ probableFragment.toggleSpinner(state); } } @Override public void enableRefreshLayout(boolean yes) { MainScreenFragment probableFragment = getMainFragmentIfVisible(); if (probableFragment!=null){ probableFragment.enableRefreshLayout(yes); } } @Override public void showMapCenteredOnStop(@Nullable Stop stop) { createAndShowMapFragment(stop, true); } //Map Fragment stuff void createAndShowMapFragment(@Nullable Stop stop, boolean addToBackStack){ final FragmentManager fm = getSupportFragmentManager(); final FragmentTransaction ft = fm.beginTransaction(); final MapLibreFragment fragment = MapLibreFragment.newInstance(stop); ft.replace(R.id.mainActContentFrame, fragment, MapLibreFragment.FRAGMENT_TAG); if (addToBackStack) ft.addToBackStack(null); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } void startIntroductionActivity(){ Intent intent = new Intent(ActivityPrincipal.this, ActivityIntro.class); intent.putExtra(ActivityIntro.RESTART_MAIN, false); startActivity(intent); } class ToolbarItemClickListener implements Toolbar.OnMenuItemClickListener{ private final Context activityContext; public ToolbarItemClickListener(Context activityContext) { this.activityContext = activityContext; } @Override public boolean onMenuItemClick(MenuItem item) { final int id = item.getItemId(); if(id == R.id.action_about){ startActivity(new Intent(ActivityPrincipal.this, ActivityAbout.class)); return true; } else if (id == R.id.action_hack) { openIceweasel(getString(R.string.hack_url), activityContext); return true; } else if (id == R.id.action_source){ openIceweasel("https://gitpull.it/source/libre-busto/", activityContext); return true; } else if (id == R.id.action_licence){ openIceweasel("https://www.gnu.org/licenses/gpl-3.0.html", activityContext); return true; } else if (id == R.id.action_experiments) { startActivity(new Intent(ActivityPrincipal.this, ActivityExperiments.class)); return true; } else if (id == R.id.action_tutorial) { startIntroductionActivity(); return true; } return false; } } @Override protected void onPause() { super.onPause(); // stop updating the alerts serviceAlertsViewModel.setRunningDownloadRequests(false); } @Override protected void onResume() { super.onResume(); serviceAlertsViewModel.launchAlertsPeriodCheck(); } } diff --git a/app/src/main/java/it/reyboz/bustorino/adapters/ArrivalsStopAdapter.java b/app/src/main/java/it/reyboz/bustorino/adapters/ArrivalsStopAdapter.java index 7102c78..35ee280 100644 --- a/app/src/main/java/it/reyboz/bustorino/adapters/ArrivalsStopAdapter.java +++ b/app/src/main/java/it/reyboz/bustorino/adapters/ArrivalsStopAdapter.java @@ -1,301 +1,305 @@ /* BusTO - UI components Copyright (C) 2017 Fabio Mazza This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.adapters; import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.util.Pair; import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.*; import it.reyboz.bustorino.fragments.FragmentListenerMain; import java.util.*; public class ArrivalsStopAdapter extends RecyclerView.Adapter implements SharedPreferences.OnSharedPreferenceChangeListener { private final static int layoutRes = R.layout.arrivals_nearby_card; //private List stops; private @NonNull GPSPoint userPosition; private FragmentListenerMain listener; private List< RouteWithStop > routesPairList; private final Context context; //Maximum number of stops to keep private final int MAX_STOPS = 20; //TODO: make it programmable - private String KEY_CAPITALIZE; + private final String KEY_CAPITALIZE; private NameCapitalize capit; public ArrivalsStopAdapter(@Nullable List< RouteWithStop > routesPairList, FragmentListenerMain fragmentListener, Context con, @NonNull GPSPoint pos) { listener = fragmentListener; userPosition = pos; this.routesPairList = routesPairList; context = con.getApplicationContext(); resetListAndPosition(); // if(paline!=null) //resetRoutesPairList(paline); KEY_CAPITALIZE = context.getString(R.string.pref_arrival_times_capit); SharedPreferences defSharPref = PreferenceManager.getDefaultSharedPreferences(context); defSharPref.registerOnSharedPreferenceChangeListener(this); String capitalizeKey = defSharPref.getString(KEY_CAPITALIZE, ""); this.capit = NameCapitalize.getCapitalize(capitalizeKey); } @NonNull @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View view = LayoutInflater.from(parent.getContext()).inflate(layoutRes, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { //DO THE ACTUAL WORK TO PUT THE DATA if(routesPairList==null || routesPairList.size() == 0) return; //NO STOPS final var stopRoutePair = routesPairList.get(position); if(stopRoutePair != null){ final Stop stop = stopRoutePair.getStop(); final Route r = stopRoutePair.getRoute(); final Double distance = stop.getDistanceFromLocation(userPosition.getLatitude(), userPosition.longitude); if(distance!=Double.POSITIVE_INFINITY){ holder.distancetextView.setText(distance.intValue()+" m"); } else { holder.distancetextView.setVisibility(View.GONE); } final String stopText = String.format(context.getResources().getString(R.string.two_strings_format),stop.getStopDisplayName(),stop.ID); holder.stopNameView.setText(stopText); //final String routeName = String.format(context.getResources().getString(R.string.two_strings_format),r.getNameForDisplay(),r.destinazione); if (r!=null) { holder.lineNameTextView.setText(r.getDisplayCode()); holder.lineDirectionTextView.setText(NameCapitalize.capitalizePass(r.destinazione, capit)); holder.arrivalsTextView.setText(r.getPassaggiToString(0,2,true)); } else { holder.lineNameTextView.setVisibility(View.INVISIBLE); holder.lineDirectionTextView.setVisibility(View.INVISIBLE); //holder.arrivalsTextView.setVisibility(View.INVISIBLE); } /* EXPERIMENTS if(r.destinazione==null || r.destinazione.trim().isEmpty()){ holder.lineDirectionTextView.setVisibility(View.GONE); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.arrivalsDescriptionTextView.getLayoutParams(); params.addRule(RelativeLayout.RIGHT_OF,holder.lineNameTextView.getId()); holder.arrivalsDescriptionTextView.setLayoutParams(params); } else { RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.arrivalsDescriptionTextView.getLayoutParams(); params.removeRule(RelativeLayout.RIGHT_OF); holder.arrivalsDescriptionTextView.setLayoutParams(params); holder.lineDirectionTextView.setVisibility(View.VISIBLE); } */ holder.stopID =stop.ID; } else { Log.w("SquareStopAdapter","!! The selected stop is null !!"); } } @Override public int getItemCount() { return routesPairList.size(); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if(key.equals(KEY_CAPITALIZE)){ String k = sharedPreferences.getString(KEY_CAPITALIZE, ""); capit = NameCapitalize.getCapitalize(k); notifyDataSetChanged(); } } class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView lineNameTextView; TextView lineDirectionTextView; TextView stopNameView; TextView arrivalsDescriptionTextView; TextView arrivalsTextView; TextView distancetextView; String stopID; ViewHolder(View holdView){ super(holdView); holdView.setOnClickListener(this); lineNameTextView = (TextView) holdView.findViewById(R.id.lineNameTextView); lineDirectionTextView = (TextView) holdView.findViewById(R.id.lineDirectionTextView); stopNameView = (TextView) holdView.findViewById(R.id.arrivalStopName); arrivalsTextView = (TextView) holdView.findViewById(R.id.arrivalsTimeTextView); arrivalsDescriptionTextView = (TextView) holdView.findViewById(R.id.arrivalsDescriptionTextView); distancetextView = (TextView) holdView.findViewById(R.id.arrivalsDistanceTextView); } @Override public void onClick(View v) { listener.requestArrivalsForStopID(stopID); } } /* public void resetRoutesPairList(List stopList){ Collections.sort(stopList,new StopSorterByDistance(userPosition)); this.routesPairList = new ArrayList<>(stopList.size()); int maxNum = Math.min(MAX_STOPS, stopList.size()); for(Palina p: stopList.subList(0,maxNum)){ //if there are no routes available, skip stop if(p.queryAllRoutes().size() == 0) continue; for(Route r: p.queryAllRoutes()){ //if there are no routes, should not do anything routesPairList.add(new Pair<>(p,r)); } } } */ + public void updatePosition(@NonNull GPSPoint pos){ + userPosition = pos; + } + public void setRoutesPairListAndPosition(@NonNull List newList, @Nullable GPSPoint pos) { + if(pos!=null) updatePosition(pos); - public void setRoutesPairListAndPosition(@NonNull List newList) { if (routesPairList == null) { routesPairList = new ArrayList<>(newList); notifyItemRangeInserted(0, newList.size()); return; } DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffUtil.Callback() { @Override public int getOldListSize() { return routesPairList.size(); } @Override public int getNewListSize() { return newList.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { RouteWithStop oldItem = routesPairList.get(oldItemPosition); RouteWithStop newItem = newList.get(newItemPosition); // usa un ID univoco return oldItem.getId().equals(newItem.getId()); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { RouteWithStop oldItem = routesPairList.get(oldItemPosition); RouteWithStop newItem = newList.get(newItemPosition); // confronta il contenuto return oldItem.equals(newItem); } } ); routesPairList.clear(); routesPairList.addAll(newList); diffResult.dispatchUpdatesTo(this); /*if (this.routesPairList == null || routesPairList.size() == 0){ routesPairList = mRoutesPairList; notifyDataSetChanged(); } else{ final var indexMapIn = getRouteIndexMap(mRoutesPairList); final var indexMapExisting = getRouteIndexMap(routesPairList); //List> oldList = routesPairList; routesPairList = mRoutesPairList; /* for (Pair pair: indexMapIn.keySet()){ final Integer posIn = indexMapIn.get(pair); if (posIn == null) continue; if (indexMapExisting.containsKey(pair)){ final Integer posExisting = indexMapExisting.get(pair); //THERE IS ALREADY //routesPairList.remove(posExisting.intValue()); //routesPairList.add(posIn,mRoutesPairList.get(posIn)); notifyItemMoved(posExisting, posIn); indexMapExisting.remove(pair); } else{ //INSERT IT //routesPairList.add(posIn,mRoutesPairList.get(posIn)); notifyItemInserted(posIn); } }// //REMOVE OLD STOPS for (Pair pair: indexMapExisting.keySet()) { final Integer posExisting = indexMapExisting.get(pair); if (posExisting == null) continue; //routesPairList.remove(posExisting.intValue()); notifyItemRemoved(posExisting); } */ } /** * Sort and remove the repetitions for the routesPairList */ private void resetListAndPosition(){ //Collections.sort(this.routesPairList,new RoutePositionSorter(userPosition)); //All of this to get only the first occurrences of a line (name & direction) var iterator = routesPairList.listIterator(); Set> allRoutesDirections = new HashSet<>(); while(iterator.hasNext()){ final var stopRoutePair = iterator.next(); stopRoutePair.getRoute(); final Pair routeNameDirection = new Pair<>(stopRoutePair.getRoute().getName(), stopRoutePair.getRoute().destinazione); if (allRoutesDirections.contains(routeNameDirection)) { iterator.remove(); } else { allRoutesDirections.add(routeNameDirection); } } } private static HashMap getRouteIndexMap(List routesPairList){ final HashMap myMap = new HashMap<>(); for (int i=0; i. */ package it.reyboz.bustorino.adapters; import android.location.Location; import androidx.annotation.Nullable; +import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.GPSPoint; +import it.reyboz.bustorino.backend.RouteWithStop; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.util.StopSorterByDistance; import it.reyboz.bustorino.fragments.FragmentListenerMain; import java.util.Collections; import java.util.List; public class SquareStopAdapter extends RecyclerView.Adapter { private final static int layoutRes = R.layout.stop_card; //private List stops; private @Nullable GPSPoint userPosition; private FragmentListenerMain listener; private List stops; public SquareStopAdapter(@Nullable List stopList, FragmentListenerMain fragmentListener, @Nullable GPSPoint pos) { listener = fragmentListener; userPosition = pos; stops = stopList; } @Override public SquareViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View view = LayoutInflater.from(parent.getContext()).inflate(layoutRes, parent, false); //sort the stops by distance if(stops != null && stops.size() > 0) Collections.sort(stops,new StopSorterByDistance(userPosition)); return new SquareViewHolder(view); } @Override public void onBindViewHolder(SquareViewHolder holder, int position) { //DO THE ACTUAL WORK TO PUT THE DATA if(stops==null || stops.size() == 0) return; //NO STOPS final Stop stop = stops.get(position); if(stop!=null){ if(stop.getDistanceFromLocation(userPosition)!=Double.POSITIVE_INFINITY){ Double distance = stop.getDistanceFromLocation(userPosition); holder.distancetextView.setText(distance.intValue()+" m"); } else { holder.distancetextView.setVisibility(View.GONE); } holder.stopNameView.setText(stop.getStopDisplayName()); holder.stopIDView.setText(stop.ID); String whatStopsHere = stop.routesThatStopHereToString(); if(whatStopsHere == null) { holder.routesView.setVisibility(View.GONE); } else { holder.routesView.setText(whatStopsHere); holder.routesView.setVisibility(View.VISIBLE); // might be GONE due to View Holder Pattern } holder.stopID =stop.ID; } else { Log.w("SquareStopAdapter","!! The selected stop is null !!"); } } @Override public int getItemCount() { return stops.size(); } class SquareViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView stopIDView; TextView stopNameView; TextView routesView; TextView distancetextView; String stopID; SquareViewHolder(View holdView){ super(holdView); holdView.setOnClickListener(this); stopIDView = (TextView) holdView.findViewById(R.id.stop_numberText); stopNameView = (TextView) holdView.findViewById(R.id.stop_nameText); routesView = (TextView) holdView.findViewById(R.id.stop_linesText); distancetextView = (TextView) holdView.findViewById(R.id.stop_distanceTextView); } @Override public void onClick(View v) { listener.requestArrivalsForStopID(stopID); } } - public void setStops(List stops) { - this.stops = stops; + public void setStops(List newStops) { + // this.stops = stops; + DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffUtil.Callback() { + @Override + public int getOldListSize() { + return stops.size(); + } + @Override + public int getNewListSize() { + return newStops.size(); + } + @Override + public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { + var oldItem = stops.get(oldItemPosition); + var newItem = newStops.get(newItemPosition); + + // usa un ID univoco + return oldItem.ID.equals(newItem.ID); + } + + @Override + public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { + var oldItem = stops.get(oldItemPosition); + var newItem = newStops.get(newItemPosition); + return oldItem.equals(newItem); + } + }); + this.stops.clear(); + this.stops.addAll(newStops); + diffResult.dispatchUpdatesTo(this); } public void setUserPosition(@Nullable GPSPoint userPosition) { this.userPosition = userPosition; } /* @Override public Stop getItem(int position) { return stops.get(position); } */ } diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/LinesGridShowingFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/LinesGridShowingFragment.kt index e5a3f91..e8dcbc6 100644 --- a/app/src/main/java/it/reyboz/bustorino/fragments/LinesGridShowingFragment.kt +++ b/app/src/main/java/it/reyboz/bustorino/fragments/LinesGridShowingFragment.kt @@ -1,449 +1,455 @@ /* BusTO - Fragments components Copyright (C) 2018-2026 Fabio Mazza This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.fragments import android.content.Context import android.os.Bundle import android.util.Log import android.view.* import android.view.animation.Animation import android.view.animation.LinearInterpolator import android.view.animation.RotateAnimation import android.widget.ImageView import android.widget.TextView import androidx.appcompat.widget.SearchView import androidx.core.view.MenuHost import androidx.core.view.MenuProvider import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.recyclerview.widget.RecyclerView import androidx.work.WorkInfo import com.google.android.flexbox.FlexDirection import com.google.android.flexbox.FlexboxLayoutManager import com.google.android.flexbox.JustifyContent import it.reyboz.bustorino.R import it.reyboz.bustorino.adapters.RouteAdapter import it.reyboz.bustorino.adapters.RouteOnlyLineAdapter import it.reyboz.bustorino.adapters.StringListAdapter import it.reyboz.bustorino.backend.utils import it.reyboz.bustorino.data.DBUpdateWorker import it.reyboz.bustorino.data.PreferencesHolder import it.reyboz.bustorino.data.gtfs.GtfsRoute import it.reyboz.bustorino.middleware.AutoFitGridLayoutManager import it.reyboz.bustorino.util.LinesNameSorter import it.reyboz.bustorino.util.ViewUtils import it.reyboz.bustorino.viewmodels.LinesGridShowingViewModel class LinesGridShowingFragment : ScreenBaseFragment() { private val viewModel: LinesGridShowingViewModel by viewModels() //private lateinit var gridLayoutManager: AutoFitGridLayoutManager private lateinit var favoritesRecyclerView: RecyclerView private lateinit var urbanRecyclerView: RecyclerView private lateinit var extraurbanRecyclerView: RecyclerView private lateinit var touristRecyclerView: RecyclerView private lateinit var favoritesTitle: TextView private lateinit var urbanLinesTitle: TextView private lateinit var extrurbanLinesTitle: TextView private lateinit var touristLinesTitle: TextView private lateinit var updateMessageTextView: TextView //private lateinit var searchBar: SearchView private var routesByAgency = HashMap>() /*hashMapOf( AG_URBAN to ArrayList(), AG_EXTRAURB to ArrayList(), AG_TOUR to ArrayList() )*/ private lateinit var fragmentListener: CommonFragmentListener private val linesNameSorter = LinesNameSorter() private val linesComparator = Comparator { a,b -> return@Comparator linesNameSorter.compare(a.shortName, b.shortName) } private val linesPriorityComparator = Comparator> { pa, pb -> if (pa.second != pb.second){ return@Comparator pa.second - pb.second } else{ return@Comparator linesNameSorter.compare(pa.first.shortName, pb.first.shortName) } } private val routeClickListener = RouteAdapter.ItemClicker { - fragmentListener.openLineFromStop(it.gtfsId, null) + //fragmentListener.openLineFromStop(it.gtfsId, null) + openLine(it) } private val arrows = HashMap() private val durations = HashMap() //private val recyclerViewAdapters= HashMap() private val lastQueryEmptyForAgency = HashMap(3) private var openRecyclerView = "AG_URBAN" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val rootView = inflater.inflate(R.layout.fragment_lines_grid, container, false) favoritesRecyclerView = rootView.findViewById(R.id.favoritesRecyclerView) urbanRecyclerView = rootView.findViewById(R.id.urbanLinesRecyclerView) extraurbanRecyclerView = rootView.findViewById(R.id.extraurbanLinesRecyclerView) touristRecyclerView = rootView.findViewById(R.id.touristLinesRecyclerView) updateMessageTextView = rootView.findViewById(R.id.updateMessageTextView) favoritesTitle = rootView.findViewById(R.id.favoritesTitleView) urbanLinesTitle = rootView.findViewById(R.id.urbanLinesTitleView) extrurbanLinesTitle = rootView.findViewById(R.id.extraurbanLinesTitleView) touristLinesTitle = rootView.findViewById(R.id.touristLinesTitleView) arrows[AG_URBAN] = rootView.findViewById(R.id.arrowUrb) arrows[AG_TOUR] = rootView.findViewById(R.id.arrowTourist) arrows[AG_EXTRAURB] = rootView.findViewById(R.id.arrowExtraurban) arrows[AG_FAV] = rootView.findViewById(R.id.arrowFavorites) //show urban expanded by default val recViews = listOf(urbanRecyclerView, extraurbanRecyclerView, touristRecyclerView) for (recyView in recViews) { val gridLayoutManager = AutoFitGridLayoutManager( requireContext().applicationContext, (utils.convertDipToPixels(context, COLUMN_WIDTH_DP.toFloat())).toInt() ) recyView.layoutManager = gridLayoutManager } //init favorites recyclerview favoritesRecyclerView.layoutManager = getFlexLayoutManager(requireContext()) viewModel.getLinesLiveData().observe(viewLifecycleOwner){ rL -> routesByAgency.clear() for (k in AGENCIES){ routesByAgency[k] = ArrayList() } val routesPrioByAg = HashMap>>() for (ag in AGENCIES){ routesPrioByAg[ag] = ArrayList() } for(p in rL){ val route = p.first val agency = route.agencyID if(agency !in routesByAgency.keys){ Log.e(DEBUG_TAG, "The agency $agency for route ${p.first.gtfsId} is not in the predefined agencies (${routesByAgency.keys})") } routesByAgency[agency]?.add(route) routesPrioByAg[agency]?.add(p) // I would print a debug here, but it's the same as above } //zip agencies and recyclerviews AGENCIES.zip(recViews) { ag, recView -> routesPrioByAg[ag]?.let { routePrioList -> if (routePrioList.isNotEmpty()) { routePrioList.sortWith(linesPriorityComparator) val adapter = RouteAdapter(routePrioList.map { it.first }, routeClickListener) val lastQueryEmpty = if(ag in lastQueryEmptyForAgency.keys) lastQueryEmptyForAgency[ag]!! else true if (lastQueryEmpty) recView.adapter = adapter else recView.swapAdapter(adapter, false) lastQueryEmptyForAgency[ag] = false } else { val messageString = if(viewModel.getLineQueryValue().isNotEmpty()) getString(R.string.no_lines_found_query) else getString(R.string.no_lines_found) val extraAdapter = StringListAdapter(listOf(messageString)) recView.adapter = extraAdapter lastQueryEmptyForAgency[ag] = true } durations[ag] = if(routePrioList.size < 20) ViewUtils.DEF_DURATION else 1000 } } } //onClicks urbanLinesTitle.setOnClickListener { openLinesAndCloseOthersIfNeeded(AG_URBAN) } extrurbanLinesTitle.setOnClickListener { openLinesAndCloseOthersIfNeeded(AG_EXTRAURB) } touristLinesTitle.setOnClickListener { openLinesAndCloseOthersIfNeeded(AG_TOUR) } favoritesTitle.setOnClickListener { closeOpenFavorites() } arrows[AG_FAV]?.setOnClickListener { closeOpenFavorites() } //arrows onClicks for(k in Companion.AGENCIES){ //k is either AG_TOUR, AG_EXTRAURBAN, AG_URBAN arrows[k]?.setOnClickListener { openLinesAndCloseOthersIfNeeded(k) } } // watch for the db update DBUpdateWorker.getWorkInfoLiveData(requireContext()).observe(viewLifecycleOwner){ workInfoList -> if (workInfoList == null || workInfoList.isEmpty()) { return@observe } var showProgress = false for (workInfo in workInfoList) { if (workInfo.state == WorkInfo.State.RUNNING) { updateMessageTextView.visibility = View.VISIBLE } else{ updateMessageTextView.visibility = View.GONE } break } } return rootView } fun setUserSearch(textSearch:String){ viewModel.setLineQuery(textSearch) } + fun openLine(route: GtfsRoute){ + fragmentListener.openLineFromStop(route.gtfsId, null) + } + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val menuHost: MenuHost = requireActivity() viewModel.favoritesLines.observe(viewLifecycleOwner){ routes-> val routesNames = routes.map { it.shortName } //create new item click listener every time val adapter = RouteOnlyLineAdapter(routesNames){ pos, _ -> val r = routes[pos] - fragmentListener.openLineFromStop(r.gtfsId, null) + //fragmentListener.openLineFromStop(r.gtfsId, null) + openLine(r) } favoritesRecyclerView.adapter = adapter } // Add menu items without using the Fragment Menu APIs // Note how we can tie the MenuProvider to the viewLifecycleOwner // and an optional Lifecycle.State (here, RESUMED) to indicate when // the menu should be visible menuHost.addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { // Add menu items here menuInflater.inflate(R.menu.menu_search, menu) val search = menu.findItem(R.id.searchMenuItem).actionView as SearchView search.setOnQueryTextListener(object : SearchView.OnQueryTextListener{ override fun onQueryTextSubmit(query: String?): Boolean { setUserSearch(query ?: "") return true } override fun onQueryTextChange(query: String?): Boolean { setUserSearch(query ?: "") return true } }) search.queryHint = getString(R.string.search_box_lines_suggestion_filter) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { // Handle the menu selection if (menuItem.itemId == R.id.searchMenuItem){ Log.d(DEBUG_TAG, "Clicked on search menu") } else{ Log.d(DEBUG_TAG, "Clicked on something else") } return false } }, viewLifecycleOwner, Lifecycle.State.RESUMED) } private fun closeOpenFavorites(){ if(favoritesRecyclerView.visibility == View.VISIBLE){ //close it favoritesRecyclerView.visibility = View.GONE setOpen(arrows[AG_FAV]!!, false) viewModel.favoritesExpanded.value = false } else{ favoritesRecyclerView.visibility = View.VISIBLE setOpen(arrows[AG_FAV]!!, true) viewModel.favoritesExpanded.value = true } } private fun openLinesAndCloseOthersIfNeeded(agency: String){ if(openRecyclerView!="" && openRecyclerView!= agency) { switchRecyclerViewStatus(openRecyclerView) } switchRecyclerViewStatus(agency) } private fun switchRecyclerViewStatus(agency: String){ val recyclerView = when(agency){ AG_TOUR -> touristRecyclerView AG_EXTRAURB -> extraurbanRecyclerView AG_URBAN -> urbanRecyclerView else -> throw IllegalArgumentException("$DEBUG_TAG: Agency Invalid") } val expandedLiveData = when(agency){ AG_TOUR -> viewModel.isTouristExpanded AG_URBAN -> viewModel.isUrbanExpanded AG_EXTRAURB -> viewModel.isExtraUrbanExpanded else -> throw IllegalArgumentException("$DEBUG_TAG: Agency Invalid") } val duration = durations[agency] val arrow = arrows[agency] val durArrow = if(duration == null || duration==ViewUtils.DEF_DURATION) 500 else duration if(duration!=null&&arrow!=null) when (recyclerView.visibility){ View.GONE -> { Log.d(DEBUG_TAG, "Open recyclerview $agency") //val a =ViewUtils.expand(recyclerView, duration, 0) recyclerView.visibility = View.VISIBLE expandedLiveData.value = true Log.d(DEBUG_TAG, "Arrow for $agency has rotation: ${arrow.rotation}") setOpen(arrow, true) //arrow.startAnimation(rotateArrow(true,durArrow)) openRecyclerView = agency } View.VISIBLE -> { Log.d(DEBUG_TAG, "Close recyclerview $agency") //ViewUtils.collapse(recyclerView, duration) recyclerView.visibility = View.GONE expandedLiveData.value = false //arrow.rotation = 90f Log.d(DEBUG_TAG, "Arrow for $agency has rotation ${arrow.rotation} pre-rotate") setOpen(arrow, false) //arrow.startAnimation(rotateArrow(false,durArrow)) openRecyclerView = "" } View.INVISIBLE -> { TODO() } } } override fun onAttach(context: Context) { super.onAttach(context) if(context is CommonFragmentListener){ fragmentListener = context } else throw RuntimeException("$context must implement CommonFragmentListener") } override fun getBaseViewForSnackBar(): View? { return null } override fun onResume() { super.onResume() val pref = PreferencesHolder.getMainSharedPreferences(requireContext()) val res = pref.getStringSet(PreferencesHolder.PREF_FAVORITE_LINES, HashSet()) res?.let { viewModel.setFavoritesLinesIDs(HashSet(it))} //restore state viewModel.favoritesExpanded.value?.let { if(!it){ //close it favoritesRecyclerView.visibility = View.GONE setOpen(arrows[AG_FAV]!!, false) } else{ favoritesRecyclerView.visibility = View.VISIBLE setOpen(arrows[AG_FAV]!!, true) } } viewModel.isUrbanExpanded.value?.let { if(it) { urbanRecyclerView.visibility = View.VISIBLE arrows[AG_URBAN]?.rotation= 90f openRecyclerView = AG_URBAN Log.d(DEBUG_TAG, "RecyclerView gtt:U is expanded") } else { urbanRecyclerView.visibility = View.GONE arrows[AG_URBAN]?.rotation= 0f } } viewModel.isTouristExpanded.value?.let { val recview = touristRecyclerView if(it) { recview.visibility = View.VISIBLE arrows[AG_TOUR]?.rotation=90f openRecyclerView = AG_TOUR } else { recview.visibility = View.GONE arrows[AG_TOUR]?.rotation= 0f } } viewModel.isExtraUrbanExpanded.value?.let { val recview = extraurbanRecyclerView if(it) { openRecyclerView = AG_EXTRAURB recview.visibility = View.VISIBLE arrows[AG_EXTRAURB]?.rotation=90f } else { recview.visibility = View.GONE arrows[AG_EXTRAURB]?.rotation=0f } } fragmentListener.readyGUIfor(FragmentKind.LINES) } companion object { private const val COLUMN_WIDTH_DP=250 private const val AG_FAV = "fav" private const val AG_URBAN = "gtt:U" private const val AG_EXTRAURB ="gtt:E" private const val AG_TOUR ="gtt:T" private const val DEBUG_TAG ="BusTO-LinesGridFragment" const val FRAGMENT_TAG = "LinesGridShowingFragment" private val AGENCIES = listOf(AG_URBAN, AG_EXTRAURB, AG_TOUR) fun newInstance() = LinesGridShowingFragment() @JvmStatic fun setOpen(imageView: ImageView, value: Boolean){ if(value) imageView.rotation = 90f else imageView.rotation = 0f } @JvmStatic fun rotateArrow(toOpen: Boolean, duration: Long): RotateAnimation{ val start = if (toOpen) 0f else 90f val stop = if(toOpen) 90f else 0f Log.d(DEBUG_TAG, "Rotate arrow from $start to $stop") val rotate = RotateAnimation(start, stop, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f) rotate.duration = duration rotate.interpolator = LinearInterpolator() //rotate.fillAfter = true rotate.fillBefore = false return rotate } } } \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt index 1478be5..6e02307 100644 --- a/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt +++ b/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt @@ -1,681 +1,682 @@ /* BusTO - Fragments components Copyright (C) 2018 Fabio Mazza This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.fragments import android.annotation.SuppressLint import android.content.Context import android.location.Location import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.widget.AppCompatButton import androidx.core.util.Pair import androidx.fragment.app.viewModels import androidx.preference.PreferenceManager import androidx.recyclerview.widget.RecyclerView import androidx.work.WorkInfo import it.reyboz.bustorino.BuildConfig import it.reyboz.bustorino.R import it.reyboz.bustorino.adapters.ArrivalsStopAdapter import it.reyboz.bustorino.adapters.SquareStopAdapter import it.reyboz.bustorino.backend.* import it.reyboz.bustorino.data.DatabaseUpdate -import it.reyboz.bustorino.fragments.NearbyArrivalsDownloader.ArrivalsListener import it.reyboz.bustorino.middleware.AutoFitGridLayoutManager import it.reyboz.bustorino.middleware.FusedNativeLocationProvider import it.reyboz.bustorino.middleware.FusedNativeLocationProvider.LocationUpdateListener import it.reyboz.bustorino.util.Permissions.Companion.anyLocationPermissionsGranted import it.reyboz.bustorino.util.Permissions.Companion.bothLocationPermissionsGranted import it.reyboz.bustorino.util.StopSorterByDistance import it.reyboz.bustorino.viewmodels.NearbyStopsViewModel import java.util.* import kotlin.math.min class NearbyStopsFragment : ScreenBaseFragment() { override fun getBaseViewForSnackBar(): View? { return null } enum class FragType(val num: Int) { STOPS(1), ARRIVALS(2); companion object { @JvmStatic fun fromNum(i: Int): FragType { when (i) { 1 -> return STOPS 2 -> return ARRIVALS else -> throw IllegalArgumentException("type not recognized") } } } } private enum class LocationShowingStatus { SEARCHING, FIRST_FIX, DISABLED, NO_PERMISSION } private var mListener: FragmentListenerMain? = null private var fragment_type = FragType.STOPS private lateinit var gridRecyclerView: RecyclerView private var dataAdapter: SquareStopAdapter? = null private var gridLayoutManager: AutoFitGridLayoutManager? = null private var lastPosition: GPSPoint? = null private var circlingProgressBar: ProgressBar? = null private lateinit var flatProgressBar: ProgressBar //protected SharedPreferences globalSharedPref; //private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener; private var messageTextView: TextView? = null private var titleTextView: TextView? = null private var loadingTextView: TextView? = null private var scrollListener: CommonScrollListener? = null private var switchButton: AppCompatButton? = null private var firstLocForStops = true private var firstLocForArrivals = true private var stopsMaxDistance = -3 private var stopsMinNumber = -1 //These are useful for the case of nearby arrivals - private var arrivalsManager: NearbyArrivalsDownloader? = null private var arrivalsStopAdapter: ArrivalsStopAdapter? = null private var currentNearbyStops = ArrayList() private var showingStatus = LocationShowingStatus.NO_PERMISSION private var isLocationEnabled = false private val locationUpdateListener: LocationUpdateListener = object : LocationUpdateListener { override fun onLocationUpdate(location: Location) { updateLocationViewModel(location) } override fun onFusedStatusChanged(isEnabled: Boolean) { Log.d(DEBUG_TAG, "Location provider is enabled: " + isEnabled) isLocationEnabled = isEnabled if (isEnabled) { setShowingStatus(LocationShowingStatus.SEARCHING) } else { setShowingStatus(LocationShowingStatus.DISABLED) } } } - private val locationOptionsArrivals = FusedNativeLocationProvider.Options(5 * 1000L, 50f) + // Two different settings for the location provider + private val locationOptionsArrivals = FusedNativeLocationProvider.Options(5 * 1000L, 25f) private val locationOptionsStops = FusedNativeLocationProvider.Options(1000L, 5f) - - /* - TODO: we do not request the permission in this fragment, only showing it when we have the location. Request position if this changes. - private final ActivityResultLauncher permissionsResultLauncher = getPositionRequestLauncher( - granted ->{ - - } - ); - */ private var locationProvider: FusedNativeLocationProvider? = null /*private val arrivalsListener: ArrivalsListener = object : ArrivalsListener { override fun setProgress(completedRequests: Int, pendingRequests: Int) { if (pendingRequests == 0) { flatProgressBar.setIndeterminate(true) flatProgressBar.setVisibility(View.GONE) } else { flatProgressBar.setIndeterminate(false) flatProgressBar.progress = completedRequests } } /*override fun onAllRequestsCancelled() { if (flatProgressBar != null) flatProgressBar!!.setVisibility(View.GONE) } */ override fun showCompletedArrivals(completedPalinas: ArrayList) { showArrivalsInRecycler(completedPalinas) } } */ //ViewModel private val viewModel : NearbyStopsViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let{ setFragmentType(FragType.fromNum(it.getInt(FRAGMENT_TYPE_KEY))) } //locManager = (LocationManager) requireContext().getSystemService(Context.LOCATION_SERVICE); //fragmentLocationListener = new FragmentLocationListener(); if (getContext() != null) { //globalSharedPref = getContext().getSharedPreferences(getString(R.string.mainSharedPreferences), Context.MODE_PRIVATE); //globalSharedPref.registerOnSharedPreferenceChangeListener(preferenceChangeListener); } //NearbyArrivalsDownloader nearbyArrivalsDownloader = new NearbyArrivalsDownloader(getContext().getApplicationContext(), arrivalsListener); locationProvider = FusedNativeLocationProvider(requireContext()) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment if (getContext() == null) throw RuntimeException() val root = inflater.inflate(R.layout.fragment_nearby_stops, container, false) gridRecyclerView = root.findViewById(R.id.stopGridRecyclerView) gridLayoutManager = AutoFitGridLayoutManager( requireContext().getApplicationContext(), utils.convertDipToPixels(getContext(), COLUMN_WIDTH_DP.toFloat()).toInt() ) gridRecyclerView.setLayoutManager(gridLayoutManager) gridRecyclerView.setHasFixedSize(false) circlingProgressBar = root.findViewById(R.id.circularProgressBar) flatProgressBar = root.findViewById(R.id.horizontalProgressBar) messageTextView = root.findViewById(R.id.messageTextView) titleTextView = root.findViewById(R.id.titleTextView) loadingTextView = root.findViewById(R.id.positionLoadingTextView) switchButton = root.findViewById(R.id.switchButton) scrollListener = CommonScrollListener(mListener, false) switchButton!!.setOnClickListener(View.OnClickListener { v: View? -> switchFragmentType() }) if (BuildConfig.DEBUG) Log.d(DEBUG_TAG, "onCreateView") val appContext = requireContext().applicationContext DatabaseUpdate.watchUpdateWorkStatus(context, this){ workInfos -> if (workInfos.isEmpty()) { viewModel.setDBUpdateRunning(false) return@watchUpdateWorkStatus } val wi = workInfos.get(0) if (wi.state == WorkInfo.State.RUNNING && locationProvider!!.isRunning()) { locationProvider!!.stopUpdates() viewModel.setDBUpdateRunning(true) } else { //start the request if (bothLocationPermissionsGranted(requireContext())) { if (!locationProvider!!.isRunning()) { startLocationUpdatesByType() } } else { setShowingStatus(LocationShowingStatus.NO_PERMISSION) } viewModel.setDBUpdateRunning(false) //actually restart request } } if (anyLocationPermissionsGranted(appContext)) { setShowingStatus(LocationShowingStatus.SEARCHING) } else { setShowingStatus(LocationShowingStatus.NO_PERMISSION) } //add location listener locationProvider!!.addListener(locationUpdateListener) return root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) gridRecyclerView.setVisibility(View.INVISIBLE) gridRecyclerView.addOnScrollListener(scrollListener!!) - mListener?.readyGUIfor(FragmentKind.NEARBY_STOPS) + //mListener?.readyGUIfor(FragmentKind.NEARBY_STOPS) //observe the livedata viewModel.stopsAtDistance.observe(getViewLifecycleOwner()) {stops -> Log.d(DEBUG_TAG, "Received " + stops.size + " stops nearby") var distance = viewModel.distanceMtLiveData.getValue() if (distance == null) { distance = 40 } if ((stops.size < stopsMinNumber && distance <= stopsMaxDistance)) { viewModel.setDistance(distance + 40) //viewModel.requestStopsAtDistance(distance, true); //Log.d(DEBUG_TAG, "Doubling distance now!"); return@observe // THIS WORKS AS AN `else` } if (!stops.isEmpty()) { currentNearbyStops = stops showStopsInViews(currentNearbyStops, lastPosition) } } viewModel.downloadingArrivals.observe(viewLifecycleOwner){ running -> if(!running) flatProgressBar.visibility = View.GONE else flatProgressBar.visibility = View.VISIBLE } viewModel.progressPerc.observe(viewLifecycleOwner){ progress -> flatProgressBar.isIndeterminate = false flatProgressBar.progress = progress flatProgressBar.max = 100 if (progress<100){ flatProgressBar.visibility = View.VISIBLE } } viewModel.arrivalsDecoupled.observe(viewLifecycleOwner){ stoprouteList -> if (getContext() == null) { Log.e(DEBUG_TAG, "Trying to show arrivals in Recycler but we're not attached") return@observe } if (firstLocForArrivals) { - arrivalsStopAdapter = ArrivalsStopAdapter(stoprouteList, mListener, getContext(), lastPosition!!) + arrivalsStopAdapter = ArrivalsStopAdapter(stoprouteList, mListener, context, lastPosition!!) gridRecyclerView.setAdapter(arrivalsStopAdapter) firstLocForArrivals = false } else { - arrivalsStopAdapter!!.setRoutesPairListAndPosition(stoprouteList) + arrivalsStopAdapter!!.setRoutesPairListAndPosition(stoprouteList, lastPosition) } //arrivalsStopAdapter.notifyDataSetChanged(); showRecyclerHidingLoadMessage() - if (mListener != null) mListener!!.readyGUIfor(FragmentKind.NEARBY_ARRIVALS) + //if (mListener != null) mListener!!.readyGUIfor(FragmentKind.NEARBY_ARRIVALS) } } /** * Internal bit used to start location updates */ private fun startLocationUpdatesByType() { when (fragment_type) { FragType.STOPS -> locationProvider!!.startUpdates(locationOptionsStops) FragType.ARRIVALS -> locationProvider!!.startUpdates(locationOptionsArrivals) } } /** * Use this method to set the fragment type * @param type the type, TYPE_ARRIVALS or TYPE_STOPS */ private fun setFragmentType(type: FragType) { val isChanged = fragment_type != type this.fragment_type = type /*switch(type){ case ARRIVALS: TIME_INTERVAL_REQUESTS = 5*1000; break; case STOPS: TIME_INTERVAL_REQUESTS = 1000; } */ if (isChanged) { startLocationUpdatesByType() setShowingStatus(LocationShowingStatus.SEARCHING) } } /** * Set the location in the view model if it is good * @param location new location */ private fun updateLocationViewModel(location: Location, accuracy: Float = 150f) { if (location.getAccuracy() < accuracy) { lastPosition = GPSPoint(location.getLatitude(), location.getLongitude()) //viewModel.requestStopsAtDistance(location.getLatitude(), location.getLongitude(), distance, true); viewModel.setLastLocation(location) } } private fun setShowingStatus(newStatus: LocationShowingStatus) { var newStatus = newStatus if (BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Asked to set showing status : $newStatus") if (newStatus == showingStatus) { return } if (!isLocationEnabled && newStatus != LocationShowingStatus.NO_PERMISSION) { Log.d(DEBUG_TAG, "asked to show status: $newStatus but the position is disabled") newStatus = LocationShowingStatus.DISABLED } when (newStatus) { LocationShowingStatus.FIRST_FIX -> { circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) gridRecyclerView.setVisibility(View.VISIBLE) messageTextView!!.setVisibility(View.GONE) } LocationShowingStatus.NO_PERMISSION -> { circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) messageTextView!!.setText(R.string.enable_position_message_nearby) messageTextView!!.setVisibility(View.VISIBLE) } LocationShowingStatus.DISABLED -> { //if (showingStatus== LocationShowingStatus.SEARCHING){ circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) //} messageTextView!!.setText(R.string.enable_location_message) messageTextView!!.setVisibility(View.VISIBLE) } LocationShowingStatus.SEARCHING -> { circlingProgressBar!!.setVisibility(View.VISIBLE) loadingTextView!!.setVisibility(View.VISIBLE) gridRecyclerView.setVisibility(View.GONE) messageTextView!!.setVisibility(View.GONE) } } showingStatus = newStatus } override fun onAttach(context: Context) { super.onAttach(context) if (context is FragmentListenerMain) { mListener = context as FragmentListenerMain } else { throw RuntimeException( context .toString() + " must implement OnFragmentInteractionListener" ) } Log.d(DEBUG_TAG, "OnAttach called") //viewModel = ViewModelProvider(this).get(NearbyStopsViewModel::class.java) } override fun onPause() { super.onPause() //gridRecyclerView.setAdapter(null) Log.d(DEBUG_TAG, "On paused called") locationProvider!!.stopUpdates() } override fun onResume() { super.onResume() //fix view if we were showing the stops or the arrivals prepareForFragmentType() when (fragment_type) { FragType.STOPS -> if (dataAdapter != null) { //gridRecyclerView.setAdapter(dataAdapter); circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) } FragType.ARRIVALS -> if (arrivalsStopAdapter != null) { //gridRecyclerView.setAdapter(arrivalsStopAdapter); circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) } } mListener!!.enableRefreshLayout(false) Log.d(DEBUG_TAG, "OnResume called") if (getContext() == null) { Log.e(DEBUG_TAG, "NULL CONTEXT, everything is going to crash now") stopsMinNumber = 5 stopsMaxDistance = 600 return } //Re-read preferences val shpr = PreferenceManager.getDefaultSharedPreferences(requireContext().getApplicationContext()) //For some reason, they are all saved as strings stopsMaxDistance = shpr.getInt(getString(R.string.pref_key_radius_recents), 600) var isMinStopInt = true try { stopsMinNumber = shpr.getInt(getString(R.string.pref_key_num_recents), 5) } catch (ex: ClassCastException) { isMinStopInt = false } if (!isMinStopInt) try { stopsMinNumber = shpr.getString(getString(R.string.pref_key_num_recents), "5")!!.toInt() } catch (ex: NumberFormatException) { stopsMinNumber = 5 } if (BuildConfig.DEBUG) Log.d( DEBUG_TAG, "Max distance for stops: $stopsMaxDistance, Min number of stops: $stopsMinNumber" ) if (!locationProvider!!.isRunning()) { startLocationUpdatesByType() } } override fun onDetach() { super.onDetach() mListener = null - if (arrivalsManager != null) arrivalsManager!!.cancelAllRequests() + //if (arrivalsManager != null) arrivalsManager!!.cancelAllRequests() } /** * Display the stops, or run new set of requests for arrivals */ private fun showStopsInViews(stops: ArrayList, location: GPSPoint?) { if (stops.isEmpty()) { setNoStopsLayout() return } if (location == null) { // we could do something better, but it's better to do this for now return } /*var minDistance = Double.POSITIVE_INFINITY for (s in stops) { minDistance = min(minDistance, s.getDistanceFromLocation(location.getLatitude(), location.getLongitude())) } */ //quick trial to hopefully always get the stops in the correct order Collections.sort(stops, StopSorterByDistance(location)) when (fragment_type) { FragType.STOPS -> showStopsInRecycler(stops) FragType.ARRIVALS -> { //don't do anything if we're not attached /*context?.let{ if (arrivalsManager == null) arrivalsManager = NearbyArrivalsDownloader(it.applicationContext, arrivalsListener) arrivalsManager!!.requestArrivalsForStops(stops) } */ viewModel.requestArrivalsForStops(stops) } } } /** * To enable targeting from the Button */ fun switchFragmentType(v: View?) { switchFragmentType() } /** * Call when you need to switch the type of fragment */ private fun switchFragmentType() { when (fragment_type) { FragType.ARRIVALS -> setFragmentType(FragType.STOPS) FragType.STOPS -> setFragmentType(FragType.ARRIVALS) else -> {} } prepareForFragmentType() //locManager.removeLocationRequestFor(fragmentLocationListener); //locManager.addLocationRequestFor(fragmentLocationListener); if (lastPosition != null) { // we have at least one fix on the position showStopsInViews(currentNearbyStops, lastPosition) } } /** * Prepare the views for the set fragment type */ private fun prepareForFragmentType() { if (fragment_type == FragType.STOPS) { - switchButton!!.setText(getString(R.string.show_arrivals)) - titleTextView!!.setText(getString(R.string.nearby_stops_message)) - if (arrivalsManager != null) arrivalsManager!!.cancelAllRequests() - if (dataAdapter != null) gridRecyclerView!!.setAdapter(dataAdapter) + switchButton!!.text = getString(R.string.show_arrivals) + titleTextView!!.text = getString(R.string.nearby_stops_message) + + dataAdapter?.let{ gridRecyclerView.adapter = it} + + mListener?.readyGUIfor(FragmentKind.NEARBY_STOPS) + } else if (fragment_type == FragType.ARRIVALS) { - titleTextView!!.setText(getString(R.string.nearby_arrivals_message)) - switchButton!!.setText(getString(R.string.show_stops)) - if (arrivalsStopAdapter != null) gridRecyclerView!!.setAdapter(arrivalsStopAdapter) + titleTextView!!.text = getString(R.string.nearby_arrivals_message) + switchButton!!.text = getString(R.string.show_stops) + val arrivalsSorted = viewModel.arrivalsDecoupled.value + arrivalsSorted?.let{ + lastPosition?.let{pos -> + arrivalsStopAdapter = ArrivalsStopAdapter(it,mListener,requireContext(), pos ) + } + } + arrivalsStopAdapter?.let{ + gridRecyclerView.setAdapter(it) + } + + mListener?.readyGUIfor(FragmentKind.NEARBY_ARRIVALS) } } //useful methods /**//// GUI METHODS //////// */ private fun showStopsInRecycler(stops: MutableList?) { - if (firstLocForStops) { + if (dataAdapter == null) { dataAdapter = SquareStopAdapter(stops, mListener, lastPosition) gridRecyclerView!!.setAdapter(dataAdapter) firstLocForStops = false } else { - dataAdapter!!.setStops(stops) dataAdapter!!.setUserPosition(lastPosition) + dataAdapter!!.setStops(stops) } - dataAdapter!!.notifyDataSetChanged() //showRecyclerHidingLoadMessage(); if (gridRecyclerView!!.getVisibility() != View.VISIBLE) { circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) gridRecyclerView!!.setVisibility(View.VISIBLE) } messageTextView!!.setVisibility(View.GONE) - if (mListener != null) mListener!!.readyGUIfor(FragmentKind.NEARBY_STOPS) } private fun showArrivalsInRecycler(routesPairList: List>) { } private fun setNoStopsLayout() { messageTextView!!.setVisibility(View.VISIBLE) messageTextView!!.setText(R.string.no_stops_nearby) circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) } /** * Does exactly what is says on the tin */ private fun showRecyclerHidingLoadMessage() { if (gridRecyclerView.getVisibility() != View.VISIBLE) { circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) gridRecyclerView.setVisibility(View.VISIBLE) } messageTextView!!.setVisibility(View.GONE) } /* * Local locationListener, to use for the GPS */ /* class FragmentLocationListener implements LocationListenerCompat { private long lastUpdateTime = -1; public boolean isRegistered = false; @Override public void onLocationChanged(@NonNull Location location) { if(viewModel==null){ return; } if(location.getAccuracy()<200) { lastPosition = new GPSPoint(location.getLatitude(), location.getLongitude()); //viewModel.requestStopsAtDistance(location.getLatitude(), location.getLongitude(), distance, true); viewModel.setLastLocation(location); } lastUpdateTime = System.currentTimeMillis(); //Log.d("BusTO:NearPositListen","can start request for stops: "+ !dbUpdateRunning); } @Override public void onProviderEnabled(@NonNull String provider) { Log.d(DEBUG_TAG, "Location provider "+provider+" enabled"); if(provider.equals(LocationManager.GPS_PROVIDER)){ setShowingStatus(LocationShowingStatus.SEARCHING); } } @Override public void onProviderDisabled(@NonNull String provider) { Log.d(DEBUG_TAG, "Location provider "+provider+" disabled"); if(provider.equals(LocationManager.GPS_PROVIDER)) { setShowingStatus(LocationShowingStatus.DISABLED); } } @Override public void onStatusChanged(@NonNull String provider, int status, @Nullable Bundle extras) { LocationListenerCompat.super.onStatusChanged(provider, status, extras); } } */ companion object { private const val DEBUG_TAG = "NearbyStopsFragment" private const val FRAGMENT_TYPE_KEY = "FragmentType" const val FRAGMENT_TAG: String = "NearbyStopsFrag" const val COLUMN_WIDTH_DP: Int = 250 /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment NearbyStopsFragment. */ @JvmStatic fun newInstance(type: FragType): NearbyStopsFragment { //if(fragmentType != TYPE_STOPS && fragmentType != TYPE_ARRIVALS ) // throw new IllegalArgumentException("WRONG KIND OF FRAGMENT USED"); val fragment = NearbyStopsFragment() val args = Bundle(1) args.putInt(FRAGMENT_TYPE_KEY, type.num) fragment.setArguments(args) return fragment } } } diff --git a/app/src/main/java/it/reyboz/bustorino/viewmodels/LinesGridShowingViewModel.kt b/app/src/main/java/it/reyboz/bustorino/viewmodels/LinesGridShowingViewModel.kt index 431416d..16eb930 100644 --- a/app/src/main/java/it/reyboz/bustorino/viewmodels/LinesGridShowingViewModel.kt +++ b/app/src/main/java/it/reyboz/bustorino/viewmodels/LinesGridShowingViewModel.kt @@ -1,94 +1,98 @@ package it.reyboz.bustorino.viewmodels import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.map import it.reyboz.bustorino.data.GtfsRepository import it.reyboz.bustorino.data.gtfs.GtfsDatabase import it.reyboz.bustorino.data.gtfs.GtfsRoute import it.reyboz.bustorino.util.LinesNameSorter class LinesGridShowingViewModel(application: Application) : AndroidViewModel(application) { private val linesNameSorter = LinesNameSorter() private val linesComparator = Comparator { a,b -> return@Comparator linesNameSorter.compare(a.shortName, b.shortName) } private val gtfsRepo: GtfsRepository private val routesLiveData: LiveData> //= gtfsRepo.getAllRoutes() val isUrbanExpanded = MutableLiveData(true) val isExtraUrbanExpanded = MutableLiveData(false) val isTouristExpanded = MutableLiveData(false) val favoritesExpanded = MutableLiveData(true) - val favoritesLinesIDs = MutableLiveData>() + val favoritesLinesIDs = MutableLiveData>() private val queryLiveData = MutableLiveData("") fun setLineQuery(query: String){ if(query!=queryLiveData.value) queryLiveData.value = query } fun getLineQueryValue():String{ return queryLiveData.value ?: "" } private val filteredLinesLiveData = MediatorLiveData>>() fun getLinesLiveData() = filteredLinesLiveData private fun filterLinesForQuery(lines: List, query: String): ArrayList>{ var result= lines.filter { r-> query.lowercase() in r.shortName.lowercase() } //EXCLUDE gtt:F - ferrovie (luckily, gtt does not run rail service anymore) result = result.filter { r -> r.agencyID != "gtt:F" } val out = ArrayList>() for (r in result){ out.add(Pair(r,1)) } // add those matching the query in the description for (r: GtfsRoute in lines) { if (query.lowercase() in r.description.lowercase()) { if (r !in result){ out.add(Pair(r,2)) } } } return out } init { gtfsRepo = GtfsRepository(application) routesLiveData = gtfsRepo.getAllRoutes() filteredLinesLiveData.addSource(routesLiveData){ filteredLinesLiveData.value = filterLinesForQuery(it,queryLiveData.value ?: "" ) } filteredLinesLiveData.addSource(queryLiveData){ routesLiveData.value?.let { routes -> filteredLinesLiveData.value = filterLinesForQuery(routes, it) } } } fun setFavoritesLinesIDs(linesIds: HashSet){ - favoritesLinesIDs.value = linesIds - } + val sameSet = favoritesLinesIDs.value?.let{ + linesIds.containsAll(it) && it.containsAll(linesIds) + } ?: false + if(!sameSet)// trigger LiveData + favoritesLinesIDs.value = linesIds.toSet() + } val favoritesLines = favoritesLinesIDs.map {lineIds -> val linesList = ArrayList() if (lineIds.size == 0 || routesLiveData.value==null) return@map linesList for(line in routesLiveData.value!!){ if(lineIds.contains(line.gtfsId)) linesList.add(line) } linesList.sortWith(linesComparator) return@map linesList } } \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/viewmodels/NearbyStopsViewModel.kt b/app/src/main/java/it/reyboz/bustorino/viewmodels/NearbyStopsViewModel.kt index 4eb4a5e..1a3bcbf 100644 --- a/app/src/main/java/it/reyboz/bustorino/viewmodels/NearbyStopsViewModel.kt +++ b/app/src/main/java/it/reyboz/bustorino/viewmodels/NearbyStopsViewModel.kt @@ -1,252 +1,354 @@ /* BusTO - View Model components Copyright (C) 2023 Fabio Mazza This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.viewmodels import android.app.Application import android.location.Location import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.map +import androidx.lifecycle.viewModelScope +import com.android.volley.Response import it.reyboz.bustorino.BuildConfig import it.reyboz.bustorino.backend.* +import it.reyboz.bustorino.backend.mato.MapiArrivalRequest import it.reyboz.bustorino.data.OldDataRepository -import it.reyboz.bustorino.fragments.NearbyArrivalsDownloader import it.reyboz.bustorino.util.StopSorterByDistance +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import java.util.* +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong +import kotlin.time.Duration.Companion.seconds class NearbyStopsViewModel(application: Application): AndroidViewModel(application) { private val executor = Executors.newFixedThreadPool(2) private val oldRepo = OldDataRepository(executor, application) val arrivalsNearby = MutableLiveData>() + // map of arrivals by stopID + private val arrivalsMapStopID = ConcurrentHashMap() + val progressPerc = MutableLiveData() val downloadingArrivals = MutableLiveData() - private val arrivalsListener = object : NearbyArrivalsDownloader.ArrivalsListener { + val lastTimeFinished = AtomicLong(0) + private var job : Job? = null + + /*private val arrivalsListener = object : NearbyArrivalsDownloader.ArrivalsListener { override fun setProgress(completedRequests: Int, pendingRequests: Int) { val totalReq = completedRequests + pendingRequests progressPerc.postValue( (completedRequests * 100) / totalReq ) if(pendingRequests == 0) downloadingArrivals.postValue(false) } override fun onAllRequestsCancelled() { downloadingArrivals.postValue(false) } override fun showCompletedArrivals(completedPalinas: ArrayList) { arrivalsNearby.postValue(completedPalinas) } } - private val nearbyArrivalsDownloader = NearbyArrivalsDownloader(application,arrivalsListener ) + */ - fun requestArrivalsForStops(stops: List) { - nearbyArrivalsDownloader.requestArrivalsForStops(stops) + //private val nearbyArrivalsDownloader = NearbyArrivalsDownloader(application,arrivalsListener ) + + private val volleyManager = NetworkVolleyManager.getInstance(application) + + /** + * Response listener for the requests + */ + private val responseListener = Response.Listener { p -> + val key = p.ID + arrivalsMapStopID[key] = p + + arrivalsNearby.postValue(arrivalsMapStopID.values.toList()) + + val c = completedRequests.incrementAndGet() + val r = runningRequests.decrementAndGet() + updateProgressPost(c,errorRequests.get(), totalReqs.get()) + if(r==0){ + setFinishedPost() + } + } + + /** + * Error listener for the requests + */ + private val errorListener = Response.ErrorListener { error -> + val e = errorRequests.incrementAndGet() + val r = runningRequests.decrementAndGet() + updateProgressPost(completedRequests.get(), e, totalReqs.get()) + if(r==0){ + setFinishedPost() + } + if(BuildConfig.DEBUG) Log.d(DEBUG_TAG,"query to palina, error "+ error.toString()) } + private fun setFinishedPost(){ + downloadingArrivals.postValue(false) + //val time = System.currentTimeMillis() + //lastTimeFinished.set(time) + job?.cancel() + job = viewModelScope.launch { + delay(30.seconds) + launch(Dispatchers.Main) { + Log.d(DEBUG_TAG, "Updating arrivals from job") + stopsAtDistance.value?.let { + requestArrivalsForStops(it) + } + } + } + } + + private val totalReqs = AtomicInteger(0) + private val completedRequests = AtomicInteger(0) + private val errorRequests = AtomicInteger(0) + private val runningRequests = AtomicInteger(0) + + /** + * Run new batch of requests + */ + fun requestArrivalsForStops(stops: List) { + //nearbyArrivalsDownloader.requestArrivalsForStops(stops) + if(runningRequests.get() > 0) { + volleyManager.requestQueue.cancelAll(REQUEST_TAG) + } + val currentDate = Date() + val timeRange = 3600 + val departures = 10 + totalReqs.set(stops.size) + runningRequests.set(stops.size) + completedRequests.set(0) + errorRequests.set(0) + arrivalsMapStopID.clear() + for (s in stops) { + val req = MapiArrivalRequest(s.ID, currentDate, timeRange, departures, responseListener, errorListener) + req.setTag(REQUEST_TAG) + volleyManager.addToRequestQueue(req) + } + downloadingArrivals.value = (true) + } + private fun updateProgressPost(completed: Int, error: Int, total: Int) { + val done = completed + error + progressPerc.postValue( (done * 100) / total ) + } + //// ------- LOCATION STUFF --------- val locationLiveData = MutableLiveData() val distanceMtLiveData = MutableLiveData(40) val stopsAtDistance = MediatorLiveData>() private val dbUpdateRunning = MutableLiveData(false) private val callback = OldDataRepository.Callback> { res -> if(res.isSuccess){ stopsAtDistance.postValue(res.result) if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Setting value of stops in bounding box") } } fun setLastLocation(location: Location) { locationLiveData.value = GPSPoint(location.latitude, location.longitude) } fun setDistance(distance: Int) { distanceMtLiveData.value = distance } fun setDBUpdateRunning(running: Boolean) { dbUpdateRunning.value = (running) } /** * Request stop in location [latitude], [longitude], at distance [distanceMeters] * If [saveValues] is true, store the position and the distance used */ fun requestStopsAtDistance(latitude: Double, longitude: Double, distanceMeters: Int, saveValues: Boolean){ if(saveValues){ locationLiveData.postValue(GPSPoint(latitude, longitude)) distanceMtLiveData.postValue(distanceMeters) } oldRepo.requestStopsWithinDistance(latitude, longitude, distanceMeters, callback) } /** * Request stops using the previously saved location */ fun requestStopsAtDistance(distanceMeters: Int, saveValue: Boolean){ if(saveValue){ distanceMtLiveData.postValue(distanceMeters) } oldRepo.requestStopsWithinDistance( locationLiveData.value!!.latitude, locationLiveData.value!!.longitude, distanceMeters, callback) } fun requestStopsCheckDBRunning(position: GPSPoint, distanceMt: Int){ if(dbUpdateRunning.value==null || !(dbUpdateRunning.value!!)){ oldRepo.requestStopsWithinDistance(position.latitude, position.longitude, distanceMt, callback) } else{ Log.d(DEBUG_TAG, "Database update is running, cannot do it") } } fun postLocation(location: Location){ locationLiveData.postValue(GPSPoint(location.latitude, location.longitude)) } fun postLocation(location: GPSPoint){ locationLiveData.postValue(location) } fun postLastDistance(distanceMeters: Int){ distanceMtLiveData.postValue(distanceMeters) } init { stopsAtDistance.addSource(locationLiveData){ point-> if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "New location: $point") val distance = distanceMtLiveData.value ?: 40 //oldRepo.requestStopsWithinDistance(point.latitude, point.longitude, distance, callback) requestStopsCheckDBRunning(point, distance) } stopsAtDistance.addSource(distanceMtLiveData){ dist-> if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "New distance: $dist") if(locationLiveData.value != null){ val point: GPSPoint = locationLiveData.value!! //oldRepo.requestStopsWithinDistance(point.latitude, point.longitude, dist, callback) requestStopsCheckDBRunning(point, dist) } else{ Log.d(DEBUG_TAG, "Modified distance but locationLiveData value is null") } } stopsAtDistance.addSource(dbUpdateRunning){ running -> if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "DB update running: $running") if(!running) { reRequestStops() } } } private fun reRequestStops(){ var req = false locationLiveData.value?.let{ point -> distanceMtLiveData.value ?.let { dist-> req = true oldRepo.requestStopsWithinDistance(point.latitude, point.longitude, dist, callback) } } if(!req){ Log.w(DEBUG_TAG, "Requested to rerun stops, but position or distance (or both) are null") } } val arrivalsDecoupled = arrivalsNearby.map { palinas -> locationLiveData.value?.let { loc -> Collections.sort(palinas, StopSorterByDistance(loc)) } var routesPairList = ArrayList(10) //int maxNum = Math.min(MAX_STOPS, stopList.size()); for (p in palinas) { //if there are no routes available, skip stop if (p.queryAllRoutes().isEmpty()) continue for (r in p.queryAllRoutes()) { //if there are no routes, should not do anything if (r.passaggi != null && !r.passaggi.isEmpty()) routesPairList.add(RouteWithStop(p, r)) } } val pos = locationLiveData.value if(pos != null) { routesPairList.sortWith { p1, p2 -> comparePairsRoutesArrivals(p1,p2,pos) } } routesPairList } fun comparePairsRoutesArrivals(pair1: RouteWithStop, pair2: RouteWithStop, pos: GPSPoint) : Int{ var delta = 0 val stop1: Stop = pair1.stop val stop2: Stop = pair2.stop val dist1 = utils.measuredistanceBetween( pos.latitude, pos.longitude, stop1.getLatitude()!!, stop1.getLongitude()!! ) val dist2 = utils.measuredistanceBetween( pos.latitude, pos.longitude, stop2.getLatitude()!!, stop2.getLongitude()!! ) val passaggi1 = pair1.route.passaggi val passaggi2 = pair2.route.passaggi if (passaggi1.size <= 0 || passaggi2.size <= 0) { Log.e("ArrivalsStopAdapter", "Cannot compare: No arrivals in one of the stops") } else { Collections.sort(passaggi1) Collections.sort(passaggi2) /*int deltaOre = passaggi1.get(0).hh-passaggi2.get(0).hh; if(deltaOre>12) deltaOre -= 24; else if (deltaOre<-12) deltaOre += 24; delta+=deltaOre*60 + passaggi1.get(0).mm-passaggi2.get(0).mm; */ delta = passaggi1[0]!!.getDifferenceMinutes(passaggi2[0]!!).toInt() } delta += ((dist1 - dist2) * MINUTI_PER_METRO * DISTANCE_MULTIPLIER).toInt() return delta } + override fun onCleared() { + volleyManager.requestQueue.cancelAll(REQUEST_TAG) + super.onCleared() + } + companion object{ private const val DEBUG_TAG = "BusTO-NearbyStopVwModel" + const val REQUEST_TAG: String = "NearbyArrivals" + const val MINUTI_PER_METRO: Double = 6.0 / 100 //v = 5km/h const val DISTANCE_MULTIPLIER: Double = 2.0 / 3 } } \ No newline at end of file