diff --git a/build.gradle b/build.gradle index c9731ec..bed180a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,58 +1,59 @@ buildscript { repositories { mavenCentral() jcenter() google() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' } } apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion '26.0.1' 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 { compile 'com.android.support:support-v4:25.3.1' compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support:design:25.3.1' + compile 'com.android.support:recyclerview-v7:25.3.1' compile 'org.jsoup:jsoup:1.7.3' compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1' } } diff --git a/res/layout/fragment_nearby_stops.xml b/res/layout/fragment_nearby_stops.xml index bfa4feb..39f57c3 100644 --- a/res/layout/fragment_nearby_stops.xml +++ b/res/layout/fragment_nearby_stops.xml @@ -1,42 +1,40 @@ - + android:focusable="true" android:visibility="gone" + android:clipChildren="false" android:clipToPadding="true" android:horizontalSpacing="10dp" + android:verticalSpacing="10dp"/> diff --git a/res/layout/square_stop_element.xml b/res/layout/square_stop_element.xml index 537175f..63e8d3f 100644 --- a/res/layout/square_stop_element.xml +++ b/res/layout/square_stop_element.xml @@ -1,39 +1,43 @@ + android:layout_height="wrap_content" + android:background="?android:attr/selectableItemBackground" +> + android:layout_alignParentLeft="true" android:layout_alignParentStart="true" + android:padding="5dp"/> + android:layout_alignParentStart="true" android:maxHeight="60dp" android:paddingLeft="3dp" + android:paddingRight="3dp" android:paddingBottom="5dp"/> \ No newline at end of file diff --git a/src/it/reyboz/bustorino/ActivityFavorites.java b/src/it/reyboz/bustorino/ActivityFavorites.java index c86416a..3be3e56 100644 --- a/src/it/reyboz/bustorino/ActivityFavorites.java +++ b/src/it/reyboz/bustorino/ActivityFavorites.java @@ -1,260 +1,260 @@ /* BusTO - Arrival times for Turin public transports. Copyright (C) 2014 Valerio Bozzolan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino; import it.reyboz.bustorino.backend.Stop; -import it.reyboz.bustorino.middleware.StopAdapter; +import it.reyboz.bustorino.adapters.StopAdapter; import it.reyboz.bustorino.middleware.StopsDB; import it.reyboz.bustorino.middleware.UserDB; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.net.Uri; import android.os.AsyncTask; import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import java.util.List; public class ActivityFavorites extends AppCompatActivity { private ListView favoriteListView; private SQLiteDatabase userDB; private EditText bus_stop_name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_favorites); // this should be done in onStarted and closed in onStop, but apparently onStarted is never run. this.userDB = new UserDB(getApplicationContext()).getWritableDatabase(); ActionBar ab = getSupportActionBar(); assert ab != null; ab.setIcon(R.drawable.ic_launcher); ab.setDisplayHomeAsUpEnabled(true); // Back button favoriteListView = (ListView) findViewById(R.id.favoriteListView); createFavoriteList(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (v.getId() == R.id.favoriteListView) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_favourites_entry, menu); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Stop busStop = (Stop) favoriteListView.getItemAtPosition(info.position); switch (item.getItemId()) { case R.id.action_favourite_entry_delete: UserDB.deleteStop(busStop, this.userDB); createFavoriteList(); return true; case R.id.action_rename_bus_stop_username: showBusStopUsernameInputDialog(busStop); return true; case R.id.action_view_on_map: Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(busStop.getGeoURL())); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); return true; default: return super.onContextItemSelected(item); } } void createFavoriteList() { // TODO: memoize default list, query only user names every time? new AsyncGetFavorites(getApplicationContext(), this.userDB).execute(); } public void showBusStopUsernameInputDialog(final Stop busStop) { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = this.getLayoutInflater(); View renameDialogLayout = inflater.inflate(R.layout.rename_dialog, null); bus_stop_name = (EditText) renameDialogLayout.findViewById(R.id.rename_dialog_bus_stop_name); bus_stop_name.setText(busStop.getStopDisplayName()); bus_stop_name.setHint(busStop.getStopDefaultName()); builder.setTitle(getString(R.string.dialog_rename_bus_stop_username_title)); builder.setView(renameDialogLayout); builder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String busStopUsername = bus_stop_name.getText().toString(); String oldUserName = busStop.getStopUserName(); // changed to none if(busStopUsername.length() == 0) { // unless it was already empty, set new if(oldUserName != null) { busStop.setStopUserName(null); UserDB.updateStop(busStop, userDB); createFavoriteList(); } } else { // changed to something // something different? if(oldUserName == null || !busStopUsername.equals(oldUserName)) { busStop.setStopUserName(busStopUsername); UserDB.updateStop(busStop, userDB); createFavoriteList(); } } } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setNeutralButton(R.string.dialog_rename_bus_stop_username_reset_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // delete user name from database busStop.setStopUserName(null); UserDB.updateStop(busStop, userDB); createFavoriteList(); } }); builder.show(); } /** * This one runs. onStart instead gets ignored for no reason whatsoever. * * @see Android Activity Lifecycle */ @Override protected void onStop() { super.onStop(); this.userDB.close(); } private class AsyncGetFavorites extends AsyncTask> { private Context c; private SQLiteDatabase userDB; AsyncGetFavorites(Context c, SQLiteDatabase userDB) { this.c = c; this.userDB = userDB; } @Override protected List doInBackground(Void... voids) { StopsDB stopsDB = new StopsDB(c); stopsDB.openIfNeeded(); List busStops = UserDB.getFavorites(this.userDB, stopsDB); stopsDB.closeIfNeeded(); return busStops; } @Override protected void onPostExecute(List busStops) { // If no data is found show a friendly message if (busStops.size() == 0) { favoriteListView.setVisibility(View.INVISIBLE); TextView favoriteTipTextView = (TextView) findViewById(R.id.favoriteTipTextView); assert favoriteTipTextView != null; favoriteTipTextView.setVisibility(View.VISIBLE); } /* There's a nice method called notifyDataSetChanged() to avoid building the ListView * all over again. This method exists in a billion answers on Stack Overflow, but * it's nowhere to be seen around here, Android Studio can't find it no matter what. * Anyway, it only works from Android 2.3 onward (which is why it refuses to appear, I * guess) and requires to modify the list with .add() and .clear() and some other * methods, so to update a single stop we need to completely rebuild the list for no * reason. It would probably end up as "slow" as throwing away the old ListView and * redrwaing everything. */ // Show results favoriteListView.setAdapter(new StopAdapter(this.c, busStops)); favoriteListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View view, int position, long id) { /** * Casting because of Javamerda * @url http://stackoverflow.com/questions/30549485/androids-list-view-parameterized-type-in-adapterview-onitemclicklistener */ Stop busStop = (Stop) parent.getItemAtPosition(position); Intent intent = new Intent(ActivityFavorites.this, ActivityMain.class); Bundle b = new Bundle(); // TODO: is passing a serialized object a good idea? Or rather, is it reasonably fast? //b.putSerializable("bus-stop-serialized", busStop); b.putString("bus-stop-ID", busStop.ID); b.putString("bus-stop-display-name", busStop.getStopDisplayName()); intent.putExtras(b); //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); // Intent.FLAG_ACTIVITY_CLEAR_TASK isn't supported in API < 11 and we're targeting API 7... intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); startActivity(intent); finish(); } }); registerForContextMenu(favoriteListView); } } } diff --git a/src/it/reyboz/bustorino/middleware/GPSLocationAdapter.java b/src/it/reyboz/bustorino/adapters/GPSLocationAdapter.java similarity index 97% rename from src/it/reyboz/bustorino/middleware/GPSLocationAdapter.java rename to src/it/reyboz/bustorino/adapters/GPSLocationAdapter.java index e849147..8fbf842 100644 --- a/src/it/reyboz/bustorino/middleware/GPSLocationAdapter.java +++ b/src/it/reyboz/bustorino/adapters/GPSLocationAdapter.java @@ -1,55 +1,55 @@ -package it.reyboz.bustorino.middleware; +package it.reyboz.bustorino.adapters; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Looper; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; public class GPSLocationAdapter implements LocationListener { private Context con; private LocationManager locMan; public GPSLocationAdapter(Context con) { this.con = con; locMan = (LocationManager) con.getSystemService(Context.LOCATION_SERVICE); } public boolean startRequestingPosition(){ try { locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this); return true; } catch (SecurityException exc){ exc.printStackTrace(); return false; } } @Override public void onLocationChanged(Location location) { Log.d("GPSLocationListener","found location:\nlat: "+location.getLatitude()+" lon: "+location.getLongitude()+"\naccuracy: "+location.getAccuracy()); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { startRequestingPosition(); } @Override public void onProviderDisabled(String provider) { locMan.removeUpdates(this); } } diff --git a/src/it/reyboz/bustorino/middleware/PalinaAdapter.java b/src/it/reyboz/bustorino/adapters/PalinaAdapter.java similarity index 99% rename from src/it/reyboz/bustorino/middleware/PalinaAdapter.java rename to src/it/reyboz/bustorino/adapters/PalinaAdapter.java index 6a46366..4dfa4a0 100644 --- a/src/it/reyboz/bustorino/middleware/PalinaAdapter.java +++ b/src/it/reyboz/bustorino/adapters/PalinaAdapter.java @@ -1,149 +1,149 @@ /* 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.middleware; +package it.reyboz.bustorino.adapters; import android.content.Context; import android.support.annotation.NonNull; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.Palina; import it.reyboz.bustorino.backend.Passaggio; import it.reyboz.bustorino.backend.Route; /** * This once was a ListView Adapter for BusLine[]. * * Thanks to Framentos developers for the guide: * http://www.framentos.com/en/android-tutorial/2012/07/16/listview-in-android-using-custom-listadapter-and-viewcache/# * * @author Valerio Bozzolan * @author Ludovico Pavesi */ public class PalinaAdapter extends ArrayAdapter { private LayoutInflater li; private static int row_layout = R.layout.entry_bus_line_passage; private static final int metroBg = R.drawable.route_background_metro; private static final int busBg = R.drawable.route_background_bus; private static final int extraurbanoBg = R.drawable.route_background_bus_long_distance; private static final int busIcon = R.drawable.bus; private static final int trainIcon = R.drawable.subway; private static final int tramIcon = R.drawable.tram; //private static final int cityIcon = R.drawable.city; // hey look, a pattern! private static class ViewHolder { TextView rowStopIcon; TextView rowRouteDestination; TextView rowRouteTimetable; } public PalinaAdapter(Context context, Palina p) { super(context, row_layout, p.queryAllRoutes()); li = LayoutInflater.from(context); } /** * Some parts taken from the AdapterBusLines class.
* Some parts inspired by these enlightening tutorials:
* http://www.simplesoft.it/android/guida-agli-adapter-e-le-listview-in-android.html
* https://www.codeofaninja.com/2013/09/android-viewholder-pattern-example.html
* And some other bits and bobs TIRATI FUORI DAL NULLA CON L'INTUIZIONE INTELLETTUALE PERCHÉ * SEMBRA CHE NESSUNO ABBIA LA MINIMA IDEA DI COME FUNZIONA UN ADAPTER SU ANDROID. */ @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { ViewHolder vh; if(convertView == null) { // INFLATE! // setting a parent here is not supported and causes a fatal exception, apparently. convertView = li.inflate(row_layout, null); // STORE TEXTVIEWS! vh = new ViewHolder(); vh.rowStopIcon = (TextView) convertView.findViewById(R.id.routeID); vh.rowRouteDestination = (TextView) convertView.findViewById(R.id.routeDestination); vh.rowRouteTimetable = (TextView) convertView.findViewById(R.id.routesThatStopHere); // STORE VIEWHOLDER IN\ON\OVER\UNDER\ABOVE\BESIDE THE VIEW! convertView.setTag(vh); } else { // RECOVER THIS STUFF! vh = (ViewHolder) convertView.getTag(); } Route route = getItem(position); vh.rowStopIcon.setText(route.name); if(route.destinazione==null || route.destinazione.length() == 0) { vh.rowRouteDestination.setVisibility(View.GONE); } else { // View Holder Pattern(R) renders each element from a previous one: if the other one had an invisible rowRouteDestination, we need to make it visible. vh.rowRouteDestination.setVisibility(View.VISIBLE); vh.rowRouteDestination.setText(route.destinazione); } switch (route.type) { case BUS: default: // convertView could contain another background, reset it vh.rowStopIcon.setBackgroundResource(busBg); vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0); break; case LONG_DISTANCE_BUS: vh.rowStopIcon.setBackgroundResource(extraurbanoBg); vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0); break; case METRO: vh.rowStopIcon.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); vh.rowStopIcon.setBackgroundResource(metroBg); vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(trainIcon, 0, 0, 0); break; case RAILWAY: vh.rowStopIcon.setBackgroundResource(busBg); vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(trainIcon, 0, 0, 0); break; case TRAM: // never used but whatever. vh.rowStopIcon.setBackgroundResource(busBg); vh.rowRouteDestination.setCompoundDrawablesWithIntrinsicBounds(tramIcon, 0, 0, 0); break; } List passaggi = route.passaggi; if(passaggi.size() == 0) { vh.rowRouteTimetable.setText(R.string.no_passages); } else { String resultString = ""; for(Passaggio passaggio : passaggi) { // "+" calls concat() and some other stuff internally, this should be faster resultString = resultString.concat(passaggio.toString()).concat(" "); } vh.rowRouteTimetable.setText(resultString); } return convertView; } } diff --git a/src/it/reyboz/bustorino/middleware/SquareStopAdapter.java b/src/it/reyboz/bustorino/adapters/SquareStopAdapter.java similarity index 52% rename from src/it/reyboz/bustorino/middleware/SquareStopAdapter.java rename to src/it/reyboz/bustorino/adapters/SquareStopAdapter.java index ce61d2f..da56c99 100644 --- a/src/it/reyboz/bustorino/middleware/SquareStopAdapter.java +++ b/src/it/reyboz/bustorino/adapters/SquareStopAdapter.java @@ -1,121 +1,128 @@ /* 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.middleware; +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.fragments.FragmentListener; +import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; import java.util.List; -public class SquareStopAdapter extends ArrayAdapter { +public class SquareStopAdapter extends RecyclerView.Adapter { private static int layoutRes = R.layout.square_stop_element; //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) { - super(con,layoutRes,objects);//stops = objects; context = con; listener = fragmentListener; userPosition = pos; + stops = objects; } + + @Override - public void sort(@NonNull Comparator comparator) { - super.sort(comparator); + public SquareViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.square_stop_element, parent, false); + //sort the stops by distance + Collections.sort(stops,new StopSorterByDistance(userPosition)); + return new SquareViewHolder(view); } @Override - public View getView(int position, View convertView, ViewGroup parent) { - LayoutInflater inflater = (LayoutInflater) context - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - SquareViewHolder vh; - if(convertView == null) { - //expand the view - convertView = inflater.inflate(layoutRes, parent,false); - vh = new SquareViewHolder(); - vh.stopIDView = (TextView) convertView.findViewById(R.id.busStopIDView); - vh.stopNameView = (TextView) convertView.findViewById(R.id.stopNameView); - vh.routesView = (TextView) convertView.findViewById(R.id.routesStoppingTextView); - vh.distancetextView = (TextView) convertView.findViewById(R.id.distanceTextView); - - } else { - vh = (SquareViewHolder) convertView.getTag(); - } - - - final Stop stop = getItem(position); + 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); - vh.distancetextView.setText(distance.intValue()+" m"); + holder.distancetextView.setText(distance.intValue()+" m"); } else { - vh.distancetextView.setVisibility(View.GONE); + holder.distancetextView.setVisibility(View.GONE); } - vh.stopNameView.setText(stop.getStopDisplayName()); - vh.stopIDView.setText(stop.ID); + holder.stopNameView.setText(stop.getStopDisplayName()); + holder.stopIDView.setText(stop.ID); String whatStopsHere = stop.routesThatStopHereToString(); if(whatStopsHere == null) { - vh.routesView.setVisibility(View.GONE); + holder.routesView.setVisibility(View.GONE); } else { - vh.routesView.setText(whatStopsHere); - vh.routesView.setVisibility(View.VISIBLE); // might be GONE due to View Holder Pattern + holder.routesView.setText(whatStopsHere); + holder.routesView.setVisibility(View.VISIBLE); // might be GONE due to View Holder Pattern } - convertView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - listener.createFragmentForStop(stop.ID); - } - }); + holder.stopID =stop.ID; } else { Log.w("SquareStopAdapter","!! The selected stop is null !!"); } + } - - //Log.d("SquareStopAdapter","Stop: "+ vh.stopIDView.getText()+" "+ vh.stopNameView.getText()); - convertView.setTag(vh); - return convertView; - + @Override + public int getItemCount() { + return stops.size(); } - private static class SquareViewHolder{ + + 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); + } + + @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/middleware/StopAdapter.java b/src/it/reyboz/bustorino/adapters/StopAdapter.java similarity index 99% rename from src/it/reyboz/bustorino/middleware/StopAdapter.java rename to src/it/reyboz/bustorino/adapters/StopAdapter.java index bd4af78..1601e00 100644 --- a/src/it/reyboz/bustorino/middleware/StopAdapter.java +++ b/src/it/reyboz/bustorino/adapters/StopAdapter.java @@ -1,118 +1,118 @@ /* 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.middleware; +package it.reyboz.bustorino.adapters; import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.Stop; /** * @see PalinaAdapter */ public class StopAdapter extends ArrayAdapter { private LayoutInflater li; private static int row_layout = R.layout.entry_bus_stop; private static final int busIcon = R.drawable.bus; private static final int trainIcon = R.drawable.subway; private static final int tramIcon = R.drawable.tram; private static final int cityIcon = R.drawable.city; private static class ViewHolder { TextView busStopIDTextView; TextView busStopNameTextView; //TextView busLineVehicleIcon; TextView busStopLinesTextView; TextView busStopLocaLityTextView; } public StopAdapter(Context context, List stops) { super(context, row_layout, stops); li = LayoutInflater.from(context); } @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { ViewHolder vh; if(convertView == null) { convertView = li.inflate(row_layout, null); vh = new ViewHolder(); vh.busStopIDTextView = (TextView) convertView.findViewById(R.id.busStopID); vh.busStopNameTextView = (TextView) convertView.findViewById(R.id.busStopName); vh.busStopLinesTextView = (TextView) convertView.findViewById(R.id.routesThatStopHere); vh.busStopLocaLityTextView = (TextView) convertView.findViewById(R.id.busStopLocality); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } Stop stop = getItem(position); vh.busStopIDTextView.setText(stop.ID); // NOTE: intentionally ignoring stop username in search results: if it's in the favorites, why are you searching for it? vh.busStopNameTextView.setText(stop.getStopDisplayName()); String whatStopsHere = stop.routesThatStopHereToString(); if(whatStopsHere == null) { vh.busStopLinesTextView.setVisibility(View.GONE); } else { vh.busStopLinesTextView.setText(whatStopsHere); vh.busStopLinesTextView.setVisibility(View.VISIBLE); // might be GONE due to View Holder Pattern } if(stop.type == null) { vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0); } else { switch(stop.type) { case BUS: default: vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0); break; case METRO: case RAILWAY: vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(trainIcon, 0, 0, 0); break; case TRAM: vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(tramIcon, 0, 0, 0); break; case LONG_DISTANCE_BUS: // è l'opposto della città ma va beh, dettagli. vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(cityIcon, 0, 0, 0); } } if (stop.location == null) { vh.busStopLocaLityTextView.setVisibility(View.GONE); } else { vh.busStopLocaLityTextView.setText(stop.location); vh.busStopLocaLityTextView.setVisibility(View.VISIBLE); // might be GONE due to View Holder Pattern } return convertView; } } diff --git a/src/it/reyboz/bustorino/backend/utils.java b/src/it/reyboz/bustorino/backend/utils.java index 171fb7e..99becf7 100644 --- a/src/it/reyboz/bustorino/backend/utils.java +++ b/src/it/reyboz/bustorino/backend/utils.java @@ -1,19 +1,32 @@ package it.reyboz.bustorino.backend; +import android.content.Context; +import android.support.v7.widget.RecyclerView; +import android.view.View; + public abstract class utils { private static final double EarthRadius = 6371e3; public static Double measuredistanceBetween(double lat1,double long1,double lat2,double long2){ final double phi1 = Math.toRadians(lat1); final double phi2 = Math.toRadians(lat2); final double deltaPhi = Math.toRadians(lat2-lat1); final double deltaTheta = Math.toRadians(long2-long1); final double a = Math.sin(deltaPhi/2)*Math.sin(deltaPhi/2)+ Math.cos(phi1)*Math.cos(phi2)*Math.sin(deltaTheta/2)*Math.sin(deltaTheta/2); final double c = 2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a)); return EarthRadius*c; } + public static int convertDipToPixels(Context con,float dips) + { + return (int) (dips * con.getResources().getDisplayMetrics().density + 0.5f); + } + public static int calculateNumColumnsFromSize(View containerView, int pixelsize){ + int width = containerView.getWidth(); + float ncols = ((float)width)/pixelsize; + return (int) Math.floor(ncols); + } } diff --git a/src/it/reyboz/bustorino/fragments/CommonScrollListener.java b/src/it/reyboz/bustorino/fragments/CommonScrollListener.java index 6b60bc5..9eddb75 100644 --- a/src/it/reyboz/bustorino/fragments/CommonScrollListener.java +++ b/src/it/reyboz/bustorino/fragments/CommonScrollListener.java @@ -1,76 +1,77 @@ /* 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 implements AbsListView.OnScrollListener{ +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); }} } diff --git a/src/it/reyboz/bustorino/fragments/FragmentHelper.java b/src/it/reyboz/bustorino/fragments/FragmentHelper.java index 8924293..0293269 100644 --- a/src/it/reyboz/bustorino/fragments/FragmentHelper.java +++ b/src/it/reyboz/bustorino/fragments/FragmentHelper.java @@ -1,200 +1,201 @@ /* BusTO (fragments) 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.ContentResolver; import android.content.ContentValues; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import it.reyboz.bustorino.R; +import it.reyboz.bustorino.adapters.PalinaAdapter; import it.reyboz.bustorino.backend.Fetcher; import it.reyboz.bustorino.backend.Palina; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.middleware.*; import java.util.List; /** * Helper class to manage the fragments and their needs */ public class FragmentHelper { GeneralActivity act; private Stop lastSuccessfullySearchedBusStop; //support for multiple frames private int primaryFrameLayout,secondaryFrameLayout, swipeRefID; public static final int NO_FRAME = -3; private NextGenDB newDBHelper; public FragmentHelper(GeneralActivity act, int swipeRefID, int mainFrame) { this(act,swipeRefID,mainFrame,NO_FRAME); } public FragmentHelper(GeneralActivity act, int swipeRefID, int primaryFrameLayout, int secondaryFrameLayout) { this.act = act; this.swipeRefID = swipeRefID; this.primaryFrameLayout = primaryFrameLayout; this.secondaryFrameLayout = secondaryFrameLayout; newDBHelper = new NextGenDB(act.getApplicationContext()); } public Stop getLastSuccessfullySearchedBusStop() { return lastSuccessfullySearchedBusStop; } public void setLastSuccessfullySearchedBusStop(Stop stop) { this.lastSuccessfullySearchedBusStop = stop; } /** * Called when you need to create a fragment for a specified Palina * @param p the Stop that needs to be displayed */ public void createOrUpdateStopFragment(Palina p){ boolean refreshing; ArrivalsFragment arrivalsFragment; if(act==null) { //SOMETHING WENT VERY WRONG return; } SwipeRefreshLayout srl = (SwipeRefreshLayout) act.findViewById(swipeRefID); FragmentManager fm = act.getSupportFragmentManager(); if(srl.isRefreshing()) refreshing=true; else if(fm.findFragmentById(R.id.resultFrame) instanceof ArrivalsFragment) { arrivalsFragment = (ArrivalsFragment) fm.findFragmentById(R.id.resultFrame); refreshing = arrivalsFragment.isFragmentForTheSameStop(p); } else refreshing = false; setLastSuccessfullySearchedBusStop(p); if(!refreshing) { //set the String to be displayed on the fragment String displayName = p.getStopDisplayName(); String displayStuff; if (displayName != null && displayName.length() > 0) { arrivalsFragment = ArrivalsFragment.newInstance(p.ID,displayName); } else { arrivalsFragment = ArrivalsFragment.newInstance(p.ID); } attachFragmentToContainer(fm,arrivalsFragment,true,ResultListFragment.getFragmentTag(p)); } else { Log.d("BusTO", "Same bus stop, accessing existing fragment"); arrivalsFragment = (ArrivalsFragment) fm.findFragmentById(R.id.resultFrame); } arrivalsFragment.setListAdapter(new PalinaAdapter(act.getApplicationContext(),p)); act.hideKeyboard(); toggleSpinner(false); } /** * Called when you need to display the results of a search of stops * @param resultList the List of stops found * @param query String queried */ public void createFragmentFor(List resultList,String query){ act.hideKeyboard(); StopListFragment listfragment = StopListFragment.newInstance(query); attachFragmentToContainer(act.getSupportFragmentManager(),listfragment,false,"search_"+query); listfragment.setStopList(resultList); toggleSpinner(false); } /** * Wrapper for toggleSpinner in Activity * @param on new status of spinner system */ public void toggleSpinner(boolean on){ if (act instanceof FragmentListener) ((FragmentListener) act).toggleSpinner(on); else { SwipeRefreshLayout srl = (SwipeRefreshLayout) act.findViewById(swipeRefID); srl.setRefreshing(false); } } /** * Attach a new fragment to a cointainer * @param fm the FragmentManager * @param fragment the Fragment * @param sendToSecondaryFrame needs to be displayed in secondary frame or not * @param tag tag for the fragment */ public void attachFragmentToContainer(FragmentManager fm,Fragment fragment, boolean sendToSecondaryFrame, String tag){ FragmentTransaction ft = fm.beginTransaction(); if(sendToSecondaryFrame && secondaryFrameLayout!=NO_FRAME) ft.replace(secondaryFrameLayout,fragment,tag); else ft.replace(primaryFrameLayout,fragment,tag); ft.addToBackStack("state_"+tag); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); ft.commit(); //fm.executePendingTransactions(); } synchronized public int insertBatchDataInNextGenDB(ContentValues[] valuesArr,String tableName){ if(newDBHelper !=null) return newDBHelper.insertBatchContent(valuesArr,tableName); else return -1; } synchronized public ContentResolver getContentResolver(){ return act.getContentResolver(); } /** * Wrapper to show the errors/status that happened * @param res result from Fetcher */ public void showErrorMessage(Fetcher.result res){ //TODO: implement a common set of errors for all fragments switch (res){ case OK: break; case CLIENT_OFFLINE: act.showMessage(R.string.network_error); break; case SERVER_ERROR: if (act.isConnected()) { act.showMessage(R.string.parsing_error); } else { act.showMessage(R.string.network_error); } case PARSER_ERROR: default: act.showMessage(R.string.internal_error); break; case QUERY_TOO_SHORT: act.showMessage(R.string.query_too_short); break; case EMPTY_RESULT_SET: act.showMessage(R.string.no_bus_stop_have_this_name); break; } } } diff --git a/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java b/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java index 1227fbe..55cf9de 100644 --- a/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java +++ b/src/it/reyboz/bustorino/fragments/NearbyStopsFragment.java @@ -1,290 +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.GridView; 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.middleware.SquareStopAdapter; +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 GridView gV; + 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; + 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); - gV = (GridView) root.findViewById(R.id.stopGridNearby); + 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); 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); - gV.setAdapter(null); + 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){ - gV.setAdapter(madapter); + gridRecyclerView.setAdapter(madapter); loadingProgressBar.setVisibility(View.GONE); } Log.d(DEBUG_TAG,"OnResume called"); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - gV.setVisibility(View.INVISIBLE); - gV.setOnScrollListener(new CommonScrollListener(mListener,false)); + gridRecyclerView.setVisibility(View.INVISIBLE); + gridRecyclerView.setOnScrollListener(new CommonScrollListener(mListener,false)); } @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); - madapter.sort(new StopSorterByDistance(lastReceivedLocation)); - gV.setAdapter(madapter); - if (gV.getVisibility() != View.VISIBLE) { + gridRecyclerView.setAdapter(madapter); + if (gridRecyclerView.getVisibility() != View.VISIBLE) { loadingProgressBar.setVisibility(View.GONE); - gV.setVisibility(View.VISIBLE); + 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/fragments/StopListFragment.java b/src/it/reyboz/bustorino/fragments/StopListFragment.java index a6f7e59..e27f3de 100644 --- a/src/it/reyboz/bustorino/fragments/StopListFragment.java +++ b/src/it/reyboz/bustorino/fragments/StopListFragment.java @@ -1,145 +1,145 @@ /* 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.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.util.Log; import it.reyboz.bustorino.backend.Route; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.middleware.AppDataProvider; import it.reyboz.bustorino.middleware.NextGenDB.Contract.StopsTable; -import it.reyboz.bustorino.middleware.StopAdapter; +import it.reyboz.bustorino.adapters.StopAdapter; import java.util.Arrays; import java.util.List; public class StopListFragment extends ResultListFragment implements LoaderManager.LoaderCallbacks { private List stopList; private StopAdapter mListAdapter; private static final String[] dataProjection={StopsTable.COL_LINES_STOPPING,StopsTable.COL_PLACE,StopsTable.COL_TYPE,StopsTable.COL_LOCATION}; private static final String KEY_STOP_ID = "stopID"; private static final String WORDS_SEARCHED= "query"; private static final int EXTRA_ID=160; private String searchedWords; public StopListFragment(){ //required empty constructor } public static StopListFragment newInstance(String searchQuery) { Bundle args = new Bundle(); //TODO: search stops inside the DB args.putString(WORDS_SEARCHED,searchQuery); StopListFragment fragment = new StopListFragment(); args.putSerializable(LIST_TYPE,FragmentKind.STOPS); fragment.setArguments(args); return fragment; } public void setStopList(List stopList){ this.stopList = stopList; } @Override public void onResume() { super.onResume(); LoaderManager loaderManager = getLoaderManager(); if(stopList!=null) { mListAdapter = new StopAdapter(getContext(),stopList); setListAdapter(mListAdapter); for (int i = 0; i < stopList.size(); i++) { final Bundle b = new Bundle(); b.putString(KEY_STOP_ID, stopList.get(i).ID); loaderManager.restartLoader(i, b, this); } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); searchedWords = getArguments().getString(WORDS_SEARCHED); } @Override public Loader onCreateLoader(int id, Bundle args) { //The id will be the position of the element in the list Uri.Builder builder = new Uri.Builder(); String stopID = args.getString(KEY_STOP_ID); //Log.d("StopListLoader","Creating loader for stop "+stopID+" in position: "+id); if(stopID!=null) { builder.scheme("content").authority(AppDataProvider.AUTHORITY) .appendPath("stop").appendPath(stopID); CursorLoader cursorLoader = new CursorLoader(getContext(),builder.build(),dataProjection,null,null,null); return cursorLoader; } else return null; } @Override public void onLoadFinished(Loader loader, Cursor data) { //check that we have valid data if(data==null) return; final int numRows = data.getCount(); final int elementIdx = loader.getId(); if (numRows==0) { Log.w(this.getClass().getName(),"No info for stop in position "+elementIdx); return; } else if(numRows>1){ Log.d("StopLoading","we have "+numRows+" rows, should only have 1. Taking the first..."); } final int linesIndex = data.getColumnIndex(StopsTable.COL_LINES_STOPPING); data.moveToFirst(); Stop stopToModify = stopList.get(elementIdx); final String linesStopping = data.getString(linesIndex); stopToModify.setRoutesThatStopHere(Arrays.asList(linesStopping.split(","))); try { final String possibleLocation = data.getString(data.getColumnIndexOrThrow(StopsTable.COL_LOCATION)); if (stopToModify.location == null && possibleLocation != null && !possibleLocation.isEmpty() && !possibleLocation.equals("_")) { stopToModify.location = possibleLocation; } if (stopToModify.type == null) { stopToModify.type = Route.Type.fromCode(data.getInt(data.getColumnIndex(StopsTable.COL_TYPE))); } }catch (IllegalArgumentException arg){ if(arg.getMessage().contains("'location' does not exist")) Log.w("StopLoading","stop with no location found"); } //Log.d("StopListFragmentLoader","Finished parsing data for stop in position "+elementIdx); mListAdapter.notifyDataSetChanged(); } @Override public void onLoaderReset(Loader loader) { loader.abandon(); } }