diff --git a/build.gradle b/build.gradle index b390fb5..8ed2f71 100644 --- a/build.gradle +++ b/build.gradle @@ -1,62 +1,64 @@ buildscript { repositories { mavenCentral() jcenter() google() } dependencies { classpath 'com.android.tools.build:gradle:3.1.0' } ext { support_ver = "25.3.1" } } apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion '27.0.3' compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } buildTypes { debug { applicationIdSuffix ".debug" versionNameSuffix "-dev" } } lintOptions { abortOnError false } repositories { mavenCentral() mavenLocal() } dependencies { - implementation "com.android.support:support-v4:$support_ver" - implementation "com.android.support:appcompat-v7:$support_ver" - implementation "com.android.support:design:$support_ver" - implementation "com.android.support:recyclerview-v7:$support_ver" - implementation "com.android.support:preference-v7:$support_ver" - implementation 'org.jsoup:jsoup:1.7.3' + compile "com.android.support:support-v4:$support_ver" + compile "com.android.support:appcompat-v7:$support_ver" + compile "com.android.support:design:$support_ver" + compile "com.android.support:recyclerview-v7:$support_ver" + compile "com.android.support:preference-v7:$support_ver" + compile "com.android.support:cardview-v7:$support_ver" + + implementation 'org.jsoup:jsoup:1.11.3' implementation 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1' } } diff --git a/res/layout/square_stop_element.xml b/res/layout/square_stop_element.xml deleted file mode 100644 index 63e8d3f..0000000 --- a/res/layout/square_stop_element.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/res/layout/stop_card.xml b/res/layout/stop_card.xml new file mode 100755 index 0000000..850bc36 --- /dev/null +++ b/res/layout/stop_card.xml @@ -0,0 +1,110 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/values/colors.xml b/res/values/colors.xml index 0a93713..b37a5dd 100644 --- a/res/values/colors.xml +++ b/res/values/colors.xml @@ -1,18 +1,18 @@ - #FF9800 + #ff9800 #F57C00 #2196F3 - #2060DD + #2060dd #009688 #4DB6AC #80cbc4 #F5F5F5 #757575 #DE0908 #2060DD \ No newline at end of file diff --git a/src/it/reyboz/bustorino/adapters/SquareStopAdapter.java b/src/it/reyboz/bustorino/adapters/SquareStopAdapter.java index da56c99..2bcb5cd 100644 --- a/src/it/reyboz/bustorino/adapters/SquareStopAdapter.java +++ b/src/it/reyboz/bustorino/adapters/SquareStopAdapter.java @@ -1,128 +1,122 @@ /* 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.location.Location; -import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.BaseAdapter; import android.widget.TextView; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.Stop; -import it.reyboz.bustorino.backend.StopSorterByDistance; +import it.reyboz.bustorino.util.StopSorterByDistance; import it.reyboz.bustorino.fragments.FragmentListener; -import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.List; public class SquareStopAdapter extends RecyclerView.Adapter { - private static int layoutRes = R.layout.square_stop_element; + private static int layoutRes = R.layout.stop_card; //private List stops; private Context context; private @Nullable Location userPosition; private FragmentListener listener; private List stops; public SquareStopAdapter(List objects, Context con,FragmentListener fragmentListener,@Nullable Location pos) { context = con; listener = fragmentListener; userPosition = pos; stops = objects; } @Override public SquareViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.square_stop_element, parent, false); + final View view = LayoutInflater.from(parent.getContext()).inflate(layoutRes, parent, false); //sort the stops by distance 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 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.busStopIDView); - stopNameView = (TextView) holdView.findViewById(R.id.stopNameView); - routesView = (TextView) holdView.findViewById(R.id.routesStoppingTextView); - distancetextView = (TextView) holdView.findViewById(R.id.distanceTextView); + 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.createFragmentForStop(stopID); } } /* @Override public Stop getItem(int position) { return stops.get(position); } */ } diff --git a/src/it/reyboz/bustorino/backend/Stop.java b/src/it/reyboz/bustorino/backend/Stop.java index 1c91b7a..72eb5ce 100644 --- a/src/it/reyboz/bustorino/backend/Stop.java +++ b/src/it/reyboz/bustorino/backend/Stop.java @@ -1,288 +1,290 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi 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.backend; import android.location.Location; import android.support.annotation.NonNull; import android.support.annotation.Nullable; +import android.util.Log; +import it.reyboz.bustorino.util.LinesNameSorter; import java.net.URLEncoder; import java.util.Collections; import java.util.List; import java.util.Locale; public class Stop implements Comparable { // remove "final" in case you need to set these from outside the parser\scrapers\fetchers public final @NonNull String ID; private @Nullable String name; private @Nullable String username; public @Nullable String location; public @Nullable Route.Type type; private @Nullable List routesThatStopHere; private final @Nullable Double lat; private final @Nullable Double lon; // leave this non-final private @Nullable String routesThatStopHereString = null; private @Nullable String absurdGTTPlaceName = null; /** * Hey, look, method overloading! */ public Stop(final @Nullable String name, final @NonNull String ID, @Nullable final String location, @Nullable final Route.Type type, @Nullable final List routesThatStopHere) { this.ID = ID; this.name = name; this.username = null; this.location = (location != null && location.length() == 0) ? null : location; this.type = type; this.routesThatStopHere = routesThatStopHere; this.lat = null; this.lon = null; } /** * Hey, look, method overloading! */ public Stop(final @NonNull String ID) { this.ID = ID; this.name = null; this.username = null; this.location = null; this.type = null; this.routesThatStopHere = null; this.lat = null; this.lon = null; } /** * Constructor that sets EVERYTHING. */ public Stop(@NonNull String ID, @Nullable String name, @Nullable String userName, @Nullable String location, @Nullable Route.Type type, @Nullable List routesThatStopHere, @Nullable Double lat, @Nullable Double lon) { this.ID = ID; this.name = name; this.username = userName; this.location = location; this.type = type; this.routesThatStopHere = routesThatStopHere; this.lat = lat; this.lon = lon; } public @Nullable String routesThatStopHereToString() { // M E M O I Z A T I O N if(this.routesThatStopHereString != null) { return this.routesThatStopHereString; } // no string yet? build it! return buildString(); } @Nullable public String getAbsurdGTTPlaceName() { return absurdGTTPlaceName; } public void setAbsurdGTTPlaceName(@NonNull String absurdGTTPlaceName) { this.absurdGTTPlaceName = absurdGTTPlaceName; } public void setRoutesThatStopHere(@Nullable List routesThatStopHere) { this.routesThatStopHere = routesThatStopHere; } private @Nullable String buildString() { // no routes => no string if(this.routesThatStopHere == null || this.routesThatStopHere.size() == 0) { return null; } StringBuilder sb = new StringBuilder(); - Collections.sort(routesThatStopHere); + Collections.sort(routesThatStopHere,new LinesNameSorter()); int i, lenMinusOne = routesThatStopHere.size() - 1; for (i = 0; i < lenMinusOne; i++) { sb.append(routesThatStopHere.get(i)).append(", "); } // last one: sb.append(routesThatStopHere.get(i)); this.routesThatStopHereString = sb.toString(); return this.routesThatStopHereString; } @Override public int compareTo(@NonNull Stop other) { int res; int thisAsInt = networkTools.failsafeParseInt(this.ID); int otherAsInt = networkTools.failsafeParseInt(other.ID); // numeric stop IDs if(thisAsInt != 0 && otherAsInt != 0) { return thisAsInt - otherAsInt; } else { // non-numeric res = this.ID.compareTo(other.ID); if (res != 0) { return res; } } // try with name, then if(this.name != null && other.name != null) { res = this.name.compareTo(other.name); } // and give up return res; } /** * Sets a name. * * @param name stop name as string (not null) */ public final void setStopName(@NonNull String name) { this.name = name; } /** * Sets user name. Empty string is converted to null. * * @param name a string of non-zero length, or null */ public final void setStopUserName(@Nullable String name) { if(name == null) { this.username = null; } else if(name.length() == 0) { this.username = null; } else { this.username = name; } } /** * Returns stop name or username (if set).
* - empty string means "already searched everywhere, can't find it"
* - null means "didn't search, yet. Maybe you should try."
* - string means "here's the name.", obviously.
* * @return string if known, null if still unknown */ public final @Nullable String getStopDisplayName() { if(this.username == null) { return this.name; } else { return this.username; } } /** * Same as getStopDisplayName, only returns default name.
* I'd use an @see tag, but Android Studio is incapable of understanding that getStopDefaultName * refers to the method exactly above this one and not some arcane and esoteric unknown symbol. */ public final @Nullable String getStopDefaultName() { return this.name; } /** * Same as getStopDisplayName, only returns user name.
* Also, never an empty string. */ public final @Nullable String getStopUserName() { return this.username; } /** * Gets username and name from other stop if they exist, sets itself accordingly. * * @param other another Stop * @return did we actually set/change anything? */ public final boolean mergeNameFrom(Stop other) { boolean ret = false; if(other.name != null) { if(this.name == null || !this.name.equals(other.name)) { this.name = other.name; ret = true; } } if(other.username != null) { if(this.username == null || !this.username.equals(other.username)) { this.username = other.username; ret = true; } } return ret; } public final @Nullable String getGeoURL() { if(this.lat == null || this.lon == null) { return null; } // Android documentation suggests US for machine readable output (use dot as decimal separator) return String.format(Locale.US, "geo:%f,%f", this.lat, this.lon); } public final @Nullable String getGeoURLWithAddress() { String url = getGeoURL(); if(url == null) { return null; } if(this.location != null) { try { String addThis = "?q=".concat(URLEncoder.encode(this.location, "utf-8")); return url.concat(addThis); } catch (Exception ignored) {} } return url; } @Nullable public Double getLatitude() { return lat; } @Nullable public Double getLongitude() { return lon; } public Double getDistanceFromLocation(Location loc){ if(this.lat!=null && this.lon !=null) return utils.measuredistanceBetween(this.lat,this.lon,loc.getLatitude(),loc.getLongitude()); else return Double.POSITIVE_INFINITY; } } diff --git a/src/it/reyboz/bustorino/fragments/CommonScrollListener.java b/src/it/reyboz/bustorino/fragments/CommonScrollListener.java index 9eddb75..94b0d55 100644 --- a/src/it/reyboz/bustorino/fragments/CommonScrollListener.java +++ b/src/it/reyboz/bustorino/fragments/CommonScrollListener.java @@ -1,77 +1,85 @@ /* 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.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.AbsListView; import java.lang.ref.WeakReference; public class CommonScrollListener extends RecyclerView.OnScrollListener implements AbsListView.OnScrollListener{ WeakReference listenerWeakReference; //enable swipeRefreshLayout when scrolling down or not boolean enableRefreshLayout; int lastvisibleitem; public CommonScrollListener(FragmentListener lis,boolean enableRefreshLayout){ listenerWeakReference = new WeakReference<>(lis); this.enableRefreshLayout = enableRefreshLayout; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { /* * This seems to be a totally useless method */ } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { FragmentListener listener = listenerWeakReference.get(); if(listener==null){ //can't do anything, sorry Log.i(this.getClass().getName(),"called onScroll but FragmentListener is null"); return; } if (firstVisibleItem!=0) { if (lastvisibleitem < firstVisibleItem) { Log.i("Busto", "Scrolling DOWN"); listener.showFloatingActionButton(false); //lastScrollUp = true; } else if (lastvisibleitem > firstVisibleItem) { Log.i("Busto", "Scrolling UP"); listener.showFloatingActionButton(true); //lastScrollUp = false; } lastvisibleitem = firstVisibleItem; } if(enableRefreshLayout){ boolean enable = false; if(view != null && view.getChildCount() > 0){ // check if the first item of the list is visible boolean firstItemVisible = view.getFirstVisiblePosition() == 0; // check if the top of the first item is visible boolean topOfFirstItemVisible = view.getChildAt(0).getTop() == 0; // enabling or disabling the refresh layout enable = firstItemVisible && topOfFirstItemVisible; } listener.enableRefreshLayout(enable); //Log.d(getString(R.string.list_fragment_debug),"onScroll active, first item visible: "+firstVisibleItem+", refreshlayout enabled: "+enable); }} + + @Override + public void onScrollStateChanged(RecyclerView recyclerView, int newState) { + FragmentListener listener = listenerWeakReference.get(); + if(newState!=SCROLL_STATE_IDLE) listener.showFloatingActionButton(false); + else listener.showFloatingActionButton(true); + + } } diff --git a/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java b/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java index 55cf9de..62a0ae7 100644 --- a/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java +++ b/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java @@ -1,337 +1,337 @@ /* 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.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; 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 it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.Route; import it.reyboz.bustorino.backend.Stop; -import it.reyboz.bustorino.backend.StopSorterByDistance; import it.reyboz.bustorino.backend.utils; import it.reyboz.bustorino.middleware.AppDataProvider; import it.reyboz.bustorino.middleware.NextGenDB.Contract.*; import it.reyboz.bustorino.adapters.SquareStopAdapter; import java.util.ArrayList; import java.util.Arrays; public class NearbyStopsFragment extends Fragment implements LoaderManager.LoaderCallbacks { private FragmentListener mListener; private LocationManager locManager; private FragmentLocationListener locationListener; private final String[] PROJECTION = {StopsTable.COL_ID,StopsTable.COL_LAT,StopsTable.COL_LONG, StopsTable.COL_NAME,StopsTable.COL_TYPE,StopsTable.COL_LINES_STOPPING}; private final static String DEBUG_TAG = "NearbyStopsFragment"; //data Bundle private final String BUNDLE_LOCATION = "location"; private final int LOADER_ID = 0; private RecyclerView gridRecyclerView; private SquareStopAdapter madapter; private AutoFitGridLayoutManager gridLayoutManager; boolean canStartDBQuery = true; private Location lastReceivedLocation = null; private ProgressBar loadingProgressBar; private int distance; private SharedPreferences globalSharedPref; private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener; private TextView noStopsTextView; - - public static final int COLUMN_WIDTH_DP = 100; + private CommonScrollListener scrollListener; + public static final int COLUMN_WIDTH_DP = 250; public NearbyStopsFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment NearbyStopsFragment. */ public static NearbyStopsFragment newInstance() { NearbyStopsFragment fragment = new NearbyStopsFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { /* mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); */ } locManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE); locationListener = new FragmentLocationListener(this); globalSharedPref = getContext().getSharedPreferences(getString(R.string.mainSharedPreferences),Context.MODE_PRIVATE); preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(DEBUG_TAG,"Key "+key+" was changed"); if(key.equals(getString(R.string.databaseUpdatingPref))){ if(!sharedPreferences.getBoolean(getString(R.string.databaseUpdatingPref),true)){ canStartDBQuery = true; Log.d(DEBUG_TAG,"The database has finished updating, can start update now"); } } } }; globalSharedPref.registerOnSharedPreferenceChangeListener(preferenceChangeListener); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View root = inflater.inflate(R.layout.fragment_nearby_stops, container, false); gridRecyclerView = (RecyclerView) root.findViewById(R.id.stopGridRecyclerView); gridLayoutManager = new AutoFitGridLayoutManager(getContext().getApplicationContext(), utils.convertDipToPixels(getContext(),COLUMN_WIDTH_DP)); gridRecyclerView.setLayoutManager(gridLayoutManager); gridRecyclerView.setHasFixedSize(false); loadingProgressBar = (ProgressBar) root.findViewById(R.id.loadingBar); noStopsTextView = (TextView) root.findViewById(R.id.noStopsTextView); + scrollListener = new CommonScrollListener(mListener,false); return root; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof FragmentListener) { mListener = (FragmentListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onPause() { super.onPause(); canStartDBQuery = false; locManager.removeUpdates(locationListener); gridRecyclerView.setAdapter(null); Log.d(DEBUG_TAG,"On paused called"); } @Override public void onResume() { super.onResume(); canStartDBQuery = !globalSharedPref.getBoolean(getString(R.string.databaseUpdatingPref),false); try{ if(canStartDBQuery) locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000,5,locationListener); } catch (SecurityException ex){ //ignored //try another location provider } if(madapter!=null){ gridRecyclerView.setAdapter(madapter); loadingProgressBar.setVisibility(View.GONE); } Log.d(DEBUG_TAG,"OnResume called"); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); gridRecyclerView.setVisibility(View.INVISIBLE); - gridRecyclerView.setOnScrollListener(new CommonScrollListener(mListener,false)); + gridRecyclerView.addOnScrollListener(scrollListener); } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public Loader onCreateLoader(int id, Bundle args) { //BUILD URI lastReceivedLocation = args.getParcelable(BUNDLE_LOCATION); Uri.Builder builder = new Uri.Builder(); builder.scheme("content").authority(AppDataProvider.AUTHORITY) .appendPath("stops").appendPath("location") .appendPath(String.valueOf(lastReceivedLocation.getLatitude())) .appendPath(String.valueOf(lastReceivedLocation.getLongitude())) .appendPath(String.valueOf(distance)); //distance CursorLoader cl = new CursorLoader(getContext(),builder.build(),PROJECTION,null,null,null); cl.setUpdateThrottle(1000); return cl; } @Override public void onLoadFinished(Loader loader, Cursor data) { ArrayList stopList = new ArrayList<>(); data.moveToFirst(); if(data.getCount()<4 && !globalSharedPref.getBoolean(getString(R.string.databaseUpdatingPref),false) && distance<=1000){ distance = distance*2; Bundle d = new Bundle(); d.putParcelable(BUNDLE_LOCATION,lastReceivedLocation); getLoaderManager().restartLoader(LOADER_ID,d,this); return; } Log.d("LoadFromCursor","Number of nearby stops: "+data.getCount()); final int col_id = data.getColumnIndex(StopsTable.COL_ID); final int latInd = data.getColumnIndex(StopsTable.COL_LAT); final int lonInd = data.getColumnIndex(StopsTable.COL_LONG); final int nameindex = data.getColumnIndex(StopsTable.COL_NAME); final int typeIndex = data.getColumnIndex(StopsTable.COL_TYPE); final int linesIndex = data.getColumnIndex(StopsTable.COL_LINES_STOPPING); for(int i=0; i0) { madapter = new SquareStopAdapter(stopList, getContext(), mListener, lastReceivedLocation); gridRecyclerView.setAdapter(madapter); if (gridRecyclerView.getVisibility() != View.VISIBLE) { loadingProgressBar.setVisibility(View.GONE); gridRecyclerView.setVisibility(View.VISIBLE); } noStopsTextView.setVisibility(View.GONE); } else { noStopsTextView.setVisibility(View.VISIBLE); loadingProgressBar.setVisibility(View.GONE); } } @Override public void onLoaderReset(Loader loader) { } /** * Local locationListener, to use for the GPS */ class FragmentLocationListener implements LocationListener{ LoaderManager.LoaderCallbacks callbacks; public FragmentLocationListener(LoaderManager.LoaderCallbacks callbacks) { this.callbacks = callbacks; } @Override public void onLocationChanged(Location location) { //set adapter float accuracy = location.getAccuracy(); if(accuracy<60 && canStartDBQuery) { distance = 100; final Bundle setting = new Bundle(); setting.putParcelable(BUNDLE_LOCATION,location); getLoaderManager().restartLoader(LOADER_ID,setting,callbacks); } Log.d("LocationListener","can start loader "+ canStartDBQuery); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } } /** * Simple trick to get an automatic number of columns (from https://www.journaldev.com/13792/android-gridlayoutmanager-example) * */ class AutoFitGridLayoutManager extends GridLayoutManager { private int columnWidth; private boolean columnWidthChanged = true; public AutoFitGridLayoutManager(Context context, int columnWidth) { super(context, 1); setColumnWidth(columnWidth); } public void setColumnWidth(int newColumnWidth) { if (newColumnWidth > 0 && newColumnWidth != columnWidth) { columnWidth = newColumnWidth; columnWidthChanged = true; } } @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { if (columnWidthChanged && columnWidth > 0) { int totalSpace; if (getOrientation() == VERTICAL) { totalSpace = getWidth() - getPaddingRight() - getPaddingLeft(); } else { totalSpace = getHeight() - getPaddingTop() - getPaddingBottom(); } int spanCount = Math.max(1, totalSpace / columnWidth); setSpanCount(spanCount); columnWidthChanged = false; } super.onLayoutChildren(recycler, state); } } } diff --git a/src/it/reyboz/bustorino/util/LinesNameSorter.java b/src/it/reyboz/bustorino/util/LinesNameSorter.java new file mode 100644 index 0000000..7a9dec1 --- /dev/null +++ b/src/it/reyboz/bustorino/util/LinesNameSorter.java @@ -0,0 +1,26 @@ +package it.reyboz.bustorino.util; + +import android.util.Log; +import it.reyboz.bustorino.backend.Route; + +import java.util.Comparator; + +public class LinesNameSorter implements Comparator { + @Override + public int compare(String name1, String name2) { + + if(name1.length()>name2.length()) return 1; + if(name1.length()==name2.length()) { + try{ + int num1 = Integer.parseInt(name1.trim()); + int num2 = Integer.parseInt(name2.trim()); + return num1-num2; + } catch (NumberFormatException ex){ + //Log.d("BUSTO Compare lines","Cannot compare lines "+name1+" and "+name2); + return name1.compareTo(name2); + } + } + return -1; + + } +} diff --git a/src/it/reyboz/bustorino/backend/StopSorterByDistance.java b/src/it/reyboz/bustorino/util/StopSorterByDistance.java similarity index 85% rename from src/it/reyboz/bustorino/backend/StopSorterByDistance.java rename to src/it/reyboz/bustorino/util/StopSorterByDistance.java index d6617f1..efd17c8 100644 --- a/src/it/reyboz/bustorino/backend/StopSorterByDistance.java +++ b/src/it/reyboz/bustorino/util/StopSorterByDistance.java @@ -1,18 +1,19 @@ -package it.reyboz.bustorino.backend; +package it.reyboz.bustorino.util; import android.location.Location; +import it.reyboz.bustorino.backend.Stop; import java.util.Comparator; public class StopSorterByDistance implements Comparator { private final Location locToCompare; public StopSorterByDistance(Location locToCompare) { this.locToCompare = locToCompare; } @Override public int compare(Stop o1, Stop o2) { return (int) (o1.getDistanceFromLocation(locToCompare)-o2.getDistanceFromLocation(locToCompare)); } }