Kotlin - OnSharedPreferenceChangeListener

136
March 03, 2021, at 11:10 PM

I learn to develop my first Android app. I choose Kotlin, just because... I have to select between Java and Kotlin, Google adopted Kotlin as official language so I use it. I red lot of post before ask this, but nothing works for me. I want to execute function when I change parameters on my settings_activity. Switch button to switch between GoogleMap Satellite View to Normal View. How to instance OnSharedPreferenceChangeListener?

class MapsActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener,
        GoogleMap.OnCameraIdleListener {
    private lateinit var map: GoogleMap
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var lastLocation: Location
    private lateinit var locationCallback: LocationCallback
    private lateinit var locationRequest: LocationRequest
    private var locationUpdateState = false
    private lateinit var MarkerOp: MarkerOptions
    private lateinit var Marker: Marker
    private lateinit var currentLatLng: LatLng
    companion object {
        private const val LOCATION_PERMISSION_REQUEST_CODE = 1
        private const val REQUEST_CHECK_SETTINGS = 2
    }
    var sharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
        if (key == "satview") {
            var mysatview = sharedPreferences.getBoolean(key, false)
            if (mysatview) {
                map.mapType = GoogleMap.MAP_TYPE_HYBRID
            } else {
                map.mapType = GoogleMap.MAP_TYPE_NORMAL
            }
        }
    }
    private fun startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(
                this,
                android.Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
                LOCATION_PERMISSION_REQUEST_CODE
            )
            return
        }
        fusedLocationClient.requestLocationUpdates(
            locationRequest,
            locationCallback,
            null /* Looper */
        )
    }
    private fun createLocationRequest() {
        locationRequest = LocationRequest()
        locationRequest.interval = 10000
        locationRequest.fastestInterval = 5000
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        val builder = LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest)
        val clientPos = LocationServices.getSettingsClient(this)
        val taskPos = clientPos.checkLocationSettings(builder.build())
        taskPos.addOnSuccessListener {
            locationUpdateState = true
            startLocationUpdates()
        }
        taskPos.addOnFailureListener { exception ->
            if (exception is ResolvableApiException) {
                // Location settings are not satisfied, but this can be fixed
                // by showing the user a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    exception.startResolutionForResult(
                        this@MapsActivity,
                        REQUEST_CHECK_SETTINGS
                    )
                } catch (sendEx: IntentSender.SendIntentException) {
                    // Ignore the error.
                }
            }
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CHECK_SETTINGS) {
            if (resultCode == Activity.RESULT_OK) {
                locationUpdateState = true
                startLocationUpdates()
            }
        }
    }
    override fun onPause() {
        super.onPause()
        fusedLocationClient.removeLocationUpdates(locationCallback)
    }
    public override fun onResume() {
        super.onResume()
        if (!locationUpdateState) {
            startLocationUpdates()
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //this.supportActionBar?.hide()
        setContentView(R.layout.activity_maps)
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
        locationCallback = object : LocationCallback() {
            override fun onLocationResult(p0: LocationResult) {
                super.onLocationResult(p0)
                lastLocation = p0.lastLocation
                currentLatLng = LatLng(lastLocation.latitude, lastLocation.longitude)
                if(::Marker.isInitialized) {
                    Marker.remove()
                }
                MarkerOp = (MarkerOptions()
                        .position(currentLatLng)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow))
                        .rotation(-map.cameraPosition.bearing)
                        )
                Marker = map.addMarker(MarkerOp)
            }
        }
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        createLocationRequest()
    }
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        val inflater: MenuInflater = menuInflater
        inflater.inflate(R.menu.menu, menu)
        return true
    }
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle item selection
        when (item.itemId) {
            R.id.config -> {
                val intent = Intent(this, SettingsActivity::class.java)
                startActivity(intent)
                true
            }
            R.id.history -> {
                true
            }
        }
        return super.onOptionsItemSelected(item)
    }
    override fun onCameraIdle() {
        if(::MarkerOp.isInitialized) {
            MarkerOp.rotation(-map.cameraPosition.bearing)
        }
        if(::Marker.isInitialized) {
            Marker.remove()
            Marker = map.addMarker(MarkerOp)
        }
    }
    override fun onMapReady(googleMap: GoogleMap) {
        map = googleMap
        map.getUiSettings().setZoomControlsEnabled(true)
        map.setOnMarkerClickListener(this)
        map.setOnCameraIdleListener(this)
        val preferences = getPreferences(MODE_PRIVATE)
        preferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener)
        if (ActivityCompat.checkSelfPermission(
                this,
                android.Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
                LOCATION_PERMISSION_REQUEST_CODE
            )
            return
        }
        map.isMyLocationEnabled = true
    }
    override fun onMarkerClick(p0: Marker?) = false
}

I don't know why my event doesn't activate the listener. Thanks for your help.

READ ALSO
Is it possible to zip up and send a local (to the app) directory without requiring the user to select one?

Is it possible to zip up and send a local (to the app) directory without requiring the user to select one?

I'm attempting to create an app that can access a directory in the app's directory, zip it with JSZip and send it to an API at the press of a single button

110
Check if Column exceeding specific value and replace

Check if Column exceeding specific value and replace

I use the long list of codes similar to below codes, to check data frame with multiple columns

79
Radio and checkbox cannot be checked when inside BootStrap Modal

Radio and checkbox cannot be checked when inside BootStrap Modal

I have a bootstrap modal that needs to have both radio┬┤s and checkboxes, and when I place the below code outside the Modal they work as expected, but as soon as I move them inside the modal I am not able to check/choose themI am using Bootstrap v

91
linear-gradient over Gatsby-Background-Image

linear-gradient over Gatsby-Background-Image

I have an image that I reference from with a Graphql query in my codeOver this image I want to have a linear-gradient, which is located in my css module

127