NullPointerException when using Kotlin Synthetic

605 Views Asked by At

I am getting a NullPointerException when I try to access an element in the layout from a DialogFragment. I have checked that, if I call getView() inside the same DialogFragment the result is 'null'.

Thank you in advance!

This is the Activity that calls commits the FragmentDialog "NewPOIDialog"

    class MainActivity : AppCompatActivity() {

    //Variables for Location service
    private var hasGps: Boolean = false
    private var hasNetwork: Boolean = false
    private var locationGps: Location? = null
    private var locationNetwork: Location? = null

    private companion object {
        private const val TAG = "MainActivity"
    }

    private lateinit var auth: FirebaseAuth
    private lateinit var permissionsRequestor: PermissionsRequestor
    private lateinit var mapView: MapView
    private lateinit var mapActivity: MapActivity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

        //Get the authorisation from Firebase
        auth = Firebase.auth

        Log.d("", "HERE SDK version: " + SDKBuildInformation.sdkVersion().versionName)

        // Get a MapView instance from layout.
        mapView = findViewById(R.id.map_view)
        mapView.onCreate(savedInstanceState)

        location()
        handleAndroidPermissions()
    }

    fun searchInMap(view: View?) {

        NewPOIDialog().show(supportFragmentManager, "test")
    }

    fun clearRouteButtonClicked(view: View?) {
        mapActivity.clearMap()
    }

    fun clearWaypoints(view: View?) {
        mapActivity.clearWaypoints()
    }


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true //we provided the menu that needs to be inflated
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.miLogout) {
            Log.i(TAG, "Logout")
            //Logout the user
            auth.signOut()
            LoginManager.getInstance().logOut()
            val logoutIntent = Intent(this, LoginActivity::class.java)

            logoutIntent.flags =
                Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK //Clear the backstack
            startActivity(logoutIntent)
        }
        return super.onOptionsItemSelected(item)
    }

    private fun handleAndroidPermissions() {
        permissionsRequestor = PermissionsRequestor(this)
        permissionsRequestor.request(object : PermissionsRequestor.ResultListener {
            override fun permissionsGranted() {
                loadMapScene()
            }

            override fun permissionsDenied() {
                Log.e(TAG, "Permissions denied by user.")
            }
        })
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        permissionsRequestor.onRequestPermissionsResult(requestCode, grantResults)
    }

    private fun loadMapScene() {

        mapView.mapScene.loadScene(MapScheme.NORMAL_DAY, object : MapScene.LoadSceneCallback {
            override fun onLoadScene(p0: MapError?) {
                if (p0 == null) {

                    mapActivity = MapActivity(this@MainActivity, mapView, supportFragmentManager)

                    mapView.camera.lookAt(
                        GeoCoordinates(53.57407651646072, -1.525012498490556),
                        100000.0
                    )
                } else {
                    Log.d("TAG", "onLoadScene failed: $p0")
                }
            }
        })

    }

    fun location() {

        var locationManager: LocationManager = getSystemService(LOCATION_SERVICE) as LocationManager

        hasGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        hasNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)

        if (hasGps || hasNetwork) {
            if (hasGps) {
                Log.d(TAG, "hasGPS")
                if (ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_FINE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    //return

                    handleAndroidPermissions()
                }
                locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    1000,
                    0f,
                    object :
                        LocationListener {
                        override fun onLocationChanged(p0: Location?) {
                            if (p0 != null) {
                                locationNetwork = p0
                            }
                        }

                        override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
                        }

                        override fun onProviderEnabled(p0: String?) {
                        }

                        override fun onProviderDisabled(p0: String?) {
                        }
                    })

                val localGpsLocation =
                    locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                if (localGpsLocation != null) {
                    locationGps = localGpsLocation
                }
            }


            ///////////////////////////////////////////////////////////////////////////

            if (hasNetwork) {
                Log.d(TAG, "hasGPS")
                locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,
                    1000,
                    0f,
                    object :
                        LocationListener {
                        override fun onLocationChanged(p0: Location?) {
                            if (p0 != null) {
                                locationNetwork = p0
                            }
                        }

                        override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
                        }

                        override fun onProviderEnabled(p0: String?) {
                        }

                        override fun onProviderDisabled(p0: String?) {
                        }
                    })

                val localGpsLocation =
                    locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                if (localGpsLocation != null) {
                    locationGps = localGpsLocation
                }

                val localNetworkLocation =
                    locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
                if (localNetworkLocation != null) {
                    locationNetwork = localNetworkLocation
                }

                if (locationGps != null && locationNetwork != null) {
                    if (locationGps!!.accuracy!! > locationNetwork!!.accuracy!!) { //The lower number is the accurate location
                        Log.d(TAG, "Network Latitude : ${locationNetwork!!.latitude}")
                        Log.d(TAG, "Network Longitude : ${locationNetwork!!.longitude}")

                        latitude_txt.text = "Latitude : ${locationNetwork!!.latitude} - Network"
                        longitude_txt.text = "Longitude : ${locationNetwork!!.longitude} - Network"

                        latitude_txt.text = "Latitude : ${locationGps!!.latitude} - Gps"
                        longitude_txt.text = "Longitude : ${locationGps!!.longitude} - Gps"


                    } else {
                        Log.d(TAG, "Gps Latitude : ${locationGps!!.latitude}")
                        Log.d(TAG, "Gps Longitude : ${locationGps!!.longitude}")

                        latitude_txt.text = "Latitude : ${locationGps!!.latitude} - Gps"
                        longitude_txt.text = "Longitude : ${locationGps!!.longitude} - Gps"
                    }
                }
            }


//            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
//                this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)
//            ) {
//                locationManager.requestLocationUpdates(
//                    LocationManager.GPS_PROVIDER,
//                    LOCATION_UPDATE_INTERVAL_IN_MS,
//                    1,
//                    this
//                );
//            } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
//                locationManager.requestLocationUpdates(
//                    LocationManager.NETWORK_PROVIDER,
//                    LOCATION_UPDATE_INTERVAL_IN_MS,
//                    1,
//                    this
//                );
//            } else {
//                Log.d(TAG, "Positioning not possible.");
//                // ...
//            }

        }

    }

}

NewPOIDialog

The view was initially called as below, I changed it as I was receiving a StackOverFlowError: var view = layoutInflater.inflate(R.layout.activity_new_poi_dialog,null)

    class NewPOIDialog : DialogFragment() {



    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        var view = LayoutInflater.from(context).inflate(R.layout.activity_new_poi_dialog, null)
        var dialog = AlertDialog.Builder(requireContext())
            .setMessage("TITLE")
            .setView(view)
            .setPositiveButton("ok") { _, _ -> }
            .setNegativeButton("Cancel") { _, _ -> }
            .create()


        //THIS LINE WORKS FINE
        var coordinatesvalue = view.findViewById<TextView>(R.id.coordinates_value)
        coordinatesvalue.text =
            "${arguments?.getDouble("latitude")}\n, ${arguments?.getDouble("longitude")}"

        //THIS CAUSES A NULL POINTER EXCEPTION
        coordinates_value.text = "TEST"


        return dialog
    }
}

The exception I am getting:

    D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.robin.socialparking, PID: 19187
    java.lang.NullPointerException: coordinates_value must not be null
        at com.robin.socialparking.dialog.NewPOIDialog.onCreateDialog(NewPOIDialog.kt:54)
        at androidx.fragment.app.DialogFragment.onGetLayoutInflater(DialogFragment.java:380)
        at androidx.fragment.app.Fragment.performGetLayoutInflater(Fragment.java:1412)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7050)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
I/Process: Sending signal. PID: 19187 SIG: 9
0

There are 0 best solutions below