Page Menu
Home
GitPull.it
Search
Configure Global Search
Log In
Files
F15187301
NearbyStopsFragment.kt
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Authored By
Unknown
Size
31 KB
Referenced Files
None
Subscribers
None
NearbyStopsFragment.kt
View Options
/*
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 <http://www.gnu.org/licenses/>.
*/
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.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 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<Stop>? = 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<Palina>) {
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<RecyclerView>(R.id.stopGridRecyclerView)
gridLayoutManager = AutoFitGridLayoutManager(
context.getApplicationContext(),
utils.convertDipToPixels(context, COLUMN_WIDTH_DP.toFloat()).toInt()
)
gridRecyclerView.setLayoutManager(gridLayoutManager)
gridRecyclerView.setHasFixedSize(false)
circlingProgressBar = root.findViewById<ProgressBar>(R.id.circularProgressBar)
flatProgressBar = root.findViewById(R.id.horizontalProgressBar)
messageTextView = root.findViewById<TextView>(R.id.messageTextView)
enableLocationButton = root.findViewById(R.id.grantLocationButton)
titleTextView = root.findViewById<TextView>(R.id.titleTextView)
loadingTextView = root.findViewById<TextView>(R.id.positionLoadingTextView)
switchButton = root.findViewById<AppCompatButton>(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<Stop>){
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<RouteWithStop>){
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?>(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<Stop>, 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<Stop>, location: GPSPoint) {
// hide the progress bar
flatProgressBar.visibility = View.GONE
Collections.sort(stops, StopSorterByDistance(location))
if (dataAdapter == null) {
dataAdapter = SquareStopAdapter(stops, mListener, lastPosition)
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
}
}
}
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Thu, Nov 19, 09:47 (9 s ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2265695
Default Alt Text
NearbyStopsFragment.kt (31 KB)
Attached To
Mode
R4 Libre BusTO
Attached
Detach File
Event Timeline