I'm progressing through the android sdk, but no matter what I do, the mentioned problem has not been fixed.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I also have the necessary permissions as seen above
class MainActivity : AppCompatActivity() {
private lateinit var fusedLocationClient : FusedLocationProviderClient
override fun onCreate(savedInstanceState : Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
if (checkSelfPermission(permission.ACCESS_FINE_LOCATION) == PERMISSION_GRANTED) {
fusedLocationClient.lastLocation.addOnSuccessListener {
Toast.makeText( this , it.latitude.toString() , Toast.LENGTH_SHORT).show()
}
}else {
requestPermissions(arrayOf(permission.ACCESS_FINE_LOCATION), 1)
}
}
}
}
The Google library is already attached to the above project. Below is the logcat log
2021-07-20 20:55:52.192 10383-10383/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 10383
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.myapplication.MainActivity.onCreate$lambda-1$lambda-0(MainActivity.kt:30)
at com.example.myapplication.MainActivity.lambda$3KV2L66GHKvgVt1VJ2iK5fjpKsI(Unknown Source:0)
at com.example.myapplication.-$$Lambda$MainActivity$3KV2L66GHKvgVt1VJ2iK5fjpKsI.onSuccess(Unknown Source:4)
at com.google.android.gms.tasks.zzn.run(com.google.android.gms:play-services-tasks@@17.2.0:4)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
As you can see the app crashes constantly for some reason.