0

I have searched a lot before posting this question
so it seams like I can't show the map using MapsActivity - I'm using Kotlin -
so this is my code

package com.example.digit.findmyphone

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast

import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.firebase.database.*
import java.util.HashMap  
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap

    var myRef:DatabaseReference?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)

        val bundle = intent.extras
        val phoneNumber = bundle.getString("phoneNumber")
        myRef = FirebaseDatabase.getInstance().reference
        myRef!!.child("Users").child(phoneNumber).child("location")
                .addValueEventListener(object: ValueEventListener{
                    override fun onCancelled(p0: DatabaseError?) {

                    }

                    override fun onDataChange(dataSnapShot: DataSnapshot?) {
                        try {
                            val tableData = dataSnapShot!!.value as HashMap<String, Any>
                            val latitude = tableData["latitude"].toString()
                            val longitude = tableData["longitude"].toString()
                            MapsActivity.sydney = LatLng(latitude.toDouble(),longitude.toDouble())
                            MapsActivity.lastSeen = tableData["last seen"].toString()

                            loadMap()
                        }catch (e:Exception){
                            Toast.makeText(applicationContext,"Error: "+e.message,Toast.LENGTH_LONG).show()
                            return
                        }
                    }

                }
                )
    }

    fun loadMap(){

        // 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)

    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    companion object {
        var sydney = LatLng(-34.0, 151.0)
        var lastSeen = "not defined"
    }
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add a marker in Sydney and move the camera

        mMap.addMarker(MarkerOptions().position(sydney).title(lastSeen))
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,15f))
    }
}

I have tried everything I know and I'm already writing the same code as the instructor but mine doesn't work and it gave me Error: null cannot be cast to non-null type com.google.android.gms.maps.supportmapfragment for this line
val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment
so after debugging this line returns null and I don't know why - it's built in not mine - I have even tried to remove all my adjustments for this file but the map didn't show up either
and this is the instructors code:
`

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap

    var dDatabaseRef:DatabaseReference?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)

        val bundle:Bundle=intent.extras
        val phoneNumber =bundle.getString("phoneNumber")
        dDatabaseRef=FirebaseDatabase.getInstance().reference

        dDatabaseRef!!.child("Users").child(phoneNumber)
                .child("location").addValueEventListener(object:ValueEventListener{

            override fun onDataChange(dataSnapshot: DataSnapshot?) {

                try{
                    val td= dataSnapshot!!.value as HashMap<String,Any>
                    val lat =td["lat"].toString()
                    val log =td["log"].toString()
                    MapsActivity.sydney= LatLng(lat.toDouble(),log.toDouble())
                    MapsActivity.lastOnline= td["lastOnline"].toString()
                    loadMap()
                }catch (ex:Exception){}
            }
            override fun onCancelled(p0: DatabaseError?) {

            }
        })
    }


    fun loadMap(){
        // 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)
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    companion object{
        var sydney = LatLng(-34.0, 151.0)
        var lastOnline="not defined"
    }
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add a marker in Sydney and move the camera

        mMap.addMarker(MarkerOptions().position(sydney).title(lastOnline))
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,15f))
    }
}

`
as you can see there is no deference between the two codes

so if anyone can help I'll be great full

Ahmed Sherif
  • 33
  • 1
  • 7
  • A couple of months ago I ran into [this](https://stackoverflow.com/questions/47269006/why-is-setting-onclicklistener-working-once) which basically does the same as a Java equivalent. Koltin works in misterious ways. – Chisko Mar 16 '18 at 02:14
  • BTW, you can get rid of your error with something like `val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment? ?: SupportMapFragment.newInstance()` if you follow fragment instantiation good practices – Chisko Mar 16 '18 at 02:22
  • 1
    Of course what I mean is, however you instantiate that fragment... – Chisko Mar 16 '18 at 03:40
  • @Chisko indeed it works in mysterious ways :D, – Ahmed Sherif Mar 16 '18 at 11:04
  • now we got red of the null problem and I don't understand yet why I had to create new instance in this way to work but I'm not complaining, the problem is now that the map it self doesn't show up, I'll try to create new map activity and see if it will show or not – Ahmed Sherif Mar 16 '18 at 11:06
  • as I thought, the map doesn't show even if I didn't change anything in it's original code – Ahmed Sherif Mar 16 '18 at 11:11
  • show your xmls. – Chisko Mar 16 '18 at 17:19
  • activity maps xml -> ` ` – Ahmed Sherif Mar 16 '18 at 22:01
  • Are you sure your firebase configuration is working? I think the problem is that the `loadMap()` function is not being called because the `myRef!!.child("Users").child(phoneNumber).child("location")` is not landing in `onDataChange()`, can you confirm it is? – Chisko Mar 16 '18 at 22:29
  • Yes, I'm sure. Everything is working just fine but the maps not, I have even created a new project with new api key and just have maps activity and it didn't show the map either. I have an old project that works fine with the map - I copied it's code and paste it in the new project but it didn't work - – Ahmed Sherif Mar 16 '18 at 22:46
  • Did you enable the Maps API in the Google Console? Probably even LogCat says something about it. – Chisko Mar 16 '18 at 22:54
  • OMG, that's actually worked, but question sorry, why I didn't need to do this step before? ... in my old app I didn't enable API for any project and it works perfectly – Ahmed Sherif Mar 16 '18 at 23:03
  • I think it was enabled by default until sometime ago. Glad I could help. – Chisko Mar 16 '18 at 23:12

0 Answers0