Search code examples
androidlayoutkotlingoogle-geocoder

Type mismatch in Geocoder Address


I am implementing a code in kotlin to show an address in google map. I have the address stored in Firebase. I am extracting the data and converting the address into a string and then trying to find the latitude and longitude from the same. Here is my code for getting the latitude and longitude:

   private fun getLocationFromAddress(context: Context, addkey: String?): LatLng? {

    val coder = Geocoder(context)
    val address: List<Address>
    var p1: LatLng? = null
    var strAddress = ""

    try {

        val user = FirebaseAuth.getInstance().currentUser
        val userid = user?.uid
        mRef = FirebaseDatabase.getInstance().reference.child("users").child(userid.toString()).child("users")

        mRef.child(addkey.toString()).addValueEventListener(object: ValueEventListener{
            override fun onCancelled(p0: DatabaseError) {
            }

            override fun onDataChange(p0: DataSnapshot) {
                strAddress = p0.child("****").child(addkey.toString()).child("***").getValue(String::class.java)

            }

        })
        address = coder.getFromLocationName(strAddress, 5)
        if (address == null) {
            return null
        }

        val location = address[0]
        p1 = LatLng(location.latitude, location.longitude)

    } catch (ex: IOException) {

        ex.printStackTrace()
    }


    return p1

}

However, I am getting Type mismatch error at address = coder.getFromLocationName(strAddress, 5).

It says: "Type Mismatch. Required: List "My Project Name.com".Address Found: (Mutable)List android.location.Address!>!


Solution

  • The reason for that error is likely to be a wrong import. The error message says it's expecting a list of xxx.com.Address objects (look at where you defined val address: List<Address>) while it found a list of android.location.Address (which is the type returned by the Geocoder API).

    By changing the wrong import statement at the top of your file you should solve the issue. Or, even better, you could change your code so that you define the variable only where needed and let Kotlin's type inference do its "magic":

    val address = coder.getFromLocationName(strAddress, 5)
    

    EDIT

    In this specific case maybe you'd still may want to explicitly define the type because your Kotlin code is calling an API written in Java that doesn't use @Nullable/@NotNull (or similar annotations), so the compiler is not able to correctly infer nullity and the result type is a "platform type" (i.e., SomeType!). So if you know that something shouldn't be null you can force it to be non-null by explicitly typing your variable (or viceversa):

    val address: List<Address> = coder.getFromLocationName(strAddress, 5)
    

    More info: Null-Safety and Platform Types.