Hi Everyone, I wrote code of GPSTracker that givin...
# compose
m
Hi Everyone, I wrote code of GPSTracker that giving correct coordinates but it not working first time when location permission dialog appears it work second time when open app agian. Kindly see and tell me solution or how to fix it. I am very thankful.
g
I suggest posting the code instead of prints of it. It's much easier to test and debug this way.
m
Right Dear. I follow it next time. Thanks Dear
b
You have an empty list for your coordinates and when you try to access the element on index 0 you get that error that is shown on the image. That happens in the MainContent function where you are accessing that list in this line of your code:
val locationCoordinates = Coordinates(cords[0].latitude, cords[0].longitude)
That happens because you have set an empty list as a default value for your
coords
list in MainComponent in this line of code:
val cords: List<Locator.Coordinate> by mainViewModel.myCords.observeAsState(listOf)
. I suggest for you to add if check before accessing elements from that list to prevent accessing an empty list.
m
Thanks so much @Blaž Vantur for your great thinking about problem.
m
Okay Dear @Adam Powell I understand and follow at next time.
Copy code
private var gpsTracker: GPSTracker? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Locator.requestPermissionLocation(this)
    gpsTracker = GPSTracker(applicationContext)

    setContent {
        RukuhTheme {
            Surface(color = MaterialTheme.colors.background) {
                App(gpsTracker!!)
            }
        }
    }
}
Copy code
@Composable
fun App(gpsTracker: GPSTracker) {
    val doubleLatitude: Double?
    val doubleLongitude: Double?
    doubleLatitude = gpsTracker.getLatitude()
    doubleLongitude = gpsTracker.getLongitude()
    if (doubleLatitude != 0.0 && doubleLongitude != 0.0)
        MainContent(doubleLatitude, doubleLongitude)
    else {
        Text(text = "Empty List")
    }
}