Miscellaneous code cleanup

master
TacoTheDank 2020-07-31 21:04:52 -04:00
parent 4dcea97982
commit 66f4865de3
26 changed files with 177 additions and 193 deletions

View File

@ -78,13 +78,13 @@ class MainActivity : AppCompatActivity() {
navHostFragment.navController.addOnDestinationChangedListener { _, destination, _ ->
when (destination.id) {
R.id.fragment_track -> {
runOnUiThread(Runnable() {
run() {
runOnUiThread {
run {
// mark menu item "Tracks" as checked
bottomNavigationView.menu.findItem(R.id.tracklist_fragment)
.setChecked(true)
}
})
}
}
else -> {
// do nothing
@ -111,7 +111,7 @@ class MainActivity : AppCompatActivity() {
* Defines the listener for changes in shared preferences
*/
private val sharedPreferenceChangeListener =
SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
when (key) {
Keys.PREF_THEME_SELECTION -> {
AppThemeHelper.setTheme(PreferencesHelper.loadThemeSelection(this@MainActivity))

View File

@ -281,7 +281,7 @@ class MapFragment : Fragment(), YesNoDialog.YesNoDialogListener, MapOverlay.Mark
/* Opens a track in TrackFragment */
private fun openTrack(tracklistElement: TracklistElement) {
val bundle: Bundle = Bundle()
val bundle = Bundle()
bundle.putString(Keys.ARG_TRACK_TITLE, tracklistElement.name)
bundle.putString(Keys.ARG_TRACK_FILE_URI, tracklistElement.trackUriString)
bundle.putString(Keys.ARG_GPX_FILE_URI, tracklistElement.gpxUriString)
@ -294,7 +294,7 @@ class MapFragment : Fragment(), YesNoDialog.YesNoDialogListener, MapOverlay.Mark
* Defines the listener for changes in shared preferences
*/
private val sharedPreferenceChangeListener =
SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
when (key) {
Keys.PREF_TRACKING_STATE -> {
if (activity != null) {

View File

@ -63,7 +63,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
val screen = preferenceManager.createPreferenceScreen(context)
// set up "Restrict to GPS" preference
val preferenceGpsOnly: SwitchPreferenceCompat = SwitchPreferenceCompat(activity as Context)
val preferenceGpsOnly = SwitchPreferenceCompat(activity as Context)
preferenceGpsOnly.title = getString(R.string.pref_gps_only_title)
preferenceGpsOnly.setIcon(R.drawable.ic_gps_24dp)
preferenceGpsOnly.key = Keys.PREF_GPS_ONLY
@ -72,8 +72,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
preferenceGpsOnly.setDefaultValue(false)
// set up "Use Imperial Measurements" preference
val preferenceImperialMeasurementUnits: SwitchPreferenceCompat =
SwitchPreferenceCompat(activity as Context)
val preferenceImperialMeasurementUnits = SwitchPreferenceCompat(activity as Context)
preferenceImperialMeasurementUnits.title =
getString(R.string.pref_imperial_measurement_units_title)
preferenceImperialMeasurementUnits.setIcon(R.drawable.ic_square_foot_24px)
@ -85,7 +84,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
preferenceImperialMeasurementUnits.setDefaultValue(LengthUnitHelper.useImperialUnits())
// set up "App Theme" preference
val preferenceThemeSelection: ListPreference = ListPreference(activity as Context)
val preferenceThemeSelection = ListPreference(activity as Context)
preferenceThemeSelection.title = getString(R.string.pref_theme_selection_title)
preferenceThemeSelection.setIcon(R.drawable.ic_smartphone_24dp)
preferenceThemeSelection.key = Keys.PREF_THEME_SELECTION
@ -107,9 +106,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
if (preference is ListPreference) {
val index: Int = preference.entryValues.indexOf(newValue)
preferenceThemeSelection.summary =
"${getString(R.string.pref_theme_selection_summary)} ${preference.entries.get(
index
)}"
"${getString(R.string.pref_theme_selection_summary)} ${preference.entries[index]}"
return@setOnPreferenceChangeListener true
} else {
return@setOnPreferenceChangeListener false
@ -117,7 +114,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
}
// set up "Delete Non-Starred" preference
val preferenceDeleteNonStarred: Preference = Preference(activity as Context)
val preferenceDeleteNonStarred = Preference(activity as Context)
preferenceDeleteNonStarred.title = getString(R.string.pref_delete_non_starred_title)
preferenceDeleteNonStarred.setIcon(R.drawable.ic_delete_24dp)
preferenceDeleteNonStarred.summary = getString(R.string.pref_delete_non_starred_summary)
@ -132,7 +129,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
}
// set up "Accuracy Threshold" preference
val preferenceAccuracyThreshold: SeekBarPreference = SeekBarPreference(activity as Context)
val preferenceAccuracyThreshold = SeekBarPreference(activity as Context)
preferenceAccuracyThreshold.title = getString(R.string.pref_accuracy_threshold_title)
preferenceAccuracyThreshold.setIcon(R.drawable.ic_timeline_24dp)
preferenceAccuracyThreshold.key = Keys.PREF_LOCATION_ACCURACY_THRESHOLD
@ -142,7 +139,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
preferenceAccuracyThreshold.setDefaultValue(Keys.DEFAULT_THRESHOLD_LOCATION_ACCURACY)
// set up "Reset" preference
val preferenceResetAdvanced: Preference = Preference(activity as Context)
val preferenceResetAdvanced = Preference(activity as Context)
preferenceResetAdvanced.title = getString(R.string.pref_reset_advanced_title)
preferenceResetAdvanced.setIcon(R.drawable.ic_undo_24dp)
preferenceResetAdvanced.summary = getString(R.string.pref_reset_advanced_summary)
@ -152,7 +149,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
}
// set up "App Version" preference
val preferenceAppVersion: Preference = Preference(context)
val preferenceAppVersion = Preference(context)
preferenceAppVersion.title = getString(R.string.pref_app_version_title)
preferenceAppVersion.setIcon(R.drawable.ic_info_24dp)
preferenceAppVersion.summary =
@ -174,7 +171,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
}
// set up "Report Issue" preference
val preferenceReportIssue: Preference = Preference(context)
val preferenceReportIssue = Preference(context)
preferenceReportIssue.title = getString(R.string.pref_report_issue_title)
preferenceReportIssue.setIcon(R.drawable.ic_bug_report_24dp)
preferenceReportIssue.summary = getString(R.string.pref_report_issue_summary)
@ -189,21 +186,21 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
}
// set preference categories
val preferenceCategoryGeneral: PreferenceCategory = PreferenceCategory(activity as Context)
val preferenceCategoryGeneral = PreferenceCategory(activity as Context)
preferenceCategoryGeneral.title = getString(R.string.pref_general_title)
preferenceCategoryGeneral.contains(preferenceImperialMeasurementUnits)
preferenceCategoryGeneral.contains(preferenceGpsOnly)
val preferenceCategoryMaintenance: PreferenceCategory =
val preferenceCategoryMaintenance =
PreferenceCategory(activity as Context)
preferenceCategoryMaintenance.title = getString(R.string.pref_maintenance_title)
preferenceCategoryMaintenance.contains(preferenceDeleteNonStarred)
val preferenceCategoryAdvanced: PreferenceCategory = PreferenceCategory(activity as Context)
val preferenceCategoryAdvanced = PreferenceCategory(activity as Context)
preferenceCategoryAdvanced.title = getString(R.string.pref_advanced_title)
preferenceCategoryAdvanced.contains(preferenceAccuracyThreshold)
preferenceCategoryAdvanced.contains(preferenceResetAdvanced)
val preferenceCategoryAbout: PreferenceCategory = PreferenceCategory(context)
val preferenceCategoryAbout = PreferenceCategory(context)
preferenceCategoryAbout.title = getString(R.string.pref_about_title)
preferenceCategoryAbout.contains(preferenceAppVersion)
preferenceCategoryAbout.contains(preferenceReportIssue)
@ -249,7 +246,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
/* Removes track and track files for given position - used by TracklistFragment */
fun deleteNonStarred(context: Context) {
private fun deleteNonStarred(context: Context) {
val backgroundJob = Job()
val uiScope = CoroutineScope(Dispatchers.Main + backgroundJob)
uiScope.launch {

View File

@ -64,10 +64,10 @@ class TrackFragment : Fragment(), RenameTrackDialog.RenameTrackListener,
// get track
val fileUriString: String =
arguments?.getString(Keys.ARG_TRACK_FILE_URI, String()) ?: String()
if (fileUriString.isNotBlank()) {
track = FileHelper.readTrack(activity as Context, Uri.parse(fileUriString))
track = if (fileUriString.isNotBlank()) {
FileHelper.readTrack(Uri.parse(fileUriString))
} else {
track = Track()
Track()
}
}
@ -99,7 +99,7 @@ class TrackFragment : Fragment(), RenameTrackDialog.RenameTrackListener,
}
// set up delete button
layout.deleteButton.setOnClickListener {
val dialogMessage: String =
val dialogMessage =
"${getString(R.string.dialog_yes_no_message_delete_recording)}\n\n- ${layout.trackNameView.text}"
YesNoDialog(this@TrackFragment as YesNoDialog.YesNoDialogListener).show(
context = activity as Context,

View File

@ -48,7 +48,7 @@ import kotlin.coroutines.CoroutineContext
/*
* TrackerService class
*/
class TrackerService() : Service(), CoroutineScope, SensorEventListener {
class TrackerService : Service(), CoroutineScope, SensorEventListener {
/* Define log tag */
private val TAG: String = LogHelper.makeLogTag(TrackerService::class.java)
@ -58,16 +58,16 @@ class TrackerService() : Service(), CoroutineScope, SensorEventListener {
var trackingState: Int = Keys.STATE_TRACKING_NOT
var gpsProviderActive: Boolean = false
var networkProviderActive: Boolean = false
var useImperial: Boolean = false
var gpsOnly: Boolean = false
private var useImperial: Boolean = false
private var gpsOnly: Boolean = false
var locationAccuracyThreshold: Int = Keys.DEFAULT_THRESHOLD_LOCATION_ACCURACY
var currentBestLocation: Location = LocationHelper.getDefaultLocation()
var stepCountOffset: Float = 0f
private var stepCountOffset: Float = 0f
var resumed: Boolean = false
var track: Track = Track()
var gpsLocationListenerRegistered: Boolean = false
var networkLocationListenerRegistered: Boolean = false
var bound: Boolean = false
private var gpsLocationListenerRegistered: Boolean = false
private var networkLocationListenerRegistered: Boolean = false
private var bound: Boolean = false
private val binder = LocalBinder()
private val handler: Handler = Handler()
private lateinit var locationManager: LocationManager
@ -99,7 +99,7 @@ class TrackerService() : Service(), CoroutineScope, SensorEventListener {
networkLocationListener = createLocationListener()
trackingState = PreferencesHelper.loadTrackingState(this)
currentBestLocation = LocationHelper.getLastKnownLocation(this)
track = FileHelper.readTrack(this, FileHelper.getTempFileUri(this))
track = FileHelper.readTrack(FileHelper.getTempFileUri(this))
backgroundJob = Job()
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener)
@ -194,7 +194,7 @@ class TrackerService() : Service(), CoroutineScope, SensorEventListener {
/* Overrides onSensorChanged from SensorEventListener */
override fun onSensorChanged(sensorEvent: SensorEvent?) {
var steps: Float = 0f
var steps = 0f
if (sensorEvent != null) {
if (stepCountOffset == 0f) {
// store steps previously recorded by the system
@ -212,11 +212,11 @@ class TrackerService() : Service(), CoroutineScope, SensorEventListener {
/* Resume tracking after stop/pause */
fun resumeTracking() {
// load temp track - returns an empty track if not available
track = FileHelper.readTrack(this, FileHelper.getTempFileUri(this))
track = FileHelper.readTrack(FileHelper.getTempFileUri(this))
// try to mark last waypoint as stopover
if (track.wayPoints.size > 0) {
val lastWayPointIndex = track.wayPoints.size - 1
track.wayPoints.get(lastWayPointIndex).isStopOver = true
track.wayPoints[lastWayPointIndex].isStopOver = true
}
// set resumed flag
resumed = true
@ -480,7 +480,7 @@ class TrackerService() : Service(), CoroutineScope, SensorEventListener {
* Defines the listener for changes in shared preferences
*/
private val sharedPreferenceChangeListener =
SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
when (key) {
// preference "Restrict to GPS"
Keys.PREF_GPS_ONLY -> {
@ -524,7 +524,6 @@ class TrackerService() : Service(), CoroutineScope, SensorEventListener {
override fun run() {
// add waypoint to track - step count is continuously updated in onSensorChanged
val result: Pair<Track, Boolean> = TrackHelper.addWayPointToTrack(
this@TrackerService,
track,
currentBestLocation,
locationAccuracyThreshold,

View File

@ -31,7 +31,7 @@ import org.y20k.trackbook.helpers.PreferencesHelper
/*
* TrackingToggleTileService class
*/
class TrackingToggleTileService() : TileService() {
class TrackingToggleTileService : TileService() {
/* Define log tag */
private val TAG: String = LogHelper.makeLogTag(TrackingToggleTileService::class.java)
@ -52,11 +52,6 @@ class TrackingToggleTileService() : TileService() {
updateTile()
}
/* Overrides onTileRemoved from TileService */
override fun onTileRemoved() {
super.onTileRemoved()
}
/* Overrides onStartListening from TileService (tile becomes visible) */
override fun onStartListening() {
@ -90,12 +85,6 @@ class TrackingToggleTileService() : TileService() {
}
/* Overrides onDestroy from Service */
override fun onDestroy() {
super.onDestroy()
}
/* Update quick settings tile */
private fun updateTile() {
val tile: Tile = qsTile
@ -141,7 +130,7 @@ class TrackingToggleTileService() : TileService() {
* Defines the listener for changes in shared preferences
*/
private val sharedPreferenceChangeListener =
SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
when (key) {
Keys.PREF_TRACKING_STATE -> {
trackingState = PreferencesHelper.loadTrackingState(this)

View File

@ -82,7 +82,7 @@ class TracklistFragment : Fragment(), TracklistAdapter.TracklistAdapterListener,
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// ask user
val adapterPosition: Int = viewHolder.adapterPosition
val dialogMessage: String =
val dialogMessage =
"${getString(R.string.dialog_yes_no_message_delete_recording)}\n\n- ${tracklistAdapter.getTrackName(
adapterPosition
)}"
@ -107,7 +107,7 @@ class TracklistFragment : Fragment(), TracklistAdapter.TracklistAdapterListener,
/* Overrides onTrackElementTapped from TracklistElementAdapterListener */
override fun onTrackElementTapped(tracklistElement: TracklistElement) {
val bundle: Bundle = Bundle()
val bundle = Bundle()
bundle.putString(Keys.ARG_TRACK_TITLE, tracklistElement.name)
bundle.putString(Keys.ARG_TRACK_FILE_URI, tracklistElement.trackUriString)
bundle.putString(Keys.ARG_GPX_FILE_URI, tracklistElement.gpxUriString)

View File

@ -45,7 +45,7 @@ data class WayPoint(
/* Converts WayPoint into Location */
fun toLocation(): Location {
val location: Location = Location(provider)
val location = Location(provider)
location.latitude = latitude
location.longitude = longitude
location.altitude = altitude

View File

@ -18,7 +18,6 @@
package org.y20k.trackbook.dialogs
import android.content.Context
import android.content.DialogInterface
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
@ -45,8 +44,7 @@ object ErrorDialog {
errorDetails: String = String()
) {
// prepare dialog builder
val builder: MaterialAlertDialogBuilder =
MaterialAlertDialogBuilder(context, R.style.AlertDialogTheme)
val builder = MaterialAlertDialogBuilder(context, R.style.AlertDialogTheme)
// set title
builder.setTitle(context.getString(errorTitle))
@ -88,11 +86,11 @@ object ErrorDialog {
// add okay button
builder.setPositiveButton(
R.string.dialog_generic_button_okay,
DialogInterface.OnClickListener { _, _ ->
// listen for click on okay button
// do nothing
})
R.string.dialog_generic_button_okay
) { _, _ ->
// listen for click on okay button
// do nothing
}
// display error dialog
builder.show()

View File

@ -45,7 +45,7 @@ class RenameTrackDialog(private var renameTrackListener: RenameTrackListener) {
/* Construct and show dialog */
fun show(context: Context, trackName: String) {
// prepare dialog builder
val builder: MaterialAlertDialogBuilder = MaterialAlertDialogBuilder(context)
val builder = MaterialAlertDialogBuilder(context)
// get input field
val inflater = LayoutInflater.from(context)

View File

@ -75,8 +75,7 @@ class YesNoDialog(private var yesNoDialogListener: YesNoDialogListener) {
) {
// prepare dialog builder
val builder: MaterialAlertDialogBuilder =
MaterialAlertDialogBuilder(context, R.style.AlertDialogTheme)
val builder = MaterialAlertDialogBuilder(context, R.style.AlertDialogTheme)
// set title and message
builder.setMessage(messageString)
@ -98,7 +97,7 @@ class YesNoDialog(private var yesNoDialogListener: YesNoDialogListener) {
}
// handle outside-click as "no"
builder.setOnCancelListener() {
builder.setOnCancelListener {
yesNoDialogListener.onYesNoDialog(type, false, payload, payloadString)
}

View File

@ -19,13 +19,15 @@ package org.y20k.trackbook.extensions
import android.content.SharedPreferences
import java.lang.Double.doubleToRawLongBits
import java.lang.Double.longBitsToDouble
/* Puts a Double value in SharedPreferences */
fun SharedPreferences.Editor.putDouble(key: String, double: Double) =
putLong(key, java.lang.Double.doubleToRawLongBits(double))
this.putLong(key, doubleToRawLongBits(double))
/* gets a Double value from SharedPreferences */
fun SharedPreferences.getDouble(key: String, default: Double) =
java.lang.Double.longBitsToDouble(getLong(key, java.lang.Double.doubleToRawLongBits(default)))
longBitsToDouble(getLong(key, doubleToRawLongBits(default)))

View File

@ -34,7 +34,7 @@ object DateTimeHelper {
/* Converts milliseconds to mm:ss or hh:mm:ss */
fun convertToReadableTime(context: Context, milliseconds: Long): String {
var timeString: String = String()
val timeString: String
val hours: Long = TimeUnit.MILLISECONDS.toHours(milliseconds)
val minutes: Long =
TimeUnit.MILLISECONDS.toMinutes(milliseconds) % TimeUnit.HOURS.toMinutes(1)
@ -44,14 +44,14 @@ object DateTimeHelper {
val m: String = context.getString(R.string.abbreviation_minutes)
val s: String = context.getString(R.string.abbreviation_seconds)
when (milliseconds >= Keys.ONE_HOUR_IN_MILLISECONDS) {
timeString = when (milliseconds >= Keys.ONE_HOUR_IN_MILLISECONDS) {
// CASE: format hh:mm:ss
true -> {
timeString = "$hours $h $minutes $m $seconds $s"
"$hours $h $minutes $m $seconds $s"
}
// CASE: format mm:ss
false -> {
timeString = "$minutes $m $seconds $s"
"$minutes $m $seconds $s"
}
}
return timeString
@ -60,7 +60,7 @@ object DateTimeHelper {
/* Create sortable string for date - used for filenames */
fun convertToSortableDateString(date: Date): String {
val dateFormat: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US)
val dateFormat = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US)
return dateFormat.format(date)
}
@ -85,7 +85,7 @@ object DateTimeHelper {
/* Calculates time difference between two locations */
fun calculateTimeDistance(previousLocation: Location?, location: Location): Long {
var timeDifference: Long = 0L
var timeDifference = 0L
// two data points needed to calculate time difference
if (previousLocation != null) {
// get time difference

View File

@ -35,6 +35,8 @@ import java.text.NumberFormat
import java.util.*
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlin.math.ln
import kotlin.math.pow
/*
@ -61,14 +63,14 @@ object FileHelper {
/* Get file size for given Uri */
fun getFileSize(context: Context, uri: Uri): Long {
val cursor: Cursor? = context.contentResolver.query(uri, null, null, null, null)
if (cursor != null) {
return if (cursor != null) {
val sizeIndex: Int = cursor.getColumnIndex(OpenableColumns.SIZE)
cursor.moveToFirst()
val size: Long = cursor.getLong(sizeIndex)
cursor.close()
return size
size
} else {
return 0L
0L
}
}
@ -76,14 +78,14 @@ object FileHelper {
/* Get file name for given Uri */
fun getFileName(context: Context, uri: Uri): String {
val cursor: Cursor? = context.contentResolver.query(uri, null, null, null, null)
if (cursor != null) {
return if (cursor != null) {
val nameIndex: Int = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
cursor.moveToFirst()
val name: String = cursor.getString(nameIndex)
cursor.close()
return name
name
} else {
return String()
String()
}
}
@ -110,8 +112,8 @@ object FileHelper {
fun readTracklist(context: Context): Tracklist {
LogHelper.v(TAG, "Reading Tracklist - Thread: ${Thread.currentThread().name}")
// get JSON from text file
val json: String = readTextFile(context, getTracklistFileUri(context))
var tracklist: Tracklist = Tracklist()
val json: String = readTextFile(getTracklistFileUri(context))
var tracklist = Tracklist()
when (json.isNotBlank()) {
// convert JSON and return as tracklist
true -> try {
@ -125,10 +127,10 @@ object FileHelper {
/* Reads track from storage using GSON */
fun readTrack(context: Context, fileUri: Uri): Track {
fun readTrack(fileUri: Uri): Track {
// get JSON from text file
val json: String = readTextFile(context, fileUri)
var track: Track = Track()
val json: String = readTextFile(fileUri)
var track = Track()
when (json.isNotEmpty()) {
// convert JSON and return as track
true -> try {
@ -305,7 +307,7 @@ object FileHelper {
tracklist.modificationDate = modificationDate
// convert to JSON
val gson: Gson = getCustomGson()
var json: String = String()
var json = String()
try {
json = gson.toJson(tracklist)
} catch (e: Exception) {
@ -328,7 +330,7 @@ object FileHelper {
private fun renameTrack(context: Context, track: Track, newName: String) {
// search track in tracklist
val tracklist: Tracklist = readTracklist(context)
var trackUriString: String = String()
var trackUriString = String()
tracklist.tracklistElements.forEach { tracklistElement ->
if (tracklistElement.getTrackId() == track.getTrackId()) {
// rename tracklist element
@ -402,7 +404,7 @@ object FileHelper {
/* Converts track to JSON */
private fun getTrackJsonString(track: Track): String {
val gson: Gson = getCustomGson()
var json: String = String()
var json = String()
try {
json = gson.toJson(track)
} catch (e: Exception) {
@ -432,13 +434,13 @@ object FileHelper {
if (bytes < unit) return "$bytes B"
// calculate exp
val exp: Int = (Math.log(bytes.toDouble()) / Math.log(unit.toDouble())).toInt()
val exp: Int = (ln(bytes.toDouble()) / ln(unit.toDouble())).toInt()
// determine prefix symbol
val prefix: String = ((if (si) "kMGTPE" else "KMGTPE")[exp - 1] + if (si) "" else "i")
// calculate result and set number format
val result: Double = bytes / Math.pow(unit.toDouble(), exp.toDouble())
val result: Double = bytes / unit.toDouble().pow(exp.toDouble())
val numberFormat = NumberFormat.getNumberInstance()
numberFormat.maximumFractionDigits = 1
@ -447,7 +449,7 @@ object FileHelper {
/* Reads InputStream from file uri and returns it as String */
private fun readTextFile(context: Context, fileUri: Uri): String {
private fun readTextFile(fileUri: Uri): String {
// todo read https://commonsware.com/blog/2016/03/15/how-consume-content-uri.html
// https://developer.android.com/training/secure-file-sharing/retrieve-info
val file: File = fileUri.toFile()
@ -457,7 +459,7 @@ object FileHelper {
}
// read until last line reached
val stream: InputStream = file.inputStream()
val reader: BufferedReader = BufferedReader(InputStreamReader(stream))
val reader = BufferedReader(InputStreamReader(stream))
val builder: StringBuilder = StringBuilder()
reader.forEachLine {
builder.append(it)
@ -477,7 +479,6 @@ object FileHelper {
/* Writes given bitmap as image file to storage */
private fun writeImageFile(
context: Context,
bitmap: Bitmap,
file: File,
format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG,

View File

@ -89,7 +89,7 @@ object LengthUnitHelper {
/* Determines which unit system the device is using (metric or imperial) */
fun useImperialUnits(): Boolean {
// America (US), Liberia (LR), Myanmar(MM) use the imperial system
val imperialSystemCountries = Arrays.asList("US", "LR", "MM")
val imperialSystemCountries = listOf("US", "LR", "MM")
val countryCode = Locale.getDefault().country
return imperialSystemCountries.contains(countryCode)
}
@ -102,7 +102,7 @@ object LengthUnitHelper {
trackLength: Float,
useImperialUnits: Boolean = false
): String {
var speed: String = "0"
var speed = "0"
// duration minus pause in seconds
val duration: Long = (trackDuration - trackRecordingPause) / 1000L
@ -117,21 +117,21 @@ object LengthUnitHelper {
speed = bd.toPlainString()
}
when (useImperialUnits) {
true -> return "$speed mph"
false -> return "$speed km/h"
return when (useImperialUnits) {
true -> "$speed mph"
false -> "$speed km/h"
}
}
/* Coverts meters per second to either km/h or mph */
fun convertMetersPerSecond(metersPerSecond: Float, useImperial: Boolean = false): Double {
if (useImperial) {
return if (useImperial) {
// mph
return metersPerSecond * 2.2369362920544
metersPerSecond * 2.2369362920544
} else {
// km/h
return metersPerSecond * 3.6
metersPerSecond * 3.6
}
}

View File

@ -40,7 +40,7 @@ object LocationHelper {
/* Get default location */
fun getDefaultLocation(): Location {
val defaultLocation: Location = Location(LocationManager.NETWORK_PROVIDER)
val defaultLocation = Location(LocationManager.NETWORK_PROVIDER)
defaultLocation.latitude = Keys.DEFAULT_LATITUDE
defaultLocation.longitude = Keys.DEFAULT_LONGITUDE
defaultLocation.accuracy = Keys.DEFAULT_ACCURACY
@ -75,10 +75,11 @@ object LocationHelper {
val lastKnownLocationNetwork: Location =
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
?: lastKnownLocation
when (isBetterLocation(lastKnownLocationGps, lastKnownLocationNetwork)) {
true -> lastKnownLocation = lastKnownLocationGps
false -> lastKnownLocation = lastKnownLocationNetwork
}
lastKnownLocation =
when (isBetterLocation(lastKnownLocationGps, lastKnownLocationNetwork)) {
true -> lastKnownLocationGps
false -> lastKnownLocationNetwork
}
}
return lastKnownLocation
}
@ -127,20 +128,20 @@ object LocationHelper {
/* Checks if GPS location provider is available and enabled */
fun isGpsEnabled(locationManager: LocationManager): Boolean {
if (locationManager.allProviders.contains(LocationManager.GPS_PROVIDER)) {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
return if (locationManager.allProviders.contains(LocationManager.GPS_PROVIDER)) {
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
} else {
return false
false
}
}
/* Checks if Network location provider is available and enabled */
fun isNetworkEnabled(locationManager: LocationManager): Boolean {
if (locationManager.allProviders.contains(LocationManager.NETWORK_PROVIDER)) {
return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
return if (locationManager.allProviders.contains(LocationManager.NETWORK_PROVIDER)) {
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
} else {
return false
false
}
}
@ -154,14 +155,10 @@ object LocationHelper {
/* Checks if given location is accurate */
fun isAccurateEnough(location: Location, locationAccuracyThreshold: Int): Boolean {
val isAccurate: Boolean
when (location.provider) {
LocationManager.GPS_PROVIDER -> isAccurate =
location.accuracy < locationAccuracyThreshold
else -> isAccurate =
location.accuracy < locationAccuracyThreshold + 10 // a bit more relaxed when location comes from network provider
return when (location.provider) {
LocationManager.GPS_PROVIDER -> location.accuracy < locationAccuracyThreshold
else -> location.accuracy < locationAccuracyThreshold + 10 // a bit more relaxed when location comes from network provider
}
return isAccurate
}
@ -204,10 +201,10 @@ object LocationHelper {
val distanceThreshold: Float
val averageAccuracy: Float = (previousLocation.accuracy + location.accuracy) / 2
// increase the distance threshold if one or both locations are
if (averageAccuracy > Keys.DEFAULT_THRESHOLD_DISTANCE) {
distanceThreshold = averageAccuracy
distanceThreshold = if (averageAccuracy > Keys.DEFAULT_THRESHOLD_DISTANCE) {
averageAccuracy
} else {
distanceThreshold = Keys.DEFAULT_THRESHOLD_DISTANCE
Keys.DEFAULT_THRESHOLD_DISTANCE
}
// location is different when far enough away from previous location
return calculateDistance(previousLocation, location) > distanceThreshold
@ -216,7 +213,7 @@ object LocationHelper {
/* Calculates distance in meters between two locations */
fun calculateDistance(previousLocation: Location?, location: Location): Float {
var distance: Float = 0f
var distance = 0f
// two data points needed to calculate distance
if (previousLocation != null) {
// add up distance

View File

@ -78,9 +78,9 @@ object LogHelper {
private fun log(tag: String, level: Int, t: Throwable?, vararg messages: Any) {
val message: String
if (t == null && messages.size == 1) {
message = if (t == null && messages.size == 1) {
// handle this common case without the extra cost of creating a stringbuffer:
message = messages[0].toString()
messages[0].toString()
} else {
val sb = StringBuilder()
for (m in messages) {
@ -89,7 +89,7 @@ object LogHelper {
if (t != null) {
sb.append("\n").append(Log.getStackTraceString(t))
}
message = sb.toString()
sb.toString()
}
Log.println(level, tag, message)
@ -112,4 +112,4 @@ object LogHelper {
// Log.println(level, tag, message)
// }
}
}
}

View File

@ -65,23 +65,25 @@ class MapOverlay(private var markerListener: MarkerListener) {
when (trackingState) {
// CASE: Tracking active
Keys.STATE_TRACKING_ACTIVE -> {
when (locationIsOld) {
true -> newMarker = ContextCompat.getDrawable(
newMarker = when (locationIsOld) {
true -> ContextCompat.getDrawable(
context,
R.drawable.ic_marker_location_red_grey_24dp
)!!
false -> newMarker =
ContextCompat.getDrawable(context, R.drawable.ic_marker_location_red_24dp)!!
false -> ContextCompat.getDrawable(
context,
R.drawable.ic_marker_location_red_24dp
)!!
}
}
// CASE. Tracking is NOT active
else -> {
when (locationIsOld) {
true -> newMarker = ContextCompat.getDrawable(
newMarker = when (locationIsOld) {
true -> ContextCompat.getDrawable(
context,
R.drawable.ic_marker_location_blue_grey_24dp
)!!
false -> newMarker = ContextCompat.getDrawable(
false -> ContextCompat.getDrawable(
context,
R.drawable.ic_marker_location_blue_24dp
)!!
@ -124,36 +126,42 @@ class MapOverlay(private var markerListener: MarkerListener) {
when (trackingState) {
// CASE: Recording is active
Keys.STATE_TRACKING_ACTIVE -> {
if (wayPoint.starred) {
newMarker =
newMarker = when {
wayPoint.starred -> {
ContextCompat.getDrawable(context, R.drawable.ic_star_red_24dp)!!
} else if (wayPoint.isStopOver) {
newMarker = ContextCompat.getDrawable(
context,
R.drawable.ic_marker_track_location_grey_24dp
)!!
} else {
newMarker = ContextCompat.getDrawable(
context,
R.drawable.ic_marker_track_location_red_24dp
)!!
}
wayPoint.isStopOver -> {
ContextCompat.getDrawable(
context,
R.drawable.ic_marker_track_location_grey_24dp
)!!
}
else -> {
ContextCompat.getDrawable(
context,
R.drawable.ic_marker_track_location_red_24dp
)!!
}
}
}
// CASE: Recording is paused/stopped
else -> {
if (wayPoint.starred) {
newMarker =
newMarker = when {
wayPoint.starred -> {
ContextCompat.getDrawable(context, R.drawable.ic_star_blue_24dp)!!
} else if (wayPoint.isStopOver) {
newMarker = ContextCompat.getDrawable(
context,
R.drawable.ic_marker_track_location_grey_24dp
)!!
} else {
newMarker = ContextCompat.getDrawable(
context,
R.drawable.ic_marker_track_location_blue_24dp
)!!
}
wayPoint.isStopOver -> {
ContextCompat.getDrawable(
context,
R.drawable.ic_marker_track_location_grey_24dp
)!!
}
else -> {
ContextCompat.getDrawable(
context,
R.drawable.ic_marker_track_location_blue_24dp
)!!
}
}
}
}
@ -185,13 +193,13 @@ class MapOverlay(private var markerListener: MarkerListener) {
provider: String,
time: Long
): OverlayItem {
val title: String =
val title =
"${context.getString(R.string.marker_description_time)}: ${SimpleDateFormat.getTimeInstance(
SimpleDateFormat.MEDIUM,
Locale.getDefault()
).format(time)}"
//val description: String = "${context.getString(R.string.marker_description_accuracy)}: ${DecimalFormat("#0.00").format(accuracy)} (${provider})"
val description: String =
val description =
"${context.getString(R.string.marker_description_time)}: ${SimpleDateFormat.getTimeInstance(
SimpleDateFormat.MEDIUM,
Locale.getDefault()
@ -199,7 +207,7 @@ class MapOverlay(private var markerListener: MarkerListener) {
.format(time)} | ${context.getString(R.string.marker_description_accuracy)}: ${DecimalFormat(
"#0.00"
).format(accuracy)} (${provider})"
val position: GeoPoint = GeoPoint(latitude, longitude)
val position = GeoPoint(latitude, longitude)
return OverlayItem(title, description, position)
}

View File

@ -116,7 +116,7 @@ object PreferencesHelper {
LocationManager.NETWORK_PROVIDER
) ?: LocationManager.NETWORK_PROVIDER
// create location
val currentBestLocation: Location = Location(provider)
val currentBestLocation = Location(provider)
// load location attributes
currentBestLocation.latitude =
settings.getDouble(Keys.PREF_CURRENT_BEST_LOCATION_LATITUDE, Keys.DEFAULT_LATITUDE)

View File

@ -47,9 +47,8 @@ object TrackHelper {
tracklistElement.date.time
/* Adds given locatiom as waypoint to track */
/* Adds given location as waypoint to track */
fun addWayPointToTrack(
context: Context,
track: Track,
location: Location,
locationAccuracyThreshold: Int,
@ -151,10 +150,10 @@ object TrackHelper {
// save number of satellites
val numberOfSatellites: Int
val extras = location.extras
if (extras != null && extras.containsKey("satellites")) {
numberOfSatellites = extras.getInt("satellites", 0)
numberOfSatellites = if (extras != null && extras.containsKey("satellites")) {
extras.getInt("satellites", 0)
} else {
numberOfSatellites = 0
0
}
// add current location as point to center on for later display
@ -187,10 +186,9 @@ object TrackHelper {
/* Creates GPX string for given track */
fun createGpxString(track: Track): String {
var gpxString: String
// add header
gpxString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" +
var gpxString: String = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" +
"<gpx version=\"1.1\" creator=\"Trackbook App (Android)\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n"

View File

@ -41,7 +41,7 @@ object UiHelper {
/* Sets layout margins for given view in DP */
fun setViewMargins(
private fun setViewMargins(
context: Context,
view: View,
left: Int = 0,

View File

@ -158,18 +158,17 @@ class TracklistAdapter(private val fragment: Fragment) :
private fun createTrackDataString(position: Int): String {
val tracklistElement: TracklistElement = tracklist.tracklistElements[position]
val trackDataString: String
when (tracklistElement.name == tracklistElement.dateString) {
trackDataString = when (tracklistElement.name == tracklistElement.dateString) {
// CASE: no individual name set - exclude date
true -> trackDataString = "${LengthUnitHelper.convertDistanceToString(
true -> "${LengthUnitHelper.convertDistanceToString(
tracklistElement.length,
useImperial
)} ${tracklistElement.durationString}"
// CASE: no individual name set - include date
false -> trackDataString =
"${tracklistElement.dateString}${LengthUnitHelper.convertDistanceToString(
tracklistElement.length,
useImperial
)} ${tracklistElement.durationString}"
false -> "${tracklistElement.dateString}${LengthUnitHelper.convertDistanceToString(
tracklistElement.length,
useImperial
)} ${tracklistElement.durationString}"
}
return trackDataString
}

View File

@ -65,11 +65,11 @@ data class MapFragmentLayoutHolder(
/* Main class variables */
val rootView: View
val mapView: MapView
val rootView: View = inflater.inflate(R.layout.fragment_map, container, false)
private val mapView: MapView
val currentLocationButton: FloatingActionButton
val recordingButton: FloatingActionButton
val recordingButtonSubMenu: Group
private val recordingButtonSubMenu: Group
val saveButton: FloatingActionButton
val clearButton: FloatingActionButton
val resumeButton: FloatingActionButton
@ -84,7 +84,6 @@ data class MapFragmentLayoutHolder(
/* Init block */
init {
// find views
rootView = inflater.inflate(R.layout.fragment_map, container, false)
mapView = rootView.findViewById(R.id.map)
currentLocationButton = rootView.findViewById(R.id.fab_location_button)
recordingButton = rootView.findViewById(R.id.fab_main_button)
@ -139,7 +138,7 @@ data class MapFragmentLayoutHolder(
/* Listen for user interaction */
@SuppressLint("ClickableViewAccessibility")
private fun addInteractionListener() {
mapView.setOnTouchListener { v, event ->
mapView.setOnTouchListener { _, _ ->
userInteraction = true
false
}
@ -160,7 +159,7 @@ data class MapFragmentLayoutHolder(
/* Save current best location and state of map to shared preferences */
fun saveState(currentBestLocation: Location) {
PreferencesHelper.saveCurrentBestLocation(context, currentBestLocation)
PreferencesHelper.saveZoomLevel(context, mapView.getZoomLevelDouble())
PreferencesHelper.saveZoomLevel(context, mapView.zoomLevelDouble)
// reset user interaction state
userInteraction = false
}

View File

@ -63,7 +63,7 @@ data class TrackFragmentLayoutHolder(
/* Main class variables */
val rootView: View
val rootView: View = inflater.inflate(R.layout.fragment_track, container, false)
val shareButton: ImageButton
val deleteButton: ImageButton
val editButton: ImageButton
@ -96,7 +96,6 @@ data class TrackFragmentLayoutHolder(
/* Init block */
init {
// find views
rootView = inflater.inflate(R.layout.fragment_track, container, false)
mapView = rootView.findViewById(R.id.map)
shareButton = rootView.findViewById(R.id.save_button)
deleteButton = rootView.findViewById(R.id.delete_button)
@ -202,10 +201,9 @@ data class TrackFragmentLayoutHolder(
private fun setupStatisticsViews() {
// get step count string
val steps: String
if (track.stepCount == -1f) steps =
context.getString(R.string.statistics_sheet_p_steps_no_pedometer)
else steps = track.stepCount.roundToInt().toString()
val steps: String =
if (track.stepCount == -1f) context.getString(R.string.statistics_sheet_p_steps_no_pedometer)
else track.stepCount.roundToInt().toString()
// populate views
trackNameView.text = track.name

View File

@ -13,7 +13,7 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="@string/descr_map_current_track"
android:visibility="visible"></org.osmdroid.views.MapView>
android:visibility="visible" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/container"

View File

@ -1,2 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>
<resources />