flutterlocation icon indicating copy to clipboard operation
flutterlocation copied to clipboard

java.lang.NullPointerException: Attempt to invoke virtual method 'io.flutter.plugin.common.PluginRegistry$RequestPermissionsResultListener com.lyokone.location.FlutterLocationService.getServiceRequestPermissionsResultListener()' on a null object reference

Open HAFIZkhan-source opened this issue 1 year ago • 12 comments

Describe the bug App crashing on very first app open

Tested on:

  • Android OS 13, Samsung Galaxy M13

Other plugins:

  • List of others Flutter plugins that could interfere

Additional logs D/FlutterGeolocator(20666): Attaching Geolocator to activity D/FlutterGeolocator(20666): Detaching Geolocator from activity E/AndroidRuntime(20666): FATAL EXCEPTION: main E/AndroidRuntime(20666): Process: com.skieats.owner, PID: 20666 E/AndroidRuntime(20666): java.lang.RuntimeException: Unable to destroy activity {com.skieats.owner/com.skieats.owner.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'io.flutter.plugin.common.PluginRegistry$RequestPermissionsResultListener com.lyokone.location.FlutterLocationService.getServiceRequestPermissionsResultListener()' on a null object reference E/AndroidRuntime(20666): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:6080) E/AndroidRuntime(20666): at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:6113) E/AndroidRuntime(20666): at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:6460) E/AndroidRuntime(20666): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:6341) E/AndroidRuntime(20666): at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:71) E/AndroidRuntime(20666): at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45) E/AndroidRuntime(20666): at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) E/AndroidRuntime(20666): at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) E/AndroidRuntime(20666): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2574) E/AndroidRuntime(20666): at android.os.Handler.dispatchMessage(Handler.java:106) E/AndroidRuntime(20666): at android.os.Looper.loopOnce(Looper.java:226) E/AndroidRuntime(20666): at android.os.Looper.loop(Looper.java:313) E/AndroidRuntime(20666): at android.app.ActivityThread.main(ActivityThread.java:8757) E/AndroidRuntime(20666): at java.lang.reflect.Method.invoke(Native Method) E/AndroidRuntime(20666): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) E/AndroidRuntime(20666): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067) E/AndroidRuntime(20666): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'io.flutter.plugin.common.PluginRegistry$RequestPermissionsResultListener com.lyokone.location.FlutterLocationService.getServiceRequestPermissionsResultListener()' on a null object reference E/AndroidRuntime(20666): at com.lyokone.location.LocationPlugin.dispose(LocationPlugin.java:117) E/AndroidRuntime(20666): at com.lyokone.location.LocationPlugin.detachActivity(LocationPlugin.java:56)

HAFIZkhan-source avatar Jul 25 '23 09:07 HAFIZkhan-source

May I ask how to solve it

gyy19931212 avatar Jul 31 '23 07:07 gyy19931212

What version of the plugin are you using?

Please attach a Minimal, Reproducible Example.

bartekpacia avatar Aug 04 '23 12:08 bartekpacia

I'm facing a similar issue with the current version (5.0.2+1).

PlatformException(error, Attempt to write to field 'io.flutter.plugin.common.EventChannel$EventSink com.lyokone.location.FlutterLocation.events' on a null object reference in method 'void com.lyokone.location.StreamHandlerImpl.onListen(java.lang.Object, io.flutter.plugin.common.EventChannel$EventSink)', null, null)

The error only occurs when using location from a separate isolate (in my case I try to start a location stream from a separate foreground service using flutter_foreground_task). When using it from the main isolate everything is fine.

LorenzSchueler avatar Aug 08 '23 10:08 LorenzSchueler

@bartekpacia I am using location: ^5.0.1

HAFIZkhan-source avatar Aug 08 '23 10:08 HAFIZkhan-source

Thanks for explaining. Could you attach minimal, reproducible examples?

bartekpacia avatar Aug 08 '23 10:08 bartekpacia

@bartekpacia sure.

pressing the activate button works, pressing activate on other isolate does not work

import 'dart:async';
import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:location/location.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({super.key});

  final location = Location();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FilledButton(
              onPressed: activateLocation,
              child: const Text("activate"),
            ),
            FilledButton(
              onPressed: activateLocationOtherIsolate,
              child: const Text("activate on other isolate"),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> activateLocation() async {
    await location.requestPermission();
    await location.enableBackgroundMode();
    final locationSubscription = location.onLocationChanged.listen(print);
    Timer(const Duration(minutes: 5), () {
      locationSubscription.cancel();
    });
  }

  Future<void> activateLocationOtherIsolate() async {
    // request permissions on main isolate
    await location.requestPermission();

    FlutterForegroundTask.init(
      androidNotificationOptions: AndroidNotificationOptions(
        channelId: 'notification_channel_id',
        channelName: 'Foreground Notification',
      ),
      iosNotificationOptions: const IOSNotificationOptions(),
      foregroundTaskOptions: ForegroundTaskOptions(
        interval: const Duration(minutes: 1).inMilliseconds,
      ),
    );

    await FlutterForegroundTask.startService(
      notificationTitle: "title",
      notificationText: "text",
      callback: startCallback,
    );
  }
}

@pragma('vm:entry-point')
void startCallback() {
  FlutterForegroundTask.setTaskHandler(MyTaskHandler());
}

class MyTaskHandler extends TaskHandler {
  @override
  Future<void> onStart(DateTime timestamp, SendPort? sendPort) async {}

  @override
  Future<void> onRepeatEvent(DateTime timestamp, SendPort? sendPort) async {
    final location = Location();
    await location.enableBackgroundMode();
    final locationSubscription = location.onLocationChanged.listen(print);
    Timer(const Duration(minutes: 5), () {
      locationSubscription.cancel();
    });
  }

  @override
  Future<void> onDestroy(DateTime timestamp, SendPort? sendPort) async {}
}

add to AndroidManifest.xml:

<service
            android:name="com.pravera.flutter_foreground_task.service.ForegroundService"
            android:stopWithTask="true" />

dependencies:

location: ^5.0.2+1
flutter_foreground_task: ^6.0.0+1

LorenzSchueler avatar Aug 08 '23 13:08 LorenzSchueler

@bartekpacia It seems to be an initialization problem. The FlutterLocation objects in StreamHandlerImpl and MethodCallHandlerImpl are null. I've not yet been able to pinpoint he problem. But as I wrote earlier, this is only the case if you use the package from a different isolate. Although I know that work on develop is currently not planned, I just wanted to mention that with develop this problem does not occur. Any ideas how to fix it?

LorenzSchueler avatar Aug 13 '23 04:08 LorenzSchueler

@Lyokone , I faced this issue on Android API 33. Could you please merge the fix https://github.com/Lyokone/flutterlocation/pull/889 ? According to the code changes it should be ok.

predictron-cloud avatar Oct 07 '23 21:10 predictron-cloud

@bartekpacia @Lyokone any update on this?

Sofstica-Abdul-Bari avatar Nov 14 '23 11:11 Sofstica-Abdul-Bari

Is #889 the fix for this?

Would you be able to use a version of this package from #889 and let me know if it works correctly, fixes this bug, and doesn't crash? Thank you in advanace 🙏🏻

bartekpacia avatar Nov 14 '23 12:11 bartekpacia

Tried running the code from commit hash code location: git: url: https://github.com/Lyokone/flutterlocation.git ref: 9e45657a9837de66851752470415ddcd8961f703 path: packages/location/

The issue still exists. I tried using flutter clean and running pub get again. Also, do let me know if I am doing it in a wrong way!

Sofstica-Abdul-Bari avatar Nov 14 '23 12:11 Sofstica-Abdul-Bari

Thanks for checking. I'll be happy to merge and release a fix but I don't have time to work on this. All contributions are welcome.

bartekpacia avatar Nov 14 '23 12:11 bartekpacia

this issue came up to me as well. I use version 6.0.1

ardeshir-33033 avatar May 06 '24 00:05 ardeshir-33033

Having the issue as well when running it from an isolate using flutter_foreground_task. I tried the mentioned commit but same issue.

flightcom avatar May 06 '24 06:05 flightcom