diff --git a/app/src/main/java/it/reyboz/bustorino/adapters/OnStopClickListener.kt b/app/src/main/java/it/reyboz/bustorino/adapters/OnStopClickListener.kt new file mode 100644 index 0000000..eab4c31 --- /dev/null +++ b/app/src/main/java/it/reyboz/bustorino/adapters/OnStopClickListener.kt @@ -0,0 +1,7 @@ +package it.reyboz.bustorino.adapters + +import it.reyboz.bustorino.backend.Stop + +fun interface OnStopClickListener { + fun onStopClick(stop: Stop) +} \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/adapters/SquareStopAdapter.java b/app/src/main/java/it/reyboz/bustorino/adapters/StopNearbyAdapter.java similarity index 73% rename from app/src/main/java/it/reyboz/bustorino/adapters/SquareStopAdapter.java rename to app/src/main/java/it/reyboz/bustorino/adapters/StopNearbyAdapter.java index 97c480d..2fe7464 100644 --- a/app/src/main/java/it/reyboz/bustorino/adapters/SquareStopAdapter.java +++ b/app/src/main/java/it/reyboz/bustorino/adapters/StopNearbyAdapter.java @@ -1,161 +1,181 @@ /* 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 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.Stop; import it.reyboz.bustorino.util.StopSorterByDistance; import it.reyboz.bustorino.fragments.FragmentListenerMain; +import org.jetbrains.annotations.NotNull; -import java.util.Collections; +import java.util.ArrayList; import java.util.List; -public class SquareStopAdapter extends RecyclerView.Adapter { +public class StopNearbyAdapter extends RecyclerView.Adapter { private final static int layoutRes = R.layout.item_stop_nearby_card; //private List stops; private @Nullable GPSPoint userPosition; - private FragmentListenerMain listener; - private List stops; + private OnStopClickListener listener; + private boolean showLocation; + private ArrayList stops; - public SquareStopAdapter(@Nullable List stopList, FragmentListenerMain fragmentListener, @Nullable GPSPoint pos) { + public StopNearbyAdapter(@NotNull ArrayList stopList, + @Nullable GPSPoint pos, boolean showLocation, OnStopClickListener fragmentListener) { listener = fragmentListener; userPosition = pos; stops = stopList; + this.showLocation = showLocation; } @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)); + if (userPosition!=null) { + if (stops != null && stops.size() > 0) + stops.sort(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 + if(stops==null || stops.isEmpty()) return; //NO STOPS final Stop stop = stops.get(position); final Context context = holder.itemView.getContext(); if(stop!=null){ - if(stop.getDistanceFromLocation(userPosition)!=Double.POSITIVE_INFINITY){ + if(userPosition!=null && stop.getDistanceFromLocation(userPosition)!=Double.POSITIVE_INFINITY){ Double distance = stop.getDistanceFromLocation(userPosition); holder.distancetextView.setText(distance.intValue()+" m"); + holder.distancetextView.setVisibility(View.VISIBLE); } else { holder.distancetextView.setVisibility(View.GONE); } holder.stopNameView.setText(context.getString( R.string.two_strings_format,"", stop.getStopDisplayName())); // stop.ID +" - "+ stop.getStopDisplayName()); holder.stopIDView.setText(stop.ID); String whatStopsHere = stop.routesThatStopHereToString(); if(whatStopsHere == null) { holder.routesView.setVisibility(View.GONE); } else { - holder.routesView.setText(context.getString(R.string.lines_fill, whatStopsHere)); + holder.routesView.setText(whatStopsHere); + //context.getString(R.string.lines_fill, whatStopsHere)); holder.routesView.setVisibility(View.VISIBLE); // might be GONE due to View Holder Pattern } - holder.stopID =stop.ID; + holder.itemView.setOnClickListener(view -> {listener.onStopClick(stop);}); + if (showLocation && !( + stop.location==null || stop.location.isEmpty() || stop.location.contains("null")) + ){ + holder.locationTextView.setText(stop.location); + holder.locationTextView.setVisibility(View.VISIBLE); + } else { + holder.locationTextView.setVisibility(View.GONE); + } } else { Log.w("SquareStopAdapter","!! The selected stop is null !!"); } } @Override public int getItemCount() { return stops.size(); } - class SquareViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { + class SquareViewHolder extends RecyclerView.ViewHolder { TextView stopIDView; TextView stopNameView; + TextView locationTextView; TextView routesView; TextView distancetextView; - String stopID; + //Stop stop; SquareViewHolder(View holdView){ super(holdView); - holdView.setOnClickListener(this); + //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); + locationTextView = holdView.findViewById(R.id.stop_locationTextView); distancetextView = (TextView) holdView.findViewById(R.id.stop_distanceTextView); } - @Override + /*@Override public void onClick(View v) { - listener.requestArrivalsForStopID(stopID); + listener.onStopClick(stop); } + */ + } 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/data/NextGenDB.java b/app/src/main/java/it/reyboz/bustorino/data/NextGenDB.java index f5a408a..2d7d504 100644 --- a/app/src/main/java/it/reyboz/bustorino/data/NextGenDB.java +++ b/app/src/main/java/it/reyboz/bustorino/data/NextGenDB.java @@ -1,698 +1,720 @@ /* BusTO (middleware) 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.data; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.*; import android.net.Uri; import android.provider.BaseColumns; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import it.reyboz.bustorino.backend.Palina; import it.reyboz.bustorino.backend.Result; import it.reyboz.bustorino.backend.Route; import it.reyboz.bustorino.backend.Stop; import java.util.*; import java.util.stream.Collectors; import static it.reyboz.bustorino.data.NextGenDB.Contract.*; public class NextGenDB extends SQLiteOpenHelper{ public static final String DATABASE_NAME = "bustodatabase.db"; public static final int DATABASE_VERSION = 3; public static final String DEBUG_TAG = "NextGenDB-BusTO"; //NO Singleton instance //private static volatile NextGenDB instance = null; //Some generating Strings private static final String SQL_CREATE_LINES_TABLE="CREATE TABLE "+Contract.LinesTable.TABLE_NAME+" ("+ Contract.LinesTable._ID +" INTEGER PRIMARY KEY AUTOINCREMENT, "+ Contract.LinesTable.COLUMN_NAME +" TEXT, "+ Contract.LinesTable.COLUMN_DESCRIPTION +" TEXT, "+Contract.LinesTable.COLUMN_TYPE +" TEXT, "+ "UNIQUE ("+LinesTable.COLUMN_NAME+","+LinesTable.COLUMN_DESCRIPTION+","+LinesTable.COLUMN_TYPE+" ) "+" )"; private static final String SQL_CREATE_BRANCH_TABLE="CREATE TABLE "+Contract.BranchesTable.TABLE_NAME+" ("+ Contract.BranchesTable._ID +" INTEGER, "+ Contract.BranchesTable.COL_BRANCHID +" INTEGER PRIMARY KEY, "+ Contract.BranchesTable.COL_LINE +" INTEGER, "+ Contract.BranchesTable.COL_DESCRIPTION +" TEXT, "+ Contract.BranchesTable.COL_DIRECTION+" TEXT, "+ Contract.BranchesTable.COL_TYPE +" INTEGER, "+ //SERVICE DAYS: 0 => FERIALE,1=>FESTIVO,-1=>UNKNOWN,add others if necessary Contract.BranchesTable.COL_FESTIVO +" INTEGER, "+ //DAYS COLUMNS. IT'S SO TEDIOUS I TRIED TO KILL MYSELF BranchesTable.COL_LUN+" INTEGER, "+BranchesTable.COL_MAR+" INTEGER, "+BranchesTable.COL_MER+" INTEGER, "+BranchesTable.COL_GIO+" INTEGER, "+ BranchesTable.COL_VEN+" INTEGER, "+ BranchesTable.COL_SAB+" INTEGER, "+BranchesTable.COL_DOM+" INTEGER, "+ "FOREIGN KEY("+ Contract.BranchesTable.COL_LINE +") references "+ Contract.LinesTable.TABLE_NAME+"("+ Contract.LinesTable._ID+") " +")"; private static final String SQL_CREATE_CONNECTIONS_TABLE="CREATE TABLE "+Contract.ConnectionsTable.TABLE_NAME+" ("+ Contract.ConnectionsTable.COLUMN_BRANCH+" INTEGER, "+ Contract.ConnectionsTable.COLUMN_STOP_ID+" TEXT, "+ Contract.ConnectionsTable.COLUMN_ORDER+" INTEGER, "+ "PRIMARY KEY ("+ Contract.ConnectionsTable.COLUMN_BRANCH+","+ Contract.ConnectionsTable.COLUMN_STOP_ID + "), "+ "FOREIGN KEY("+ Contract.ConnectionsTable.COLUMN_BRANCH+") references "+ Contract.BranchesTable.TABLE_NAME+"("+ Contract.BranchesTable.COL_BRANCHID +"), "+ "FOREIGN KEY("+ Contract.ConnectionsTable.COLUMN_STOP_ID+") references "+ Contract.StopsTable.TABLE_NAME+"("+ Contract.StopsTable.COL_ID +") " +")"; private static final String SQL_CREATE_STOPS_TABLE="CREATE TABLE "+Contract.StopsTable.TABLE_NAME+" ("+ Contract.StopsTable.COL_ID+" TEXT PRIMARY KEY, "+ Contract.StopsTable.COL_TYPE+" INTEGER, "+Contract.StopsTable.COL_LAT+" REAL NOT NULL, "+ Contract.StopsTable.COL_LONG+" REAL NOT NULL, "+ Contract.StopsTable.COL_NAME+" TEXT NOT NULL, "+ StopsTable.COL_GTFS_ID+" TEXT, "+ Contract.StopsTable.COL_LOCATION+" TEXT, "+Contract.StopsTable.COL_PLACE+" TEXT, "+ Contract.StopsTable.COL_LINES_STOPPING +" TEXT )"; private static final String SQL_CREATE_STOPS_TABLE_TO_COMPLETE = " ("+ Contract.StopsTable.COL_ID+" TEXT PRIMARY KEY, "+ Contract.StopsTable.COL_TYPE+" INTEGER, "+Contract.StopsTable.COL_LAT+" REAL NOT NULL, "+ Contract.StopsTable.COL_LONG+" REAL NOT NULL, "+ Contract.StopsTable.COL_NAME+" TEXT NOT NULL, "+ Contract.StopsTable.COL_LOCATION+" TEXT, "+Contract.StopsTable.COL_PLACE+" TEXT, "+ Contract.StopsTable.COL_LINES_STOPPING +" TEXT )"; public static final String[] QUERY_COLUMN_stops_all = { StopsTable.COL_ID, StopsTable.COL_NAME, StopsTable.COL_GTFS_ID, StopsTable.COL_LOCATION, StopsTable.COL_TYPE, StopsTable.COL_LAT, StopsTable.COL_LONG, StopsTable.COL_LINES_STOPPING}; public static final String QUERY_WHERE_LAT_AND_LNG_IN_RANGE = StopsTable.COL_LAT + " >= ? AND " + StopsTable.COL_LAT + " <= ? AND "+ StopsTable.COL_LONG + " >= ? AND "+ StopsTable.COL_LONG + " <= ?"; public static final String QUERY_FROM_GTFS_ID_IN_TO_COMPLETE= StopsTable.COL_GTFS_ID +" IN "; public static String QUERY_WHERE_ID = StopsTable.COL_ID+" = ?"; public static final int RESULT_SQLITE_ERROR = -4; private final Context appContext; private final InvalidationTracker invalidationTracker = new InvalidationTracker(); private static NextGenDB INSTANCE; private NextGenDB(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); appContext = context.getApplicationContext(); } public static NextGenDB getInstance(Context context) { if (INSTANCE == null){ INSTANCE = new NextGenDB(context.getApplicationContext()); } return INSTANCE; } @Override public void onCreate(SQLiteDatabase db) { Log.d("BusTO-AppDB","Lines creating database:\n"+SQL_CREATE_LINES_TABLE+"\n"+ SQL_CREATE_STOPS_TABLE+"\n"+SQL_CREATE_BRANCH_TABLE+"\n"+SQL_CREATE_CONNECTIONS_TABLE); db.execSQL(SQL_CREATE_LINES_TABLE); db.execSQL(SQL_CREATE_STOPS_TABLE); //tables with constraints db.execSQL(SQL_CREATE_BRANCH_TABLE); db.execSQL(SQL_CREATE_CONNECTIONS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if(oldVersion<2 && newVersion == 2){ //DROP ALL TABLES db.execSQL("DROP TABLE "+ConnectionsTable.TABLE_NAME); db.execSQL("DROP TABLE "+BranchesTable.TABLE_NAME); db.execSQL("DROP TABLE "+LinesTable.TABLE_NAME); db.execSQL("DROP TABLE "+ StopsTable.TABLE_NAME); //RECREATE THE TABLES WITH THE NEW SCHEMA db.execSQL(SQL_CREATE_LINES_TABLE); db.execSQL(SQL_CREATE_STOPS_TABLE); //tables with constraints db.execSQL(SQL_CREATE_BRANCH_TABLE); db.execSQL(SQL_CREATE_CONNECTIONS_TABLE); //DatabaseUpdate.requestDBUpdateWithWork(appContext, true, true); DBUpdateWorker.requestDBUpdateUniqueWork(appContext, true); } if(oldVersion < 3 && newVersion == 3){ Log.d("BusTO-Database", "Running upgrades for version 3"); //add the new column db.execSQL("ALTER TABLE "+StopsTable.TABLE_NAME+ " ADD COLUMN "+StopsTable.COL_GTFS_ID+" TEXT "); // DatabaseUpdate.requestDBUpdateWithWork(appContext, true); } } @Override public void onConfigure(SQLiteDatabase db) { super.onConfigure(db); db.execSQL("PRAGMA foreign_keys=ON"); } public static String getSqlCreateStopsTable(String tableName){ return "CREATE TABLE "+tableName+" ("+ Contract.StopsTable.COL_ID+" TEXT PRIMARY KEY, "+ Contract.StopsTable.COL_TYPE+" INTEGER, "+Contract.StopsTable.COL_LAT+" REAL NOT NULL, "+ Contract.StopsTable.COL_LONG+" REAL NOT NULL, "+ Contract.StopsTable.COL_NAME+" TEXT NOT NULL, "+ Contract.StopsTable.COL_LOCATION+" TEXT, "+Contract.StopsTable.COL_PLACE+" TEXT, "+ Contract.StopsTable.COL_LINES_STOPPING +" TEXT )"; } /** * Query some bus stops inside a map view * @return stoplist, if empty it means that an error occurred * * You can obtain the coordinates from OSMDroid using something like this: * BoundingBoxE6 bb = mMapView.getBoundingBox(); * double latFrom = bb.getLatSouthE6() / 1E6; * double latTo = bb.getLatNorthE6() / 1E6; * double lngFrom = bb.getLonWestE6() / 1E6; * double lngTo = bb.getLonEastE6() / 1E6; */ @NonNull public synchronized Result> queryAllInsideMapView(double minLat, double maxLat, double minLng, double maxLng) { ArrayList stops = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); // coordinates must be strings in the where condition String minLatRaw = String.valueOf(minLat); String maxLatRaw = String.valueOf(maxLat); String minLngRaw = String.valueOf(minLng); String maxLngRaw = String.valueOf(maxLng); if(db == null) { return Result.failure(new SQLiteException("Database is null")); } try (final Cursor result = db.query(StopsTable.TABLE_NAME, QUERY_COLUMN_stops_all, QUERY_WHERE_LAT_AND_LNG_IN_RANGE, new String[] {minLatRaw, maxLatRaw, minLngRaw, maxLngRaw}, null, null, null)) { stops = getStopsFromCursorAllFields(result); } catch(SQLiteException e) { Log.e(DEBUG_TAG, "SQLiteException occurred"); return Result.failure(e); }catch (Exception e){ Log.e(DEBUG_TAG, "Exception occurred when getting stops"); return Result.failure(e); } return Result.success(stops); } @NonNull public QueryLiveData> queryAllInsideMapViewLiveData(double minLat, double maxLat, double minLng, double maxLng) { return new QueryLiveData<>(List.of(StopsTable.TABLE_NAME), invalidationTracker,()->{ Result> queryResult = queryAllInsideMapView(minLat, maxLat, minLng, maxLng); if(queryResult.isSuccess()){ return queryResult.result; } else{ Log.w(DEBUG_TAG, "queryAllInsideMapViewLiveData failed", queryResult.exception); return new ArrayList<>(); } }); } /** * Query stops in the database having these IDs * @param bustoDB readable database instance * @param gtfsIDs gtfs IDs to query * @return list of stops */ @NonNull public static synchronized Result> queryAllStopsWithGtfsIDs(@NonNull SQLiteDatabase bustoDB,@NonNull List gtfsIDs){ final ArrayList stops = new ArrayList<>(); if (gtfsIDs.isEmpty()) { return Result.success(stops); } final StringBuilder builder = new StringBuilder(QUERY_FROM_GTFS_ID_IN_TO_COMPLETE); boolean first = true; builder.append(" ( "); for(int i=0; i< gtfsIDs.size(); i++){ if(first){ first = false; } else{ builder.append(", "); } builder.append("?");//.append("\"").append(id).append("\""); } builder.append(") "); final String whereClause = builder.toString(); final String[] idsQuery = gtfsIDs.toArray(new String[0]); try(Cursor result = bustoDB.query(StopsTable.TABLE_NAME,QUERY_COLUMN_stops_all, whereClause, idsQuery, null, null, null)) { stops.addAll(getStopsFromCursorAllFields(result)); } catch(SQLiteException e) { Log.w(DEBUG_TAG, "SQLiteException occurred in getting stops"); return Result.failure(e); } return Result.success(stops); } public static String buildWhereClause(String colName, List args){ final StringBuilder builder = new StringBuilder().append(colName).append(" IN "); boolean first = true; builder.append(" ( "); for(int i=0; i< args.size(); i++){ if(first){ first = false; } else{ builder.append(", "); } builder.append("?"); } builder.append(") "); return builder.toString(); } /** * Query stops in the database having these IDs * @param bustoDB readable database instance * @param stopIds to query * @return list of stops */ @NonNull public static synchronized Result> queryStopsWithStopIds(@NonNull SQLiteDatabase bustoDB,@NonNull List stopIds){ ArrayList stops = null; if (stopIds.isEmpty()) { return Result.success(stops); } final StringBuilder builder = new StringBuilder().append(StopsTable.COL_ID).append(" IN "); boolean first = true; builder.append(" ( "); for(int i=0; i< stopIds.size(); i++){ if(first){ first = false; } else{ builder.append(", "); } builder.append("?");//.append("\"").append(id).append("\""); } builder.append(") "); final String whereClause = builder.toString(); Log.d(DEBUG_TAG, "Asking for all stops with IDs, query: "+whereClause); final String[] idsQuery = stopIds.toArray(new String[0]); try(Cursor result = bustoDB.query(StopsTable.TABLE_NAME,QUERY_COLUMN_stops_all, whereClause, idsQuery, null, null, null)) { stops = getStopsFromCursorAllFields(result); } catch(SQLiteException e) { Log.e(DEBUG_TAG, "SQLiteException occurred"); return Result.failure(e); } return Result.success(stops); } @NonNull public QueryLiveData> queryStopsWithStopIdsLiveData(@NonNull List stopIds){ return new QueryLiveData<>(List.of(StopsTable.TABLE_NAME), invalidationTracker, ()->{ Log.d(DEBUG_TAG, "Table stops changed, redoing query"); SQLiteDatabase db = this.getReadableDatabase(); Result> result = queryStopsWithStopIds(db, stopIds); if(result.isSuccess()){ return result.result; } else{ return null; } }); } + @NonNull + public synchronized List searchStopsByCodeOrName(String query, boolean searchById){ + String escaped = query.replace("\\", "\\\\") + .replace("%", "\\%") + .replace("_", "\\_"); + String sql; + final String like = "%" + escaped + "%"; + if (searchById){ + sql = "SELECT * FROM "+StopsTable.TABLE_NAME+" WHERE "+StopsTable.COL_ID+" LIKE ? ESCAPE '\\'"; + } else{ + sql = "SELECT * FROM "+StopsTable.TABLE_NAME+" WHERE "+StopsTable.COL_NAME+" LIKE ? ESCAPE '\\'"; + } + final List out = new ArrayList<>(); + SQLiteDatabase db = getReadableDatabase(); + try (Cursor c= db.rawQuery(sql, new String[]{like} + ) ) { + out.addAll(getStopsFromCursorAllFields(c)); + } + + return out; + } + /** * Get the list of stop in the query, with all the possible fields {NextGenDB.QUERY_COLUMN_stops_all} * @param result cursor from query * @return an Array of the stops found in the query */ public static ArrayList getStopsFromCursorAllFields(Cursor result){ final int colID = result.getColumnIndex(StopsTable.COL_ID); final int colName = result.getColumnIndex(StopsTable.COL_NAME); final int colLocation = result.getColumnIndex(StopsTable.COL_LOCATION); final int colType = result.getColumnIndex(StopsTable.COL_TYPE); final int colLat = result.getColumnIndex(StopsTable.COL_LAT); final int colGtfsID = result.getColumnIndex(StopsTable.COL_GTFS_ID); final int colLon = result.getColumnIndex(StopsTable.COL_LONG); final int colLines = result.getColumnIndex(StopsTable.COL_LINES_STOPPING); int count = result.getCount(); ArrayList stops = new ArrayList<>(count); int i = 0; while(result.moveToNext()) { final String stopID = result.getString(colID).trim(); Route.Type type; //if(result.getString(colType) == null) type = Route.Type.BUS; //else type = Route.getTypeFromSymbol(result.getString(colType)); //if(result.getInt(colType) == null) type = Route.Type.BUS; try{ type = Route.Type.fromCode(result.getInt(colType)); } catch (Exception e){ type = Route.Type.BUS; } String lines = result.getString(colLines).trim(); String locationSometimesEmpty = result.getString(colLocation); if (locationSometimesEmpty!= null && locationSometimesEmpty.length() <= 0) { locationSometimesEmpty = null; } stops.add(new Stop(stopID, result.getString(colName), null, locationSometimesEmpty, type, splitLinesString(lines), result.getDouble(colLat), result.getDouble(colLon), result.getString(colGtfsID)) ); } return stops; } public static boolean insertBranchesIntoDB(@NonNull Context context, @NonNull List routesToInsert){ final NextGenDB nextGenDB = NextGenDB.getInstance(context); //ContentValues[] values = new ContentValues[routesToInsert.size()]; ArrayList branchesValues = new ArrayList<>(routesToInsert.size()); ArrayList connectionsVals = new ArrayList<>(routesToInsert.size()); long starttime,endtime; for (Route r:routesToInsert){ //if it has received an interrupt, stop if(Thread.interrupted()) return false; //otherwise, build contentValues final ContentValues cv = createContentValuesBranch(r); branchesValues.add(cv); if(r.getStopsList() != null) for(int i=0; i palinas, HashMap> routesStoppingByStop){ SQLiteDatabase db = getWritableDatabase(); boolean completed = false; if(!db.isOpen()){ //catch errors like: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase //we have to abort the work and restart it return completed; } int patternsStopsHits = 0; long startTime = System.currentTimeMillis(); try { //TODO: Get the type of stop from the lines //Empty the needed tables db.beginTransaction(); //put new data Log.d(DEBUG_TAG, "Inserting " + palinas.size() + " stops"); String routesStoppingString = ""; for (final Palina p : palinas) { final ContentValues cv = new ContentValues(); cv.put(StopsTable.COL_ID, p.ID); cv.put(StopsTable.COL_NAME, p.getStopDefaultName()); if (p.location != null) cv.put(StopsTable.COL_LOCATION, p.location); cv.put(StopsTable.COL_LAT, p.getLatitude()); cv.put(StopsTable.COL_LONG, p.getLongitude()); if (p.getAbsurdGTTPlaceName() != null) cv.put(StopsTable.COL_PLACE, p.getAbsurdGTTPlaceName()); if (p.gtfsID != null && routesStoppingByStop.containsKey(p.gtfsID)) { final ArrayList routesSs = new ArrayList<>(routesStoppingByStop.get(p.gtfsID)); routesStoppingString = Palina.buildRoutesStringFromNames(routesSs); patternsStopsHits++; } else { routesStoppingString = p.routesThatStopHereToString(); } cv.put(StopsTable.COL_LINES_STOPPING, routesStoppingString); if (p.type != null) cv.put(StopsTable.COL_TYPE, p.type.getCode()); if (p.gtfsID != null) cv.put(StopsTable.COL_GTFS_ID, p.gtfsID); //Log.d(DEBUG_TAG,cv.toString()); //cpOp.add(ContentProviderOperation.newInsert(uritobeused).withValues(cv).build()); //valuesArr[i] = cv; db.replace(StopsTable.TABLE_NAME, null, cv); } db.setTransactionSuccessful(); completed = true; }catch (SQLException exc){ Log.w(DEBUG_TAG, "SQlite Exception: " + exc.getMessage()); } finally { db.endTransaction(); } long endTime = System.currentTimeMillis(); Log.d(DEBUG_TAG, "Inserting stops took: " + ((double) (endTime - startTime) / 1000) + " s, successful: "+completed); Log.d(DEBUG_TAG, "\t"+patternsStopsHits+" routes string were built from the patterns"); if(completed){ invalidationTracker.notifyInvalidation(StopsTable.TABLE_NAME); } return completed; } @NonNull private static ContentValues createContentValuesBranch(Route r) { final ContentValues cv = new ContentValues(); cv.put(BranchesTable.COL_BRANCHID, r.branchid); cv.put(LinesTable.COLUMN_NAME, r.getName()); cv.put(BranchesTable.COL_DIRECTION, r.destinazione); cv.put(BranchesTable.COL_DESCRIPTION, r.description); for (int day : r.serviceDays) { switch (day){ case Calendar.MONDAY: cv.put(BranchesTable.COL_LUN,1); break; case Calendar.TUESDAY: cv.put(BranchesTable.COL_MAR,1); break; case Calendar.WEDNESDAY: cv.put(BranchesTable.COL_MER,1); break; case Calendar.THURSDAY: cv.put(BranchesTable.COL_GIO,1); break; case Calendar.FRIDAY: cv.put(BranchesTable.COL_VEN,1); break; case Calendar.SATURDAY: cv.put(BranchesTable.COL_SAB,1); break; case Calendar.SUNDAY: cv.put(BranchesTable.COL_DOM,1); break; } } if(r.type!=null) cv.put(BranchesTable.COL_TYPE, r.type.getCode()); cv.put(BranchesTable.COL_FESTIVO, r.festivo.getCode()); return cv; } /* static ArrayList createStopListFromCursor(Cursor data){ ArrayList stopList = new ArrayList<>(); 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); data.moveToFirst(); for(int i=0; i 0) { invalidationTracker.notifyInvalidation(tableName); // ✅ Notify only after confirmed commit } return success; } public static List splitLinesString(String linesStr){ return Arrays.asList(linesStr.split("\\s*,\\s*")); } public static final class Contract{ //Ok, I get it, it really is a pain in the ass.. // But it's the only way to have maintainable code public interface DataTables { String getTableName(); String[] getFields(); } public static final class LinesTable implements BaseColumns, DataTables { //The fields public static final String TABLE_NAME = "lines"; public static final String COLUMN_NAME = "line_name"; public static final String COLUMN_DESCRIPTION = "line_description"; public static final String COLUMN_TYPE = "line_bacino"; @Override public String getTableName() { return TABLE_NAME; } @Override public String[] getFields() { return new String[]{COLUMN_NAME,COLUMN_DESCRIPTION,COLUMN_TYPE}; } } public static final class BranchesTable implements BaseColumns, DataTables { public static final String TABLE_NAME = "branches"; public static final String COL_BRANCHID = "branchid"; public static final String COL_LINE = "lineid"; public static final String COL_DESCRIPTION = "branch_description"; public static final String COL_DIRECTION = "branch_direzione"; public static final String COL_FESTIVO = "branch_festivo"; public static final String COL_TYPE = "branch_type"; public static final String COL_LUN="runs_lun"; public static final String COL_MAR="runs_mar"; public static final String COL_MER="runs_mer"; public static final String COL_GIO="runs_gio"; public static final String COL_VEN="runs_ven"; public static final String COL_SAB="runs_sab"; public static final String COL_DOM="runs_dom"; @Override public String getTableName() { return TABLE_NAME; } @Override public String[] getFields() { return new String[]{COL_BRANCHID,COL_LINE,COL_DESCRIPTION, COL_DIRECTION,COL_FESTIVO,COL_TYPE, COL_LUN,COL_MAR,COL_MER,COL_GIO,COL_VEN,COL_SAB,COL_DOM }; } } public static final class ConnectionsTable implements DataTables { public static final String TABLE_NAME = "connections"; public static final String COLUMN_BRANCH = "branchid"; public static final String COLUMN_STOP_ID = "stopid"; public static final String COLUMN_ORDER = "ordine"; @Override public String getTableName() { return TABLE_NAME; } @Override public String[] getFields() { return new String[]{COLUMN_STOP_ID,COLUMN_BRANCH,COLUMN_ORDER}; } } public static final class StopsTable implements DataTables { public static final String TABLE_NAME = "stops"; public static final String COL_ID = "stopid"; //integer public static final String COL_TYPE = "stop_type"; public static final String COL_NAME = "stop_name"; public static final String COL_GTFS_ID = "gtfs_id"; public static final String COL_LAT = "stop_latitude"; public static final String COL_LONG = "stop_longitude"; public static final String COL_LOCATION = "stop_location"; public static final String COL_PLACE = "stop_placeName"; public static final String COL_LINES_STOPPING = "stop_lines"; @Override public String getTableName() { return TABLE_NAME; } @Override public String[] getFields() { return new String[]{COL_ID,COL_TYPE,COL_NAME,COL_GTFS_ID,COL_LAT,COL_LONG,COL_LOCATION,COL_PLACE,COL_LINES_STOPPING}; } } } public static final class DBUpdatingException extends Exception{ public DBUpdatingException(String message) { super(message); } } } diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java b/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java index f8d3020..00af54b 100644 --- a/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java +++ b/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java @@ -1,974 +1,1098 @@ /* BusTO - Fragments components 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.fragments; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; +import android.text.InputType; +import android.widget.TextView; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageButton; +import androidx.appcompat.widget.SearchView; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.app.ActivityCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.ViewModelProvider; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.material.floatingactionbutton.FloatingActionButton; +import java.util.ArrayList; +import java.util.List; import java.util.Map; -import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import it.reyboz.bustorino.BuildConfig; import it.reyboz.bustorino.R; +import it.reyboz.bustorino.adapters.StopNearbyAdapter; import it.reyboz.bustorino.backend.*; import it.reyboz.bustorino.util.Permissions; import it.reyboz.bustorino.viewmodels.IntroViewModel; +import it.reyboz.bustorino.viewmodels.SearchStopsDBViewModel; import org.jetbrains.annotations.NotNull; import static it.reyboz.bustorino.util.Permissions.LOCATION_PERMISSIONS; /** * A simple {@link Fragment} subclass. * Use the {@link MainScreenFragment#newInstance} factory method to * create an instance of this fragment. */ public class MainScreenFragment extends BarcodeFragment implements FragmentListenerMain, ParentFragmentManagerFromChild{ private static final String SAVED_FRAGMENT="saved_fragment"; private static final String DEBUG_TAG = "BusTO - MainFragment"; public static final String ARG_INITIAL_CONTENT = "initial_content"; public static final String ARG_STOP_ID = "pending_stop_id"; public static final String ARG_SEARCH_QUERY = "pending_search_query"; public final static String FRAGMENT_TAG = "MainScreenFragment"; private enum SearchMode {SEARCH_ID,SEARCH_NAME,INITIAL} - public enum InternalScreen { + public enum InitialScreen { HOME_BUTTONS(0), NEARBY_STOPS(1), ARRIVALS(2), STOP_SEARCH(3), NEARBY_ARRIVALS(4); public final int code; - InternalScreen(int code) { this.code = code; } + InitialScreen(int code) { this.code = code; } @Nullable - public static InternalScreen fromCode(int code) { - for (InternalScreen c : values()) if (c.code == code) return c; + public static InitialScreen fromCode(int code) { + for (InitialScreen c : values()) if (c.code == code) return c; return null; } @NonNull - public static InternalScreen fromFragmentKind(@NonNull FragmentKind kind){ + public static InitialScreen fromFragmentKind(@NonNull FragmentKind kind){ switch (kind){ - case HOME_BUTTONS -> { return InternalScreen.HOME_BUTTONS; } - case NEARBY_STOPS -> { return InternalScreen.NEARBY_STOPS; } - case FragmentKind.ARRIVALS -> { return InternalScreen.ARRIVALS; } - case FragmentKind.STOPS -> { return InternalScreen.STOP_SEARCH; } - case FragmentKind.NEARBY_ARRIVALS -> { return InternalScreen.NEARBY_ARRIVALS; } + case HOME_BUTTONS -> { return InitialScreen.HOME_BUTTONS; } + case NEARBY_STOPS -> { return InitialScreen.NEARBY_STOPS; } + case FragmentKind.ARRIVALS -> { return InitialScreen.ARRIVALS; } + case FragmentKind.STOPS -> { return InitialScreen.STOP_SEARCH; } + case FragmentKind.NEARBY_ARRIVALS -> { return InitialScreen.NEARBY_ARRIVALS; } default -> { throw new IllegalArgumentException("Unknown fragment kind"); } } } } private FragmentHelper fragmentHelper; private SwipeRefreshLayout swipeRefreshLayout; - private EditText busStopSearchByIDEditText; - private EditText busStopSearchByNameEditText; + //private EditText busStopSearchByIDEditText; + //private EditText busStopSearchByNameEditText; + + private SearchView busStopSearchView; private ProgressBar progressBar; private FloatingActionButton floatingActionButton; - /// VIEW MODELS in BaseFragment - + private SearchStopsDBViewModel searchStopsViewModel; private boolean setupOnStart = true; private boolean suppressArrivalsReload = false; private boolean initialScreenShown = false; private SearchMode searchMode = SearchMode.INITIAL; private FragmentManager childFragMan; /// LOCATION STUFF /// boolean pendingIntroRun = false; boolean pendingNearbyStopsFragmentRequest = false; boolean pendingNearbyAddToBackStack = false; boolean locationPermissionGranted, locationPermissionAsked = false; //// ACTIVITY ATTACHED (LISTENER /// private CommonFragmentListener mListener; private String pendingStopID = null; private String pendingSearchQuery = null; - private InternalScreen internalScreen = InternalScreen.HOME_BUTTONS; + private InitialScreen initialScreen = InitialScreen.HOME_BUTTONS; private CoordinatorLayout coordLayout; + private RecyclerView suggestionsRecyclerView; + private StopNearbyAdapter suggestionsAdapter = null; + private TextView stopSearchMessageTextView; + //this is really a hackish thing, but it works private final LinkedBlockingQueue thingsToDoOnStart = new LinkedBlockingQueue<>(); + private boolean isSearchModeById(){ + return searchMode != SearchMode.SEARCH_NAME; + } + + private void emptySearchQueryViewModel(){ + searchStopsViewModel.searchStops("",isSearchModeById()); + } private void refreshStop() { if(getContext() == null){ Log.w(DEBUG_TAG,"Asked to refresh stop but context is null"); return; } if (childFragMan.findFragmentById(R.id.resultFrame) instanceof ArrivalsFragment) { ArrivalsFragment fragment = (ArrivalsFragment) childFragMan.findFragmentById(R.id.resultFrame); if (fragment == null){ //we create a new fragment, which is WRONG Log.e("BusTO-RefreshStop", "Asking for refresh when there is no fragment"); } else{ //String stopName = fragment.getStopID(); fragment.requestArrivalsForTheFragment(); } } else { //we create a new fragment, which is WRONG Log.w(DEBUG_TAG, "Asked to refresh stop when there is no fragment"); } } private final ActivityResultLauncher requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<>() { @Override public void onActivityResult(Map result) { if (result == null) return; if (result.get(Manifest.permission.ACCESS_COARSE_LOCATION) == null || result.get(Manifest.permission.ACCESS_FINE_LOCATION) == null) return; Log.d(DEBUG_TAG, "Permissions for location are: " + result); if (Boolean.TRUE.equals(result.get(Manifest.permission.ACCESS_COARSE_LOCATION)) || Boolean.TRUE.equals(result.get(Manifest.permission.ACCESS_FINE_LOCATION))) { locationPermissionGranted = true; Log.w(DEBUG_TAG, "Starting position"); /*if (mListener != null && getContext() != null) { if (locationManager == null) locationManager = AppLocationManager.getInstance(getContext()); locationManager.addLocationRequestFor(requester); } */ // show nearby fragment //showNearbyStopsFragment(); Log.d(DEBUG_TAG, "We have location permission"); if (pendingNearbyStopsFragmentRequest) { showNearbyFragmentIfPossible(pendingNearbyAddToBackStack); pendingNearbyStopsFragmentRequest = false; } } if (pendingNearbyStopsFragmentRequest) pendingNearbyStopsFragmentRequest = false; } }); public MainScreenFragment() { // Required empty public constructor } - public static MainScreenFragment newInstance(@NonNull InternalScreen kind, + public static MainScreenFragment newInstance(@NonNull InitialScreen kind, @Nullable String stopId, @Nullable String query) { MainScreenFragment f = new MainScreenFragment(); f.setArguments(makeArgs(kind, stopId, query)); return f; } - public static MainScreenFragment newInstance(@NonNull InternalScreen kind, @Nullable Bundle args){ + public static MainScreenFragment newInstance(@NonNull InitialScreen kind, @Nullable Bundle args){ MainScreenFragment f = new MainScreenFragment(); if (args != null) { f.setArguments(args); } return f; } /** * Create the bundle for the arguments of the fragment * @param kind the kind of initial screen * @param stopId * @param query * @return */ - public static Bundle makeArgs(@NonNull InternalScreen kind, @Nullable String stopId, @Nullable String query) { + public static Bundle makeArgs(@NonNull InitialScreen kind, @Nullable String stopId, @Nullable String query) { Bundle b = new Bundle(); b.putInt(ARG_INITIAL_CONTENT, kind.code); if (stopId != null) b.putString(ARG_STOP_ID, stopId); if (query != null) b.putString(ARG_SEARCH_QUERY, query); return b; } public static Bundle makeArgsArrivals(@NonNull String stopID){ - return makeArgs(InternalScreen.ARRIVALS, stopID, null); + return makeArgs(InitialScreen.ARRIVALS, stopID, null); } public static Bundle makeArgsStops(@NonNull String query){ - return makeArgs(InternalScreen.STOP_SEARCH, query, null); + return makeArgs(InitialScreen.STOP_SEARCH, query, null); } public static Bundle makeArgsNearby(){ - return makeArgs(InternalScreen.NEARBY_STOPS, null, null); + return makeArgs(InitialScreen.NEARBY_STOPS, null, null); } public static Bundle makeArgsButtonsScreen(){ - return makeArgs(InternalScreen.HOME_BUTTONS, null, null); + return makeArgs(InitialScreen.HOME_BUTTONS, null, null); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { Log.d(DEBUG_TAG, "ARGS ARE NOT NULL: "+ args); if (args.containsKey(ARG_INITIAL_CONTENT)) { - int code = args.getInt(ARG_INITIAL_CONTENT, InternalScreen.HOME_BUTTONS.code); - InternalScreen parsed = InternalScreen.fromCode(code); - internalScreen = (parsed != null) ? parsed : InternalScreen.HOME_BUTTONS; + int code = args.getInt(ARG_INITIAL_CONTENT, InitialScreen.HOME_BUTTONS.code); + InitialScreen parsed = InitialScreen.fromCode(code); + initialScreen = (parsed != null) ? parsed : InitialScreen.HOME_BUTTONS; } String stopId = args.getString(ARG_STOP_ID); if (stopId != null) pendingSearchQuery = stopId; else pendingSearchQuery = args.getString(ARG_SEARCH_QUERY); } fragmentHelper = new FragmentHelper(this, getChildFragmentManager(), getContext(), R.id.resultFrame); - } @Override public boolean needToPopMainStackOnBack() { return fragmentHelper.needToPopMainStackOnBack(); } @Override public void setMainFragmentManagerTransition(boolean yes) { fragmentHelper.setMainFragmentManagerTransition(yes); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View root = inflater.inflate(R.layout.fragment_main_screen, container, false); /// UI ELEMENTS // - busStopSearchByIDEditText = root.findViewById(R.id.busStopSearchByIDEditText); - busStopSearchByNameEditText = root.findViewById(R.id.busStopSearchByNameEditText); + //busStopSearchByIDEditText = root.findViewById(R.id.busStopSearchByIDEditText); + //busStopSearchByNameEditText = root.findViewById(R.id.busStopSearchByNameEditText); + busStopSearchView = root.findViewById(R.id.busStopSearchView); progressBar = root.findViewById(R.id.progressBar); swipeRefreshLayout = root.findViewById(R.id.listRefreshLayout); floatingActionButton = root.findViewById(R.id.floatingActionButton); - busStopSearchByIDEditText.setSelectAllOnFocus(true); - busStopSearchByIDEditText + stopSearchMessageTextView = root.findViewById(R.id.stopSearchMessageTextView); + suggestionsRecyclerView = root.findViewById(R.id.suggestionsRecyclerView); + suggestionsRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL, false)); + EditText searchEditText = busStopSearchView.findViewById(androidx.appcompat.R.id.search_src_text); + searchEditText.setSelectAllOnFocus(true); + searchEditText.setOnFocusChangeListener( (view,hasFocus) ->{ + if(hasFocus){ + showFloatingActionButton(true); + } + }); + + busStopSearchView.setOnFocusChangeListener( (view, hasFocus) ->{ + if(hasFocus){ + showFloatingActionButton(true); + } + }); + //busStopSearchView.setSelectAllOnFocus(true); + /*busStopSearchByIDEditText .setOnEditorActionListener((v, actionId, event) -> { // IME_ACTION_SEARCH alphabetical option if (actionId == EditorInfo.IME_ACTION_SEARCH) { onSearchClick(v); return true; } return false; }); - busStopSearchByNameEditText + + */ + /*searchEditText .setOnEditorActionListener((v, actionId, event) -> { // IME_ACTION_SEARCH alphabetical option if (actionId == EditorInfo.IME_ACTION_SEARCH) { onSearchClick(v); return true; } return false; }); + */ + + busStopSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { + @Override + public boolean onQueryTextSubmit(String q) { + onSearchClick(null); + emptySearchQueryViewModel(); + return true; + } + + @Override + public boolean onQueryTextChange(String q) { + //Log.d(DEBUG_TAG, "Changed query text"); + searchStopsViewModel.searchStops(q, isSearchModeById()); + return true; + } + }); + swipeRefreshLayout .setOnRefreshListener(this::refreshStop); swipeRefreshLayout.setColorSchemeResources(R.color.blue_500, R.color.orange_500); coordLayout = root.findViewById(R.id.coord_layout); floatingActionButton.setImageResource(R.drawable.magnifying_glass_larger); floatingActionButton.setOnClickListener((this::onToggleKeyboardLayout)); - busStopSearchByIDEditText.setOnFocusChangeListener((v, hasFocus) -> { + /*busStopSearchByIDEditText.setOnFocusChangeListener((v, hasFocus) -> { //Log.d(DEBUG_TAG, "stop search by ID has focus: " + hasFocus); if(hasFocus) setSearchModeBusStopID(); }); busStopSearchByNameEditText.setOnFocusChangeListener((v, hasFocus) -> { //Log.d(DEBUG_TAG, "stop search by Name has focus: " + hasFocus); if(hasFocus) setSearchModeBusStopName(); }); + */ + AppCompatImageButton qrButton = root.findViewById(R.id.QRButton); qrButton.setOnClickListener(this::onQRButtonClick); AppCompatImageButton searchButton = root.findViewById(R.id.searchButton); searchButton.setOnClickListener(this::onSearchClick); // Fragment stuff childFragMan = getChildFragmentManager(); childFragMan.addOnBackStackChangedListener(() -> Log.d("BusTO Main Fragment", "BACK STACK CHANGED")); /* cr.setAccuracy(Criteria.ACCURACY_FINE); cr.setAltitudeRequired(false); cr.setBearingRequired(false); cr.setCostAllowed(true); cr.setPowerRequirement(Criteria.NO_REQUIREMENT); */ //locationManager = AppLocationManager.getInstance(requireContext()); IntroViewModel introViewModel = new ViewModelProvider(requireActivity()).get(IntroViewModel.class); introViewModel.getIntroIsRunning().observe(getViewLifecycleOwner(), isRunning -> { pendingIntroRun = isRunning; }); // TODO: Figure out how to go back to home when pressing home in the nav side bar /*fragShowingViewModel.getKindShowingFragment().observe(getViewLifecycleOwner(), kind -> { Log.w(DEBUG_TAG, "showing fragment kind: " + kind); try { var screenType = InternalScreen.fromFragmentKind(kind); if(screenType != internalScreen) { showDifferentSubFragments(screenType); internalScreen = screenType; } } catch (IllegalArgumentException e) { //ignored Log.d(DEBUG_TAG, "no update from fragment kind"); } }); */ Log.d(DEBUG_TAG, "OnCreateView, savedInstanceState null: "+(savedInstanceState==null)); return root; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - Log.d(DEBUG_TAG, "onViewCreated, SwipeRefreshLayout visible: "+(swipeRefreshLayout.getVisibility()==View.VISIBLE)); - Log.d(DEBUG_TAG, "Saved instance state is: "+savedInstanceState); - //Restore instance state - /*if (savedInstanceState!=null){ - Fragment fragment = getChildFragmentManager().getFragment(savedInstanceState, SAVED_FRAGMENT); - if (fragment!=null){ - getChildFragmentManager().beginTransaction().add(R.id.resultFrame, fragment).commit(); - setupOnStart = false; - } - } + Log.d(DEBUG_TAG, "onViewCreated, have savedInstanceState: "+ (savedInstanceState!=null) + + "; SwipeRefreshLayout visible: "+(swipeRefreshLayout.getVisibility()==View.VISIBLE)); + //Log.d(DEBUG_TAG, "Saved instance state is: "+savedInstanceState); + searchStopsViewModel = new ViewModelProvider(requireActivity()).get(SearchStopsDBViewModel.class); + + searchStopsViewModel.getFilteredStopsSearch().observe(getViewLifecycleOwner(), + stops -> setSuggestionsStopRecyclerView(stops, true)); - */ if (getChildFragmentManager().findFragmentById(R.id.resultFrame)!= null){ swipeRefreshLayout.setVisibility(View.VISIBLE); // The child FragmentManager has restored its content — don't dispatch again return; } if (savedInstanceState != null) return; - showDifferentSubFragments(internalScreen); + showDifferentSubFragments(initialScreen); } /** * Installs the initial child fragment based on the arguments supplied as arguments */ - private void showDifferentSubFragments(@NonNull InternalScreen screen) { + private void showDifferentSubFragments(@NonNull InitialScreen screen) { boolean firstTime = !initialScreenShown; switch (screen) { case NEARBY_STOPS: case NEARBY_ARRIVALS: // TODO differentiate later //add to back stack if it is not just created showNearbyStopsFragmentChecking(!firstTime); break; case ARRIVALS: // pendingStopID is consumed in onResume → requestArrivalsForStopID if(pendingSearchQuery != null && isResumed()) { swipeRefreshLayout.setVisibility(View.VISIBLE); Log.d(DEBUG_TAG, "Searching arrivals for initial stop: "+pendingSearchQuery); requestsArrivalsInternal(pendingSearchQuery, false); pendingSearchQuery = null; } break; case STOP_SEARCH: if (pendingSearchQuery != null && pendingSearchQuery.length() >= 2) { fragmentHelper.requestStopSearch(pendingSearchQuery); } else { showButtonsFragment(firstTime); } pendingSearchQuery = null; break; case HOME_BUTTONS: default: showButtonsFragment(firstTime); } if(!initialScreenShown){ initialScreenShown = true; } } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); Log.d(DEBUG_TAG, "Saving instance state"); Fragment fragment = getChildFragmentManager().findFragmentById(R.id.resultFrame); if (fragment!=null) getChildFragmentManager().putFragment(outState, SAVED_FRAGMENT, fragment); //if (fragmentHelper!=null) fragmentHelper.setBlockAllActivities(true); } + public void setSuggestionsStopRecyclerView(List stops, boolean showMessage){ + + var res = !stops.isEmpty(); + var query = searchStopsViewModel.getQueryStops(); + //Log.d(DEBUG_TAG, "received stops suggestions, are "+stops.size()); + if(res){ + if(suggestionsAdapter!=null){ + suggestionsAdapter.setStops(stops); + } else{ + suggestionsAdapter = new StopNearbyAdapter(new ArrayList<>(stops), null, true, (stop)->{ + requestArrivalsForStopID(stop.ID); + //clear query + emptySearchQueryViewModel(); + //setSuggestionsStopRecyclerView(List.of(), false); + }); + suggestionsRecyclerView.setAdapter(suggestionsAdapter); + } + suggestionsRecyclerView.setVisibility(View.VISIBLE); + + } else{ + if(suggestionsAdapter !=null) suggestionsAdapter = null; + suggestionsRecyclerView.setVisibility(View.GONE); + if(showMessage && query!=null && !query.trim().isEmpty()){ + stopSearchMessageTextView.setText( searchMode == SearchMode.SEARCH_NAME ? + R.string.no_stop_found_search_name : R.string.no_stop_found_search_number); + stopSearchMessageTextView.setVisibility(View.VISIBLE); + } else{ + stopSearchMessageTextView.setVisibility(View.GONE); + } + + } + } + public void setSuppressArrivalsReload(boolean value){ suppressArrivalsReload = value; // we have to suppress the reloading of the (possible) ArrivalsFragment /*if(value) { Fragment fragment = getChildFragmentManager().findFragmentById(R.id.resultFrame); if (fragment instanceof ArrivalsFragment) { ArrivalsFragment frag = (ArrivalsFragment) fragment; frag.setReloadOnResume(false); } } */ } /** * Cancel the reload of the arrival times * because we are going to pop the fragment */ public void cancelReloadArrivalsIfNeeded(){ if(getContext()==null) return; //we are not attached //Fragment fr = getChildFragmentManager().findFragmentById(R.id.resultFrame); fragmentHelper.stopLastRequestIfNeeded(); toggleSpinner(false); } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); Log.d(DEBUG_TAG, "OnAttach called, setupOnAttach: "+ setupOnStart); if (context instanceof CommonFragmentListener) { mListener = (CommonFragmentListener) context; } else { throw new RuntimeException(context + " must implement CommonFragmentListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; // setupOnAttached = true; } @Override public void onStart() { super.onStart(); Log.d(DEBUG_TAG, "onStart called, setupOnStart: "+setupOnStart); try { while (!thingsToDoOnStart.isEmpty()) { var task = thingsToDoOnStart.take(); task.run(); } } catch (InterruptedException e) { Log.w(DEBUG_TAG, "Interrupted while doing task for start"); thingsToDoOnStart.clear(); } if (setupOnStart) { if (pendingStopID==null){ - if(!pendingIntroRun){ //show the fragment //showButtonsFragment(); } - } else{ ///TODO: if there is a stop displayed, we need to hold the update } - setupOnStart = false; } + // this happens when the fragment is recreated and the query is set on the searchView + if(!searchStopsViewModel.getShowingSearchSuggestions()){ + emptySearchQueryViewModel(); + } } private void showButtonsFragment(boolean addInsteadOfReplace){ swipeRefreshLayout.setVisibility(View.VISIBLE); var ft = childFragMan.beginTransaction(); var frag = ButtonsFragment.newInstance(); if(addInsteadOfReplace) ft.add(R.id.resultFrame,frag, ButtonsFragment.FRAGMENT_TAG); else{ ft.replace(R.id.resultFrame, frag, ButtonsFragment.FRAGMENT_TAG); ft.addToBackStack(null); } ft.commit(); } public void showButtonsFragmentIfNotNearby(boolean addToBackStack){ if(isAdded()) { var framan = getChildFragmentManager(); var showingFrag = framan.findFragmentById(R.id.resultFrame); if (showingFrag == null || showingFrag instanceof NearbyStopsFragment) { var fragHome = ButtonsFragment.newInstance(); var ft = framan.beginTransaction(); if (showingFrag == null) { ft.add(R.id.resultFrame, fragHome, ButtonsFragment.FRAGMENT_TAG); } else { ft.replace(R.id.resultFrame, fragHome, ButtonsFragment.FRAGMENT_TAG); } if (addToBackStack) ft.addToBackStack(null); ft.commit(); } else { Log.d(DEBUG_TAG, "attempting to show buttons home fragment but have other types (different than nearby)"); } } else{ Log.d(DEBUG_TAG, "Fragment is not added, putting in queue of things to do"); try { thingsToDoOnStart.put(() -> { showButtonsFragmentIfNotNearby(addToBackStack); }); } catch (InterruptedException e) { Log.e(DEBUG_TAG,"Cannot add task"); } } } private void showNearbyStopsFragmentChecking(boolean addToBackStack){ if(!checkLocationPermission()){ requestLocationPermission(); pendingNearbyStopsFragmentRequest = true; pendingNearbyAddToBackStack = addToBackStack; Log.d(DEBUG_TAG, "requesting location permission for nearby fragment"); } else { Log.d(DEBUG_TAG, "Showing nearby stops fragment"); showNearbyFragmentIfPossible(addToBackStack); } } @Override public void onResume() { super.onResume(); final Context con = requireContext(); Log.w(DEBUG_TAG, "OnResume called, setupOnStart: "+ setupOnStart); //recheck the introduction activity has been run if(Permissions.bothLocationPermissionsGranted(con)){ Log.d(DEBUG_TAG, "Location permission OK"); } //don't request permission // if we have a pending stopID request, do it Log.d(DEBUG_TAG, "Pending stop ID for arrivals: "+pendingStopID); //this is the second time we are attaching this fragment -> Log.d(DEBUG_TAG, "Waiting for new stop request: "+ suppressArrivalsReload); if (suppressArrivalsReload){ // we have to suppress the reloading of the (possible) ArrivalsFragment Fragment fragment = getChildFragmentManager().findFragmentById(R.id.resultFrame); if (fragment instanceof ArrivalsFragment){ ArrivalsFragment frag = (ArrivalsFragment) fragment; frag.setReloadOnResume(false); } //deactivate suppressArrivalsReload = false; } // check if the fragment start query is null if(pendingSearchQuery!=null) { requestsArrivalsInternal(pendingSearchQuery, false); pendingSearchQuery = null; } else if(pendingStopID!=null){ Log.d(DEBUG_TAG, "Pending request for arrivals at stop ID: "+pendingStopID); requestArrivalsForStopID(pendingStopID); pendingStopID = null; } - //mListener.readyGUIfor(FragmentKind.MAIN_SCREEN_FRAGMENT); //fragmentHelper.setBlockAllActivities(false); } @Override public void onPause() { //mainHandler = null; //locationManager.removeLocationRequestFor(requester); //fragmentHelper.setBlockAllActivities(true); fragmentHelper.stopLastRequestIfNeeded(); + searchStopsViewModel.saveOpenSearchSuggestions(); super.onPause(); } /* GUI METHODS */ @Override public void onQrScanSuccess(@NotNull String busIDToSearch) { - busStopSearchByIDEditText.setText(busIDToSearch); + EditText searchEditText = busStopSearchView.findViewById(androidx.appcompat.R.id.search_src_text); + searchEditText.setText(busIDToSearch); requestArrivalsForStopID(busIDToSearch); } /** * QR scan button clicked * * @param v View QRButton clicked */ public void onQRButtonClick(View v) { launchBarcodeScan(); } /** * OK this is pure shit * * @param v View clicked */ public void onSearchClick(View v) { //final StopsFinderByName[] stopsFinderByNames = new StopsFinderByName[]{new GTTStopsFetcher(), new FiveTStopsFetcher()}; - if (searchMode == SearchMode.SEARCH_ID) { - String busStopID = busStopSearchByIDEditText.getText().toString(); + if (searchMode == SearchMode.SEARCH_ID || searchMode == SearchMode.INITIAL) { + String busStopID = busStopSearchView.getQuery().toString(); fragmentHelper.stopLastRequestIfNeeded(); requestArrivalsForStopID(busStopID); } else if (searchMode == SearchMode.SEARCH_NAME) { // searchMode == SEARCH_BY_NAME - String query = busStopSearchByNameEditText.getText().toString(); + String query = busStopSearchView.getQuery().toString(); query = query.trim(); if(getContext()!=null) { if (query.length() < 1) { Toast.makeText(getContext(), R.string.insert_bus_stop_name_error, Toast.LENGTH_SHORT).show(); } else if(query.length()< 2){ Toast.makeText(getContext(), R.string.query_too_short, Toast.LENGTH_SHORT).show(); } else { fragmentHelper.requestStopSearch(query); } } } } public void onToggleKeyboardLayout(View v) { switch (searchMode){ case SEARCH_ID: - setSearchModeBusStopName(); - if (busStopSearchByNameEditText.requestFocus()) { + setSearchMode(SearchMode.SEARCH_NAME); + if (busStopSearchView.requestFocus()) showKeyboard(); - } + //} break; case SEARCH_NAME: case INITIAL: - setSearchModeBusStopID(); - if (busStopSearchByIDEditText.requestFocus()) { - showKeyboard(); - } + setSearchMode(SearchMode.SEARCH_ID); + if (busStopSearchView.requestFocus()) + showKeyboard(); + //} } } @Override public void enableRefreshLayout(boolean yes) { Log.d(DEBUG_TAG, "Enabling refresh layout: " + yes); swipeRefreshLayout.setEnabled(yes); } ////////////////////////////////////// GUI HELPERS ///////////////////////////////////////////// + + private EditText getSearchEditText() { + return busStopSearchView.findViewById(androidx.appcompat.R.id.search_src_text); + } public void showKeyboard() { if(getActivity() == null) return; - InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); - View view; - if(searchMode == SearchMode.SEARCH_ID) - view= busStopSearchByIDEditText; - else if(searchMode == SearchMode.SEARCH_NAME) - view = busStopSearchByNameEditText; - else{ - Log.e(DEBUG_TAG, "Asking to show keyboard but SearchMode is "+searchMode+", ignoring"); - return; - } - - imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); + final EditText et = getSearchEditText(); + et.requestFocus(); + et.post(() -> { + InputMethodManager imm = (InputMethodManager) + requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE); + if (imm == null) return; + imm.restartInput(et); // applica il nuovo inputType + imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT); + }); } - private void setSearchModeBusStopID() { - searchMode = SearchMode.SEARCH_ID; - busStopSearchByNameEditText.setVisibility(View.GONE); - busStopSearchByNameEditText.setText(""); - busStopSearchByIDEditText.setVisibility(View.VISIBLE); - floatingActionButton.setImageResource(R.drawable.alphabetical); - } - private void setSearchModeBusStopName() { - searchMode = SearchMode.SEARCH_NAME; - busStopSearchByIDEditText.setVisibility(View.GONE); - busStopSearchByIDEditText.setText(""); - busStopSearchByNameEditText.setVisibility(View.VISIBLE); - floatingActionButton.setImageResource(R.drawable.numeric); - } protected boolean isNearbyFragmentShown(){ Fragment fragment = getChildFragmentManager().findFragmentByTag(NearbyStopsFragment.FRAGMENT_TAG); return (fragment!= null && fragment.isResumed()); } - /** + private void setSearchMode(SearchMode mode) { + searchMode = mode; + busStopSearchView.setQuery("", false); + boolean byId = mode != SearchMode.SEARCH_NAME; + busStopSearchView.setInputType(byId ? InputType.TYPE_CLASS_NUMBER : InputType.TYPE_CLASS_TEXT); + floatingActionButton.setImageResource(byId ? R.drawable.numeric : R.drawable.alphabetical); + busStopSearchView.setQueryHint(getString(byId ? R.string.insert_bus_stop_number : R.string.insert_bus_stop_name)); + } + + /* * Having that cursor at the left of the edit text makes me cancer. * * @param busStopID bus stop ID */ + // + /* private void setBusStopSearchByIDEditText(String busStopID) { busStopSearchByIDEditText.setText(busStopID); busStopSearchByIDEditText.setSelection(busStopID.length()); } + */ + @Nullable @Override public View getBaseViewForSnackBar() { return coordLayout; } @Override public void toggleSpinner(boolean enable) { if (enable) { //already set by the RefreshListener when needed //swipeRefreshLayout.setRefreshing(true); progressBar.setVisibility(View.VISIBLE); } else { swipeRefreshLayout.setRefreshing(false); progressBar.setVisibility(View.GONE); } } private void prepareGUIForArrivals() { swipeRefreshLayout.setEnabled(true); swipeRefreshLayout.setVisibility(View.VISIBLE); + //this is to hide the eventual search results from the text + //setSuggestionsStopRecyclerView(List.of(), false); //actionHelpMenuItem.setVisible(true); } private void prepareGUIForBusStops() { swipeRefreshLayout.setEnabled(false); swipeRefreshLayout.setVisibility(View.VISIBLE); + //setSuggestionsStopRecyclerView(List.of(), false); + //actionHelpMenuItem.setVisible(false); } @Override public void showFloatingActionButton(boolean yes) { //mListener.showFloatingActionButton(yes); if(yes) floatingActionButton.setVisibility(View.VISIBLE); else floatingActionButton.setVisibility(View.GONE); } /** * This provides a temporary fix to make the transition * to a single asynctask go smoother * * @param fragmentType the type of fragment created */ @Override public void readyGUIfor(FragmentKind fragmentType) { if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Readying main fragment for type "+fragmentType); //if we are getting results, already, stop waiting for nearbyStops if (fragmentType == FragmentKind.ARRIVALS || fragmentType == FragmentKind.STOPS) { hideKeyboard(); if (pendingNearbyStopsFragmentRequest) { //locationManager.removeLocationRequestFor(requester); pendingNearbyStopsFragmentRequest = false; } } if (fragmentType == null) Log.e("ActivityMain", "Problem with fragmentType"); else switch (fragmentType) { case ARRIVALS: prepareGUIForArrivals(); break; case STOPS: prepareGUIForBusStops(); break; default: //Log.d(DEBUG_TAG, "Fragment type is unknown"); return; } // Shows hints } + /* + // KEEPING THIS METHODS AS EXAMPLES FOR SHOW + boolean searchStopsResultsFragmentShown(){ + Fragment frag = childFragMan.findFragmentById(R.id.resultFrame); + return frag instanceof StopSearchResultFragment; + } + void showSearchStopsResultsFragment(){ + final String TAG = "stopSearchResult"; + Fragment frag = childFragMan.findFragmentById(R.id.resultFrame); + if (frag instanceof StopSearchResultFragment){ + return; //nothing to do + } + boolean exists = frag != null; + var trans = childFragMan.beginTransaction(); + + frag = childFragMan.findFragmentByTag(TAG); + if (!(frag instanceof StopSearchResultFragment)) { + frag = StopSearchResultFragment.newInstance(); + } + if(exists){ + //show the fragment + trans.replace(R.id.resultFrame,frag, TAG); + } else{ + //create new fragment + trans.add(R.id.resultFrame,frag, TAG); + } + trans.addToBackStack(null); + trans.commit(); + } + */ + @Override public void openLineFromStop(String routeGtfsId, @Nullable String stopIDFrom) { //pass to activity if(mListener!=null) mListener.openLineFromStop(routeGtfsId, stopIDFrom); } @Override public void openLineFromVehicle(String routeGtfsId, @Nullable String optionalPatternId, @Nullable Bundle args) { if(mListener!=null) mListener.openLineFromVehicle(routeGtfsId, optionalPatternId, args); } @Override public void openNearbyStopsFragment() { if(isAdded()) showNearbyStopsFragmentChecking(true); else try{ thingsToDoOnStart.put(() -> showNearbyStopsFragmentChecking(true)); } catch (InterruptedException e) { Log.e(DEBUG_TAG, "trying to put open nearby in task but was interrupted"); } } @Override public void openLinesFragment() { if(mListener!=null) mListener.openLinesFragment(); } @Override public void openFavoritesFragment() { if(mListener!=null) mListener.openFavoritesFragment(); } @Override public void showMapCenteredOnStop(Stop stop) { if(mListener!=null) mListener.showMapCenteredOnStop(stop); } private void requestsArrivalsInternal(String stopID, boolean addToBackStack) { if (!isResumed()){ //defer request to onResume - it will be added to the backstack pendingStopID = stopID; Log.d(DEBUG_TAG, "Deferring update for stop "+stopID+ " saved: "+pendingStopID); return; } final boolean delayedRequest = !(pendingStopID==null); final FragmentManager framan = getChildFragmentManager(); if (getContext()==null){ Log.e(DEBUG_TAG, "Asked for arrivals with null context"); return; } if (stopID == null || stopID.isEmpty()) { // we're still in UI thread, no need to mess with Progress showToastMessage(R.string.insert_bus_stop_number_error, true); toggleSpinner(false); } else{ // ensure that the new sub-fragment is gonna be visible swipeRefreshLayout.setVisibility(View.VISIBLE); var palinaTrial = new Palina(stopID); if (framan.findFragmentById(R.id.resultFrame) instanceof ArrivalsFragment fragment) { if (fragment.isFragmentForTheSameStop(palinaTrial)){ // Run with previous fetchers //fragment.getCurrentFetchers().toArray() fragment.requestArrivalsForTheFragment(); } else{ // The rest of the case is handled by the fragment Helper fragmentHelper.showArrivalsFragmentForStop(palinaTrial, addToBackStack); } } else { // this is not needed any more //prepareGUIForArrivals(); fragmentHelper.showArrivalsFragmentForStop(palinaTrial, addToBackStack); } } } /** * Main method for stops requests * @param ID the Stop ID */ @Override public void requestArrivalsForStopID(String ID) { requestsArrivalsInternal(ID, true); } private boolean checkLocationPermission(){ final Context context = getContext(); if(context==null) return false; final boolean noPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED; return !noPermission; } private void requestLocationPermission(){ if(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)){ makeToast(R.string.enable_position_message_nearby); } requestPermissionLauncher.launch(LOCATION_PERMISSIONS); } private void showNearbyFragmentIfPossible(boolean addToBackStack) { if (isNearbyFragmentShown()) { //nothing to do Log.d(DEBUG_TAG, "Asked to show nearby fragment but we already are showing it"); return; } if (getContext() == null) { Log.e(DEBUG_TAG, "Wanting to show nearby fragment but context is null"); return; } if (!childFragMan.isDestroyed()) { //Go ahead with the request swipeRefreshLayout.setVisibility(View.VISIBLE); final Fragment existingFrag = childFragMan.findFragmentById(R.id.resultFrame); // fragment; if (!(existingFrag instanceof NearbyStopsFragment)){ Log.d(DEBUG_TAG, "actually showing Nearby Stops Fragment"); //there is no fragment showing var nearbyFrag = (NearbyStopsFragment) childFragMan.findFragmentByTag(NearbyStopsFragment.FRAGMENT_TAG); if(nearbyFrag==null){ nearbyFrag = NearbyStopsFragment.newInstance(NearbyStopsFragment.FragType.STOPS); } FragmentTransaction ft = childFragMan.beginTransaction(); ft.replace(R.id.resultFrame, nearbyFrag, NearbyStopsFragment.FRAGMENT_TAG); if(addToBackStack) ft.addToBackStack(null); if (getActivity()!=null && !getActivity().isFinishing()) ft.commit(); else Log.e(DEBUG_TAG, "Not showing nearby fragment because activity null or is finishing"); } pendingNearbyStopsFragmentRequest = false; } } } \ 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 523fc45..2ea66e5 100644 --- a/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt +++ b/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt @@ -1,861 +1,860 @@ /* 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.res.ColorStateList 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.content.res.ResourcesCompat import androidx.fragment.app.viewModels import androidx.preference.PreferenceManager import androidx.recyclerview.widget.RecyclerView import androidx.work.WorkInfo import com.google.android.material.button.MaterialButton 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.adapters.StopNearbyAdapter import it.reyboz.bustorino.backend.* import it.reyboz.bustorino.data.DatabaseUpdate 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 import it.reyboz.bustorino.util.Permissions.Companion.bothLocationPermissionsGranted import it.reyboz.bustorino.util.StopSorterByDistance -import it.reyboz.bustorino.util.ViewUtils import it.reyboz.bustorino.viewmodels.NearbyStopsViewModel import java.util.* import java.util.concurrent.atomic.AtomicBoolean 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, LOCATION_FOUND, DISABLED, NO_PERMISSION //NO_STOPS_NEARBY } private var mListener: FragmentListenerMain? = null private var fragmentType = FragType.STOPS private lateinit var gridRecyclerView: RecyclerView - private var dataAdapter: SquareStopAdapter? = null + private var dataAdapter: StopNearbyAdapter? = 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 lateinit var enableLocationButton : MaterialButton 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 arrivalsStopAdapter: ArrivalsStopAdapter? = null private var currentNearbyStops: ArrayList? = null private var showingStatus = LocationShowingStatus.NO_PERMISSION private var isLocationEnabled = false private var dataShownInAdapter = AtomicBoolean(false) private var noDataMessageId = R.string.no_stops_nearby private var loadingDataMessageId = R.string.position_searching_message private val locationUpdateListener: LocationUpdateListener = object : LocationUpdateListener { override fun onLocationUpdate(location: Location) { if (location.getAccuracy() < MIN_ACCURACY) { lastPosition = GPSPoint(location.getLatitude(), location.getLongitude()) viewModel.setLastLocation(location) } else{ Log.d(DEBUG_TAG, "Refusing location ${location.latitude},${location.longitude} because accuracy: ${location.accuracy} > MIN_ACCURACY=$MIN_ACCURACY") } } override fun onFusedStatusChanged(isEnabled: Boolean) { Log.d(DEBUG_TAG, "Location provider is enabled: " + isEnabled) isLocationEnabled = isEnabled if(!dataShownInAdapter.get()) if (isEnabled) { setShowingStatus(LocationShowingStatus.SEARCHING) } else { setShowingStatus(LocationShowingStatus.DISABLED) } } } private val locationPermissionLauncher = getPositionRequestLauncher(){ granted -> startLocationUpdatesByType() setShowingStatus(LocationShowingStatus.SEARCHING) } // Two different settings for the location provider private val locationOptionsArrivals = FusedNativeLocationProvider.Options(5 * 1000L, 25f) private val locationOptionsStops = FusedNativeLocationProvider.Options(1000L, 5f) 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 val context = requireContext() val root = inflater.inflate(R.layout.fragment_nearby_stops, container, false) gridRecyclerView = root.findViewById(R.id.stopGridRecyclerView) gridLayoutManager = AutoFitGridLayoutManager( context.getApplicationContext(), utils.convertDipToPixels(context, 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) enableLocationButton = root.findViewById(R.id.grantLocationButton) titleTextView = root.findViewById(R.id.titleTextView) loadingTextView = root.findViewById(R.id.positionLoadingTextView) switchButton = root.findViewById(R.id.switchButton) scrollListener = CommonScrollListener(mListener, false) switchButton!!.setOnClickListener { 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 checkPermissionLocationStart() viewModel.setDBUpdateRunning(false) //actually restart request } } //add location listener locationProvider!!.addListener(locationUpdateListener) enableLocationButton.setOnClickListener { locationPermissionLauncher.launch(Permissions.LOCATION_PERMISSIONS) } return root } private fun checkPermissionLocationStart(){ Log.d(DEBUG_TAG, "Check permission and start location updates") if (bothLocationPermissionsGranted(requireContext())) { if (!locationProvider!!.isRunning()) { startLocationUpdatesByType() setShowingStatus(LocationShowingStatus.SEARCHING) } else{ Log.w(DEBUG_TAG, "Asked to check and start location updates, but provider is already running") } } else { setShowingStatus(LocationShowingStatus.NO_PERMISSION) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) gridRecyclerView.setVisibility(View.INVISIBLE) gridRecyclerView.addOnScrollListener(scrollListener!!) //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 + 50) //viewModel.requestStopsAtDistance(distance, true); //Log.d(DEBUG_TAG, "Doubling distance now!"); return@observe // THIS WORKS AS AN `else` } displayStopsOrRequestArrivals(stops) } viewModel.locationLiveData.observe(getViewLifecycleOwner()) {loc -> if(loc!=null){ setShowingStatus(LocationShowingStatus.LOCATION_FOUND) } //the stops are updated manually } viewModel.downloadingArrivals.observe(viewLifecycleOwner){ running -> flatProgressBar.isIndeterminate = true 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 } showArrivals(stoprouteList) //arrivalsStopAdapter.notifyDataSetChanged(); //showRecyclerHidingLoadMessage() //if (mListener != null) mListener!!.readyGUIfor(FragmentKind.NEARBY_ARRIVALS) } //added //checkPermissionLocationStart() } private fun displayStopsOrRequestArrivals(stops: ArrayList){ if (!stops.isEmpty()) { currentNearbyStops = stops //displayStopsOrLaunchArrivalsRequest(stops, lastPosition) viewModel.locationLiveData.value?.let{loc -> when(fragmentType){ FragType.STOPS->{ lastPosition?.let{loc -> Collections.sort(stops, StopSorterByDistance(loc)) showStopsInRecycler(stops,loc) } } FragType.ARRIVALS -> { lastPosition?.let{ Collections.sort(stops, StopSorterByDistance(loc)) } viewModel.requestArrivalsForStops(stops) } } } } else{ showNoStopsMessage() viewModel.cancelAllArrivalsRequests() } } private fun showArrivals(stoprouteList: ArrayList){ val context = requireContext() if (firstLocForArrivals) { mListener?.let{ lastPosition?.let{ pos -> arrivalsStopAdapter = ArrivalsStopAdapter(stoprouteList, it, context, pos) gridRecyclerView.setAdapter(arrivalsStopAdapter) firstLocForArrivals = false } } } else { lastPosition?.let{ pos -> arrivalsStopAdapter?.setRoutesPairListAndPosition(stoprouteList, pos) } } dataShownInAdapter.set(true) } /** * Internal bit used to start location updates */ private fun startLocationUpdatesByType() { when (fragmentType) { 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 = fragmentType != type this.fragmentType = type if (isChanged) { startLocationUpdatesByType() } } /** * Set the location in the view model if it is good * @param location new location */ /* private fun updateLocationViewModel(location: Location, accuracy: Float = 150f) { } */ private fun setShowingStatus(newStatus: LocationShowingStatus) { var newStatus = newStatus if (newStatus == showingStatus) { return } if (BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Changing showing status from $showingStatus to $newStatus") 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.LOCATION_FOUND -> { circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) gridRecyclerView.setVisibility(View.VISIBLE) messageTextView!!.setVisibility(View.GONE) enableLocationButton.setVisibility(View.GONE) } LocationShowingStatus.NO_PERMISSION -> { circlingProgressBar?.setVisibility(View.GONE) flatProgressBar.setVisibility(View.GONE) loadingTextView?.setVisibility(View.GONE) messageTextView?.setText(R.string.enable_position_message_nearby) messageTextView?.setVisibility(View.VISIBLE) enableLocationButton.setVisibility(View.VISIBLE) } LocationShowingStatus.DISABLED -> { //if (showingStatus== LocationShowingStatus.SEARCHING){ circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) flatProgressBar.setVisibility(View.GONE) //} messageTextView!!.setText(R.string.enable_location_message) messageTextView!!.setVisibility(View.VISIBLE) enableLocationButton.setVisibility(View.GONE) } LocationShowingStatus.SEARCHING -> { circlingProgressBar!!.setVisibility(View.VISIBLE) flatProgressBar.setVisibility(View.GONE) gridRecyclerView.setVisibility(View.GONE) messageTextView!!.setVisibility(View.GONE) enableLocationButton.setVisibility(View.GONE) loadingTextView?.apply { setText(loadingDataMessageId) visibility = View.VISIBLE } } } 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 loadPreferencesStops() setGuiForFragmentType(fragmentType) //if(lastPosition == null){ viewModel.locationLiveData.value?.let{loc -> lastPosition = loc } //} if(bothLocationPermissionsGranted(requireContext())){ locationProvider?.apply { if(isLocationEnabled()){ //location is enabled, start updates startLocationUpdatesByType() if(lastPosition == null){ setShowingStatus(LocationShowingStatus.SEARCHING) } } else{ setShowingStatus(LocationShowingStatus.DISABLED) } } } else{ setShowingStatus(LocationShowingStatus.NO_PERMISSION) } //setupDataAndLayoutByFragmentType() mListener!!.enableRefreshLayout(false) if(fragmentType == FragType.ARRIVALS){ viewModel.arrivalsDecoupled.value?.let{ //re-do the adapter firstLocForArrivals = true showArrivals(it) } } else if(fragmentType == FragType.STOPS) { viewModel.stopsAtDistance.value?.let { //remake the adapter firstLocForStops = true displayStopsOrRequestArrivals(it) } } /* when (fragmentType) { 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) } } */ 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 } //Re-read preferences } private fun loadPreferencesStops(){ 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" ) } override fun onDetach() { super.onDetach() mListener = null //if (arrivalsManager != null) arrivalsManager!!.cancelAllRequests() } override fun onStart() { super.onStart() if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "onStart called") //checkPermissionLocationStart() } /** * Display the stops, or run new set of requests for arrivals */ /*private fun displayStopsOrLaunchArrivalsRequest(stops: ArrayList, location: GPSPoint) { if (stops.isEmpty()) { setNoStopsLayout() return } //quick trial to hopefully always get the stops in the correct order when (fragment_type) { FragType.STOPS -> { setShowingStatus(LocationShowingStatus.STOPS_FOUND) showStopsInRecycler(stops, location) } FragType.ARRIVALS -> { viewModel.requestArrivalsForStops(stops) //setShowingStatus(LocationShowingStatus.SEARCHING) viewModel.arrivalsDecoupled.value?.let{ } } } } */ /** * Call when you need to switch the type of fragment */ private fun switchFragmentType() { when (fragmentType) { FragType.ARRIVALS -> { viewModel.cancelAllArrivalsRequests() setFragmentType(FragType.STOPS) //when switching from arrivals firstLocForStops = true } FragType.STOPS -> { setFragmentType(FragType.ARRIVALS) firstLocForArrivals = true } } //now it's switched setGuiForFragmentType(fragmentType) viewModel.stopsAtDistance.value?.let{ //re-issue update, triggering chain viewModel.stopsAtDistance.value = it } /*if(fragmentType == FragType.ARRIVALS) { viewModel.stopsAtDistance.value?.let{ viewModel.requestArrivalsForStops(it) } } */ // //setupDataAndLayoutByFragmentType() } private fun setGuiForFragmentType(fragmentType: FragType) { when (fragmentType) { FragType.STOPS ->{ switchButton!!.text = getString(R.string.show_arrivals) titleTextView!!.text = getString(R.string.nearby_stops_message) noDataMessageId = R.string.no_stops_nearby loadingDataMessageId = R.string.position_searching_message //switchButton?.backgroundTintList = ColorStateList.valueOf( // ViewUtils.getColorFromTheme(requireContext(), R.attr.colorPrimaryDark)) } FragType.ARRIVALS ->{ titleTextView!!.text = getString(R.string.nearby_arrivals_message) switchButton!!.text = getString(R.string.show_stops) noDataMessageId = R.string.no_stops_nearby_arrivals loadingDataMessageId = R.string.searching_arrivals_indefinite //switchButton?.backgroundTintList = ColorStateList.valueOf( // ResourcesCompat.getColor(resources, R.color.light_blue_900, requireActivity().theme)) } } } /** * Prepare the views for the set fragment type */ /*private fun setupDataAndLayoutByFragmentType() { var dataAvailable = false if (fragmentType == FragType.STOPS) { switchButton!!.text = getString(R.string.show_arrivals) titleTextView!!.text = getString(R.string.nearby_stops_message) viewModel.stopsAtDistance.value?.let { stops-> // if data adapter is not null set stops, otherwise dataAdapter?.setStops(stops) ?: lastPosition?.let{ pos -> dataAdapter = SquareStopAdapter(stops, mListener, pos) } Log.d(DEBUG_TAG, "Found ${stops.size} stops") } dataAdapter?.let{ gridRecyclerView.adapter = it dataAvailable = true } mListener?.readyGUIfor(FragmentKind.NEARBY_STOPS) } else if (fragmentType == FragType.ARRIVALS) { titleTextView!!.text = getString(R.string.nearby_arrivals_message) switchButton!!.text = getString(R.string.show_stops) val arrivalsSorted = viewModel.arrivalsDecoupled.value arrivalsSorted?.let{ arrivalsStopAdapter?.setRoutesPairListAndPosition( it, lastPosition) ?: lastPosition?.let{pos -> arrivalsStopAdapter = ArrivalsStopAdapter(it, mListener!!, requireContext(), pos) } } arrivalsStopAdapter?.let{ gridRecyclerView.setAdapter(it) } mListener?.readyGUIfor(FragmentKind.NEARBY_ARRIVALS) } if(gridRecyclerView.adapter == null){ flatProgressBar.isIndeterminate = true flatProgressBar.visibility = View.VISIBLE } else{ flatProgressBar.visibility = View.GONE flatProgressBar.isIndeterminate = false } } */ //useful methods /**//// GUI METHODS //////// */ private fun showStopsInRecycler(stops: MutableList, location: GPSPoint) { // hide the progress bar flatProgressBar.visibility = View.GONE Collections.sort(stops, StopSorterByDistance(location)) if (dataAdapter == null) { - dataAdapter = SquareStopAdapter(stops, mListener, lastPosition) + dataAdapter = StopNearbyAdapter(ArrayList(stops), lastPosition, false){ + stop-> mListener?.requestArrivalsForStopID(stop.ID) + } firstLocForStops = false } else { dataAdapter!!.setUserPosition(lastPosition) dataAdapter!!.setStops(stops) } gridRecyclerView.setAdapter(dataAdapter) if(gridRecyclerView.visibility != View.VISIBLE){ if(showingStatus == LocationShowingStatus.LOCATION_FOUND) Log.e(DEBUG_TAG, "Visualization error: the recyclerView is not visible but location status is $showingStatus") else{ Log.w(DEBUG_TAG, "Grid recyclerView should be visible for the stops, setting status ${LocationShowingStatus.LOCATION_FOUND}") setShowingStatus(LocationShowingStatus.LOCATION_FOUND) } } dataShownInAdapter.set(true) //showRecyclerHidingLoadMessage(); /*if (gridRecyclerView!!.getVisibility() != View.VISIBLE) { circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) gridRecyclerView!!.setVisibility(View.VISIBLE) } messageTextView!!.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) } */ private fun showNoStopsMessage(){ messageTextView!!.setVisibility(View.VISIBLE) messageTextView!!.setText(noDataMessageId) flatProgressBar.visibility = View.GONE circlingProgressBar!!.setVisibility(View.GONE) loadingTextView!!.setVisibility(View.GONE) enableLocationButton.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 const val MIN_ACCURACY = 200.0 /** * 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/util/StopSorterSearch.kt b/app/src/main/java/it/reyboz/bustorino/util/StopSorterSearch.kt new file mode 100644 index 0000000..e7dda18 --- /dev/null +++ b/app/src/main/java/it/reyboz/bustorino/util/StopSorterSearch.kt @@ -0,0 +1,30 @@ +package it.reyboz.bustorino.util + +import it.reyboz.bustorino.backend.Stop + +class StopSorterSearch(val searchById: Boolean): Comparator { + override fun compare(s0: Stop?, s1: Stop?): Int { + if (s0 ==null) { + if (s1 != null) return 1 + else return 0 + } + else if(s1 == null){ + //s0 is not null + return -1 + } + if(s0.location==null){ + if(s1.location != null) return 1 + } else if(s1.location==null) return -1 + + if(searchById){ + val lenDiff = s0.ID.length - s1.ID.length + if(lenDiff!=0) return lenDiff + //second criterion + val diff = s0.ID.toInt() - s1.ID.toInt() + //if(diff!=0) return diff + return diff + } else{ + return -1*(s0.numRoutesStopping - s1.numRoutesStopping) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/viewmodels/SearchStopsDBViewModel.kt b/app/src/main/java/it/reyboz/bustorino/viewmodels/SearchStopsDBViewModel.kt new file mode 100644 index 0000000..ccf9cad --- /dev/null +++ b/app/src/main/java/it/reyboz/bustorino/viewmodels/SearchStopsDBViewModel.kt @@ -0,0 +1,90 @@ +package it.reyboz.bustorino.viewmodels + +import android.app.Application +import android.util.Log +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MediatorLiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.distinctUntilChanged +import androidx.lifecycle.liveData +import androidx.lifecycle.map +import androidx.lifecycle.switchMap +import androidx.lifecycle.viewModelScope +import it.reyboz.bustorino.backend.Stop +import it.reyboz.bustorino.data.NextGenDB +import it.reyboz.bustorino.util.StopSorterSearch +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlin.math.min +import kotlin.time.Duration.Companion.milliseconds + +class SearchStopsDBViewModel(application: Application): AndroidViewModel(application) { + + private data class Request(val q: String, val byId: Boolean) + + private val nextGenDB = NextGenDB.getInstance(application) + + var showingSearchSuggestions = false + + + private val queryLiveData = MutableLiveData(Request("", true)) + private val numberLimitStop = MutableLiveData(20) + val queryResultsLiveData = queryLiveData.distinctUntilChanged().switchMap { r-> + liveData(viewModelScope.coroutineContext + Dispatchers.IO, timeoutInMs = 0) { + if (r.q.isEmpty()) { + //showQueryResult.postValue(false) + emit(emptyList()) + } + else { + delay(250.milliseconds) + //showQueryResult.postValue(true) + val list = nextGenDB.searchStopsByCodeOrName(r.q, r.byId) + /*if (r.byId) + emit(list.sortedBy { it.ID }) + else + emit(list.sortedBy { it.numRoutesStopping }.reversed()) + + */ + emit(list.sortedWith(StopSorterSearch(r.byId))) + } + } + } + + val showQueryResult = queryResultsLiveData.map { it.isNotEmpty() } + + fun searchStops(query: String, byId: Boolean){ + //Log.d(TAG, "setting query $query with id $byId, was previously ${queryLiveData.value}") + this.queryLiveData.value = Request(query, byId) + } + fun getQueryStops(): String?{ + return queryLiveData.value?.q + } + fun setLimitSearchStops(num: Int){ + numberLimitStop.value = num + } + + + val filteredStopsSearch = MediatorLiveData>() + private fun setFilteredStops(stops:List, num: Int){ + filteredStopsSearch.postValue(stops.subList(0, min(num, stops.size))) + } + + init { + filteredStopsSearch.addSource(queryResultsLiveData) { + setFilteredStops(it, numberLimitStop.value!!) + } + filteredStopsSearch.addSource(numberLimitStop) { + queryResultsLiveData.value?.let{ stops -> + setFilteredStops(stops, it) + } + } + } + + fun saveOpenSearchSuggestions(){ + showingSearchSuggestions = showQueryResult.value?: false + } + + companion object{ + private const val TAG = "BusTO-SearchStopsVM" + } +} \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_main_screen.xml b/app/src/main/res/layout/fragment_main_screen.xml index 4c96a87..e482100 100644 --- a/app/src/main/res/layout/fragment_main_screen.xml +++ b/app/src/main/res/layout/fragment_main_screen.xml @@ -1,152 +1,195 @@ - - - + + - + /> + - - + android:background="@drawable/search_button_custom" + android:contentDescription="@string/search" + app:layout_constraintTop_toTopOf="parent" + app:layout_constraintBottom_toTopOf="@id/barrierSearch" + app:layout_constraintStart_toEndOf="@id/busStopSearchView" + app:layout_constraintEnd_toStartOf="@id/QRButton" + android:visibility="gone" + /> + + + + + + + + - + - + + - + + + \ No newline at end of file diff --git a/app/src/main/res/layout/item_stop_nearby_card.xml b/app/src/main/res/layout/item_stop_nearby_card.xml index ceaccad..1ad939c 100644 --- a/app/src/main/res/layout/item_stop_nearby_card.xml +++ b/app/src/main/res/layout/item_stop_nearby_card.xml @@ -1,110 +1,140 @@ + + + \ No newline at end of file diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 682c36d..6ce415e 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1,270 +1,272 @@ Stai utilizzando l\'ultimo ritrovato in materia di rispetto della tua privacy. Cerca Codice QR Scansiona codice QR alla fermata Si No Prossimo Precedente Necessaria app per leggere i codici QR Questa azione richiede un\'altra app per scansionare i codici QR, ma non è stata trovata sul dispositivo. Vuoi installare Binary Eye? Numero fermata Nome fermata Inserisci il numero della fermata Inserisci il nome della fermata Verifica l\'accesso ad Internet! Sembra che nessuna fermata abbia questo nome Nessun passaggio trovato alla fermata Ricerca arrivi da %1$s Errore di lettura del sito 5T/GTT (dannato sito!) Fermata: %1$s Fermata: Linea Linee Linee urbane Linee extraurbane Linee turistiche Direzione: Nessuna linea in questa categoria Nessuna linea corrisponde alla ricerca Filtra per nome Linea %1$s Linee: %1$s Linea %1$s, direzione: Fermata %1$s Scegli la fermata… Matricola %1$s Nessun passaggio Nessun QR code trovato, riprova Preferiti Aiuto Donazioni Informazioni sull\'app Più informazioni Vai alla wiki https://gitpull.it/w/librebusto/it/ Codice sorgente Licenza Incontra l\'autore Mostra linea Vedi direzione Fermata aggiunta ai preferiti Impossibile aggiungere ai preferiti (memoria piena o database corrotto?)! Preferiti Mappa Nessun preferito? Arghh!\nSchiaccia sulla stella di una fermata per aggiungerla a questa lista! Rimuovi Rinomina Rinomina fermata Reset Informazioni Tocca la stella per aggiungere la fermata ai preferiti\n\nCome leggere gli orari:\n 12:56* Orario in tempo reale\n 12:56 Orario programmato\n\nTrascina giù per aggiornare l\'orario. \nTocca a lungo su Fonte Orari per cambiare sorgente degli orari di arrivo OK! Benvenuto!\n \n

Grazie per aver scelto BusTO, un\'app open source e indipendente da GTT/5T, per spostarsi a Torino attraverso software libero!

\n

BusTO rispetta la tua privacy non raccogliendo nessun dato sull\'utilizzo, ed è leggera e senza pubblicità!

\n
\n

Qui puoi trovare più informazioni e link riguardo al progetto.

\n\t\t
\n

Schermata iniziale

\n

Se vuoi rivedere la schermata iniziale, usa il pulsante qui sotto:"]]> Notizie e aggiornamenti

Nel canale Telegram puoi trovare informazioni sugli ultimi aggiornamenti dell\'app

]]>
Ma come funziona?\n

Quest\'app ottiene i passaggi dei bus, le fermate e altre informazioni utili unendo dati forniti dal sito www.gtt.to.it, www.5t.torino.it, muoversiatorino.it \"per uso personale\" e altre fonti Open Data (aperto.comune.torino.it).

\n
\n\t\t

Ingredienti:
\n\t\t- Fabio Mazza attuale rockstar developer anziano.
\n\t\t- Andrea Ugo attuale rockstar developer in formazione.
\n\t\t- Silviu Chiriac designer del logo 2021.
\n\t\t- Marco M formidabile tester e cacciatore di bug.
\n\t\t- Ludovico Pavesi ex rockstar developer anziano asd.
\n\t\t- Valerio Bozzolan attuale manutentore.
\n\t\t- Marco Gagino apprezzato ex collaboratore, ideatore icona e grafica.
\n\t\t- JSoup libreria per \"web scaping\".
\n\t\t- Google icone e librerie di supporto e design.
\n\t\t- Altre icone da Bootstrap, Feather, Remix e Hero Icons
\n\t\t- Tutti i contributori e i beta tester!\n\t\t

\n

Se vuoi avere più informazioni o donare per supportare lo sviluppo dell\'app, usa i pulsanti qui sotto!

"]]>
Licenze\n\t\t

L\'app e il relativo codice sorgente sono distribuiti sotto la licenza GNU General Public License v3 (https://www.gnu.org/licenses/gpl-3.0.html).\n\t\tCiò significa che puoi usare, studiare, migliorare e ricondividere quest\'app con qualunque mezzo e per qualsiasi scopo: a patto di mantenere sempre questi diritti a tua volta e di dare credito a Valerio Bozzolan e agli altri autori del codice dell\'app.\n\t\t

\n\n\t\t
\n\t\t

Note

\n\t\t

Quest\'applicazione è rilasciata nella speranza che sia utile a tutti ma senza NESSUNA garanzia sul suo funzionamento attuale e/o futuro.

\n\t\t

Tutti i dati utilizzati dall\'app provengono direttamente da GTT o da simili agenzie pubbliche: se trovi che sono inesatti per qualche motivo, ti invitiamo a rivolgerti a loro.

\n\t\t

Buon utilizzo! :)

]]>
Nome troppo corto, digita più caratteri e riprova %1$s verso %2$s %s (destinazione sconosciuta) Errore interno inaspettato, impossibile estrarre dati dal sito GTT/5T Visualizza sulla mappa Non trovo un\'applicazione dove mostrarla Posizione della fermata non trovata Vicino a me Fermate vicine Ricerca della posizione Nessuna fermata nei dintorni Preferenze Aggiornamento del database… Aggiornamento del database Aggiornamento database forzato Tocca per aggiornare ora il database Numero minimo di fermate Il numero di fermate da ricercare non è valido Valore errato, inserisci un numero Impostazioni Distanza massima di ricerca (m) Funzionalità sperimentali Impostazioni Generali Fermate recenti Impostazioni generali Gestione del database Lancia aggiornamento manuale del database Consenti l\'accesso alla posizione per mostrarla sulla mappa Consenti l\'accesso alla posizione per mostrare le fermate vicine Abilitare la posizione sul dispositivo arriva alle alla fermata Mostra arrivi Mostra fermate Arrivi qui vicino Fermata rimossa dai preferiti Canale telegram Mostra introduzione La mia posizione Segui posizione Attiva o disattiva posizione Posizione attivata Posizione disattivata La posizione è disabilitata sul dispositivo Fonte orari: %1$s App GTT Sito GTT Sito 5T Torino Muoversi a Torino Sconosciuta Fonti orari di arrivo Scegli le fonti di orari da usare Cambiamento sorgente orari… Premi a lungo per cambiare la sorgente degli orari Nessun passaggio per le linee: Canale default delle notifiche Operazioni sul database Informazioni sul database (aggiornamento) BusTO - posizioni in tempo reale Posizioni in tempo reale Attività del servizio delle posizioni in tempo reale Servizio posizioni MaTO in tempo reale attivo Download dei trip dal server MaTO Chiesto troppe volte per il permesso %1$s Non si può usare questa funzionalità senza il permesso di archivio! di archivio Un bug ha fatto crashare l\'app! \nPremi \"OK\" per inviare il report agli sviluppatori via email, così potranno scovare e risolvere il tuo bug! \nIl report contiene piccole informazioni non sensibili sulla configurazione del tuo telefono e sullo stato dell\'app al momento del crash. L\'applicazione è crashata, e il crash report è stato messo negli allegati. Se vuoi, descrivi cosa stavi facendo prima che si interrompesse: Arrivi Mappa Preferiti Apri drawer Chiudi drawer Esperimenti Offrici un caffè Mappa Ricerca fermate Versione app Orari di arrivo Richiesto aggiornamento del database Download dati dal server MaTO Mostra direzioni in maiuscolo Non cambiare Tutto in maiuscolo Solo prima lettera maiuscola Mostra arrivi quando tocchi una fermata Abilita esperimenti Schermata da mostrare all\'avvio Tocca per cambiare Fonte posizioni in tempo reale di bus e tram MaTO (aggiornate più spesso, può avere errori) GTFS RT (aggiornato meno frequentemente, posizioni più controllate) Linea aggiunta ai preferiti Linea rimossa dai preferiti Preferite Tocca a lungo la fermata per le opzioni Stile della mappa Versatiles (vettoriale) OSM Legacy (raster, più leggera) Rimuovi i dati dei trip (libera spazio) Tutti i trip GTFS sono rimossi dal database Mostra introduzione open source per il trasporto pubblico di Torino. Stai usando un\'app indipendente, senza pubblicità e senza nessun tracciamento.]]> Se ti trovi a una fermata, puoi scansionare il codice QR presente sulla palina toccando l\'icona a sinistra della barra di ricerca.]]> preferiti toccando la stella a fianco del nome.]]> fermate più vicine a te direttamente nella schermata principale...]]> posizioni in tempo reale dei bus e tram (in blu)]]> Guarda nelle Impostazioni per personalizzare l\'app come preferisci, e su Informazioni per sapere di più sull\'app e il team di sviluppo.]]> Capito, chiudi introduzione Chiudi introduzione Abilita accesso alla posizione Accesso alla posizione abilitato Accesso alla posizione non consentito dall\'utente Abilita notifiche Notifiche abilitate Backup e ripristino Dati salvati Backup Ripristino Backup completato Salva o ripristina i dati Salva backup Importa i dati dal backup Backup importato Seleziona almeno un elemento da importare! Importa preferiti dal backup Importa preferenze dal backup Nessuna app disponibile per mostrare la fermata! Destinazione sconosciuta Direzione già selezionata Sei troppo lontano, posizione nascosta Caricamento destinazione… Ciao fragment vuoto Il servizio delle posizioni funziona normalmente Nessuna posizione ricevuta Errore nella connessione al server Errore nel parsing della risposta Errore: risposta dal server inaspettata In connessione... Fonte posizioni in tempo reale: Cambia fonte Rimuovi posizioni sulla mappa quando si cambia fonte delle posizioni in tempo reale Aggiornato: %1$s Nessun avviso nella tua lingua, mostrati in %1$s Italiano Inglese Avvisi per la linea %1$s: Controllo degli avvisi disponibili in corso Servizio GPS non trovato sul dispositivo! Download dati avvisi in tempo reale Permesso mancante Per usare questa funzionalità, l\'app necessita dell\'accesso alla posizione, che ora può essere dato solo dalle impostazioni di sistema. Apri le impostazioni Premi ancora \"indietro\" per uscire dall\'app Chiaro Scuro Segui il sistema Imposta tema scuro o chiaro Nessuna informazione trasmessa sulla direzione o sul viaggio del veicolo. Download in corso delle informazioni sul viaggio + Nessuna fermata trovata con questo nome + Nessuna fermata trovata con questo numero
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3d627d3..829603a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,422 +1,424 @@ BusTO Libre BusTO BusTO dev BusTO git You\'re using the latest in technology when it comes to respecting your privacy. Search Scan QR Code Yes No Next Previous Barcode scanner app is needed This functionality requires another app to scan the QR codes, which has not been found on the device. We suggest using Binary Eye, which is open source software, would you like to install it now? Bus stop number Bus stop name Insert bus stop number Insert bus stop name %1$s towards %2$s %s (unknown destination) Verify your Internet connection! Seems that no bus stop has this name No arrivals found for this stop Error parsing the 5T/GTT website (damn site!) Name too short, type more characters and retry Arrivals at: %1$s Arrivals at: Choose the bus stop… Line Lines Urban lines Extra urban lines Tourist lines No lines found in this category No lines match the searched name Destination: Lines: %1$s Line %1$s Line %1$s towards: Stop %1$s Vehicle %1$s No timetable found No QR code found, retry Scan QR code at the bus stop Unexpected internal error, cannot extract data from GTT/5T website Help About the app More about Open the wiki https://gitpull.it/w/librebusto/en/ Source code Licence11 Meet the author Bus stop is now in your favorites Bus stop removed from your favorites Added line to favorites Remove line from favorites Favorites Favorites Favorites Map No favorites? Arghh! Press on a bus stop star to populate this list! Delete Rename Rename the bus stop Reset About the app Tap the star to add the bus stop to the favourites\n\nHow to read timelines:\n   12:56* Real-time arrivals\n   12:56   Scheduled arrivals\n\nPull down to refresh the timetable \n Long press on Arrivals source to change the source of the arrival times GOT IT! Arrival times No arrivals found for lines: Welcome!

Thanks for using BusTO, an open source and independent app useful to move around Torino using a Free/Libre software.


Why use this app?

- You\'ll never be tracked
- You\'ll never see boring ads
- We\'ll always respect your privacy
- Moreover, it\'s lightweight!


Introductory tutorial

If you want to see the introduction again, use the button below:

]]>
News and Updates

On the Telegram channel, you can find information about the latest app updates

]]>
How does it work?

This app is able to do all the amazing things it does by pulling data from www.gtt.to.it, www.5t.torino.it or muoversiatorino.it "for personal use", along with open data from the AperTO (aperto.comune.torino.it) website.


The work of several people is behind this app, in particular:
- Fabio Mazza, current senior rockstar developer.
- Andrea Ugo, current junior rockstar developer.
- Silviu Chiriac, designer of the 2021 logo.
- Marco M, rockstar tester and bug hunter.
- Ludovico Pavesi, previous senior rockstar developer (asd).
- Valerio Bozzolan, maintainer and infrastructure (sponsor).
- Marco Gagino, contributor and first icon creator.
- JSoup web scraper library.
- makovkastar floating buttons.
- Google for icons and support and design libraries.
- Other icons from Bootstrap, Feather, Remix and Hero Icons.
- All the contributors, and the beta testers, too!


If you want more detailed information, or want to donate money to support the development, use the buttons below!

]]>
Licenses

The app and the related source code are released by Valerio Bozzolan and the other authors under the terms of the GNU General Public License v3+). So everyone is allowed to use, to study, to improve and to share this app by any kind of means and for any purpose: under the conditions of maintaining this rights and of attributing the original work to Valerio Bozzolan.


Notes

This app has been developed with the hope to be useful to everyone, but comes without ANY warranty of any kind.

The data used by the app comes directly from GTT and other public agencies: if you find any errors, please take it up to them, not to us.

This translation is kindly provided by Riccardo Caniato, Marco Gagino and Fabio Mazza.

Now you can hack public transport, too! :)

]]>
Cannot add to favorites (storage full or corrupted database?)! View on a map Show line details Show full direction Cannot find any application to show it in Cannot find the position of the stop ListFragment - BusTO it.reyboz.bustorino.preferences db_is_updating Near me Nearby stops Nearby arrivals App version The number of stops to show in the recent stops is invalid Invalid value, put a valid number Finding location No stops nearby + No stop found matching this name + No stop found matching this number Loading arrival times No stops nearby to search arrival times for Minimum number of stops Preferences Settings Settings General Experimental features Maximum distance (meters) Recent stops General settings Database management Launch manual database update Allow access to location to show it on the map Allow access to location to show stops nearby Please enable location on the device No GPS receiver found on the device! Database update in progress… Updating the database Force database update Touch to update the app database now is arriving at at the stop %1$s - %2$s Show arrivals Show stops Join Telegram channel Show introduction Center on my location Follow me Enable or disable location Location enabled Location disabled Location is disabled on device Arrivals source: %1$s Loading arrivals from %1$s GTT App GTT Website 5T Torino website Muoversi a Torino Undetermined Changing arrival times source… Long press to change the source of arrivals @string/source_mato @string/fivetapifetcher @string/gttjsonfetcher @string/fivetscraper Sources of arrival times Select which sources of arrival times to use Default Default channel for notifications Database operations Updates of the app database BusTO - live position service Live positions Showing activity related to the live positions service MaTO live bus positions service is running Downloading trips from MaTO server Asked for %1$s permission too many times Cannot use the map with the storage permission! storage The application has crashed because you encountered a bug. \nIf you want, you can help the developers by sending the crash report via email. \nNote that no sensitive data is contained in the report, just small bits of info on your phone and app configuration/state. The application crashed and the crash report is in the attachments. Please describe what you were doing before the crash: \n Arrivals Home Map Favorites Open navigation drawer Close navigation drawer Experiments Buy us a coffee Map Search by stop Filter by name Launching database update Downloading data from MaTO server Downloading realtime alerts data Capitalize directions @string/directions_capitalize_no_change @string/directions_capitalize_everything @string/directions_capitalize_first_letter Do not change arrivals directions Capitalize everything Capitalize only first letter KEEP CAPITALIZE_ALL CAPITALIZE_FIRST Section to show on startup Touch to change it Show arrivals touching on stop Enable experiments Long press the stop for options @string/nav_home_text @string/near_me_title @string/nav_favorites_text @string/nav_map_text @string/lines Light Dark Change it with the system Set dark or light theme Source of real time positions for buses and trams MaTO (updated more frequently, might have errors) GTFS RT (less frequently updated, more accurate) @string/positions_source_mato_descr @string/positions_source_gtfsrt_descr "You are too far, not showing your position Style of the map Versatiles (vector) OSM legacy (raster, lighter) @string/map_style_versatiles @string/map_style_legacy_raster Remove trips data (free up space) All GTFS trips have been removed from the database Show tutorial open source app for Turin public transport. This is an independent app, with no ads and no tracking whatsoever.]]> favorites by touching the star next to its name]]> blue)]]> Settings to customize the app behaviour, and in the About the app section if you want to know more about the app and the developers.]]> Notifications permission to show the information about background processing. Press the button below to grant it]]> Grant location permission Location permission granted Location permission has not been granted Missing permission To use this functionality, the application needs access to the location, which now can only be granted in the system settings. Open settings OK, close the tutorial Close the tutorial Enable notifications Notifications enabled Backup and restore Backup Restore Backup or restore data Data saved Backup completed Backup to file Import data from backup Backup has been imported Check at least one item to import! Import favorites from backup Import preferences from backup Hello blank fragment No map app present to show the stop! Direction is already shown Loading destination… Destination unknown Service for positions working normally No positions received Error connecting to the server Error parsing the server response Error: network response is not as expected Connecting... MaTO GTFS RT Live positions source: Switch source Clear bus positions when switching live positions source Updated: %1$s Alerts for line %1$s: Alerts for stop %1$s: No alerts in your language, showing in %1$s Italian English Checking new alerts now Press back again to close the app Donate No information on the direction or trip of the vehicle was transmitted. Downloading trip information…