Reputation: 165
I have a kotlin.KotlinNullPointerException
at line:
val locationmanager=context!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
When I rotate my screen. This line is in function in:
class MyMapFragment: Fragment(),OnMapReadyCallback
Upvotes: 0
Views: 176
Reputation: 9434
The activity is destroyed and re-created when you rotate the phone. This means while the activity is being re-created the context will be null, and you must be trying to access it at some point during this.
I'm not sure where you have the line of code you posted, but if you want to guarantee a non-null context you should wait till the activity is created.
var locationmanager: LocationManager? = null
override fun onActivityCreated(savedInstanceState: Bundle?) {
val context = context ?: return // this line gets a non-null context and is safer than !!
locationmanager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
...
In general, when accessing things that are nullable in Kotlin, it is much preferred to use ?
instead of !!
to avoid any null pointer exceptions
Upvotes: 1
Reputation: 782
Fragment can access context only after onAttach
lifecycle method called, because it get attached to it's host activity in this lifecycle method. So, to avoid NPE you need
in fragment
lateinit var locationmanager: LocationManager
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
locationmanager = context!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return inflater.inflate(R.layout.your_fragment_layout, container, false)
}
Upvotes: 1