Home > OS >  lateinit property mMap has not been initialized mMap
lateinit property mMap has not been initialized mMap

Time:10-05

Class that performs the service and initializes the mMap: GoogleMap

class LocationServiceUser : Service(), OnMapReadyCallback {
    private val serviceScopeUser = CoroutineScope(SupervisorJob()   Dispatchers.IO)
    private lateinit var locationClient: LocationClientUser
    private val db = FirebaseFirestore.getInstance()
    private lateinit var mMap: GoogleMap
    private val markerOptions = MarkerOptions()

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        locationClient = DefaultLocationClientUser(
            applicationContext,
            LocationServices.getFusedLocationProviderClient(applicationContext)
        )
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            ACTION_READING_DATA -> readingData()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap
    }

    fun readingData() {
        locationClient.getLocation(5000L)
            .catch { e -> e.printStackTrace() }
            .onEach { location ->
                var lat = location.latitude
                var lng = location.longitude
                var currentLatLng = LatLng(lat, lng)
                db.collection("").document("")
                    .addSnapshotListener { documentUser, error ->
                        if (documentUser != null) {
                            lat = documentUser.getGeoPoint("localizacao")?.latitude!!
                            lng = documentUser.getGeoPoint("localizacao")?.longitude!!
                            Log.d(
                                "Response",
                                "Dado lido a cada 5s:  lat: $lat, lng: $lng}"
                            )
                            currentLatLng = LatLng(lat, lng)
                        }
                        if (::mMap.isInitialized) {
                            mMap.addMarker(
                                MarkerOptions().position(currentLatLng)
                                    .title("Minha Localizacao atual")
                            )
                            Log.d("Response", "Minha localizacao de agora: $currentLatLng")
                        }else{
                            Log.d("Response", "readingData: Erro ao inicializar o mMap")
                        }
                        markerOptions.position(currentLatLng)
                        mMap.addMarker(markerOptions)
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLatLng))
                    }
            }.launchIn(serviceScopeUser)
    }

    override fun onDestroy() {
        super.onDestroy()
        serviceScopeUser.cancel()
    }

    companion object {
        const val ACTION_READING_DATA = "ACTION_READING_DATA"
    }

Fragment that uses this service class

class UserFragment: Fragment() {
    private var _binding: FragmentUserBinding? = null
    private val binding: FragmentUserBinding get() = _binding!!
    private lateinit var locationClientUser: LocationClientUser

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentUserBinding.inflate(inflater,container,false)

        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activity?.startService(Intent(context,LocationServices::class.java))
        locationClientUser = DefaultLocationClientUser(
            requireContext().applicationContext,
            LocationServices.getFusedLocationProviderClient(requireContext().applicationContext)
        )
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.btnReadingData.setOnClickListener {
            Intent(
                requireContext().applicationContext,
                LocationServiceUser::class.java
            ).apply {
                action = LocationServiceUser.ACTION_READING_DATA
                activity?.startService(this)
            }
        }
    }

It's having a problem initializing the lateinit var mMap: GoogleMap in the service, I know it's normal to start in the fragment, but it's my service that has the loc data I want to update. Is there a way to initialize this lateinit var in the service?

CodePudding user response:

mMap.addMarker(markerOptions)
                
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLatLng))

Add these two lines in this block also

if (::mMap.isInitialized) 
  • Related