0

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.

Kirion
  • 49
  • 11

1 Answers1

0

The documentation states here that lastLocation may be null. If you call a function on a null object, it will throw NullPointerException. That's what's happening when you call lastLocation.addOnSuccessListener.

You can use a null-safe call to avoid calling the function if lastLocation is null: lastLocation?.addOnSuccessListener...

Usually in Kotlin, the compiler will prevent you from calling functions on objects that might be null, but if you are working with a Java API that doesn't have nullability annotations, then you have to pay attention to the documentation of the functions you are calling to know whether you are working with nullable values.

More generalized information about what null exceptions are is explained in this question. It's based on Java, but the concepts carry over to Kotlin if you are calling functions that are defined in Java.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • So how can I get rid of a null pointer exception error ? So how can I determine the device's location or What should I do in the face of this error? – Kirion Jul 20 '21 at 18:59
  • If you just want to ignore the location is there is none available like your code already does since it has no failure listener, then you can use a null-safe call like I suggested in my answer. If your app needs a location to continue, you should register for location updates so you can wait for it to be available and respond to the first location received. That is explained in the documentation. I can't recommend any further than that because I haven't used this API in several years. – Tenfour04 Jul 20 '21 at 19:11
  • I did what you said, but nothing changed, the application still crashes, but thank you for your information. – Kirion Jul 20 '21 at 19:17
  • It is impossible to get a NullPointerException when you are making a null-safe call. You might have some other error happening now. – Tenfour04 Jul 20 '21 at 19:20