Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java.lang.RuntimeException: Unable to destroy activity ... java.lang.NullPointerException #761

Closed
jakobleck opened this issue Sep 15, 2022 · 8 comments
Labels

Comments

@jakobleck
Copy link

Description
App crashed on startup with the following message:

Launching lib/main.dart on moto g 10 in debug mode...
Running Gradle task 'assembleDebug'...
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
✓  Built build/app/outputs/flutter-apk/app-debug.apk.
Installing build/app/outputs/flutter-apk/app.apk...
W/FlutterActivityAndFragmentDelegate(21887): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
D/FlutterLocationService(21887): Creating service.
D/FlutterLocationService(21887): Binding to location service.
E/AndroidRuntime(21887): FATAL EXCEPTION: main
E/AndroidRuntime(21887): Process: insert.app.identifier, PID: 21887
E/AndroidRuntime(21887): java.lang.RuntimeException: Unable to destroy activity {insert.app.identifier/insert.app.identifier.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(21887): 	at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5209)
E/AndroidRuntime(21887): 	at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:5241)
E/AndroidRuntime(21887): 	at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5536)
E/AndroidRuntime(21887): 	at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5466)
E/AndroidRuntime(21887): 	at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
E/AndroidRuntime(21887): 	at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
E/AndroidRuntime(21887): 	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
E/AndroidRuntime(21887): 	at android.app.ClientTransactionHandler.executeTransaction(ClientTransactionHandler.java:58)
E/AndroidRuntime(21887): 	at android.app.ActivityThread.handleRelaunchActivityLocally(ActivityThread.java:5519)
E/AndroidRuntime(21887): 	at android.app.ActivityThread.access$3400(ActivityThread.java:251)
E/AndroidRuntime(21887): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2141)
E/AndroidRuntime(21887): 	at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(21887): 	at android.os.Looper.loop(Looper.java:250)
E/AndroidRuntime(21887): 	at android.app.ActivityThread.main(ActivityThread.java:7806)
E/AndroidRuntime(21887): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(21887): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/AndroidRuntime(21887): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
E/AndroidRuntime(21887): 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(21887): 	at com.lyokone.location.LocationPlugin.dispose(LocationPlugin.java:117)
E/AndroidRuntime(21887): 	at com.lyokone.location.LocationPlugin.detachActivity(LocationPlugin.java:56)
E/AndroidRuntime(21887): 	at com.lyokone.location.LocationPlugin.onDetachedFromActivityForConfigChanges(LocationPlugin.java:74)
E/AndroidRuntime(21887): 	at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.detachFromActivityForConfigChanges(FlutterEngineConnectionRegistry.java:365)
E/AndroidRuntime(21887): 	at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onDetach(FlutterActivityAndFragmentDelegate.java:679)
E/AndroidRuntime(21887): 	at io.flutter.embedding.android.FlutterActivity.onDestroy(FlutterActivity.java:715)
E/AndroidRuntime(21887): 	at android.app.Activity.performDestroy(Activity.java:8355)
E/AndroidRuntime(21887): 	at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1344)
E/AndroidRuntime(21887): 	at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5194)
E/AndroidRuntime(21887): 	... 16 more
Error connecting to the service protocol: failed to connect to http://127.0.0.1:62457/4SzQLfPwU-M=/

Steps To Reproduce
Unclear. In several attempts at starting the app anew there was no problem.

Tested on:

  • Android 11, API Level 30, real device
  • Flutter Version 3.0.5
  • location: 4.4.0

Seems to be similar or identical to #674

@jakobleck jakobleck added the bug label Sep 15, 2022
@xunreal75
Copy link

Hi your problem seems not location package

Your issue seems following-
A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.-

Please check this.

@jakobleck
Copy link
Author

jakobleck commented Sep 15, 2022

@xunreal75 Do you have any indication that this deprecation warning is related to the crash? I do not think it is. This warning shows up all the time when the app starts with no problem, as in

...
✓  Built build/app/outputs/flutter-apk/app-debug.apk.
Installing build/app/outputs/flutter-apk/app.apk...
W/FlutterActivityAndFragmentDelegate( 4030): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
D/FlutterLocationService( 4030): Creating service.
D/FlutterLocationService( 4030): Binding to location service.
Debug service listening on ws://127.0.0.1:61607/n_YZVipw8Cw=/ws
Syncing files to device moto g 10...
...

What crashes the app clearly is a NullPointerException, with a stack trace pointing to the location package.

(Unless there is some weird interaction between the splash screen and the location package. On https://docs.flutter.dev/development/platform-integration/android/splash-screen-migration it says that a deprecated splash screen can cause a crash. Still, the stack trace to the location package would seem curious if the splash screen was the cause...)

@xunreal75
Copy link

Sorry

i Was on the wrong path

The package seem orphahned at the moment.

because the permissions state from locate is not clean when in use and always, I'm using package:permission_handler and following class.

`import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:f_logs/model/flog/flog.dart';
import 'package:flutter_platform_alert/flutter_platform_alert.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:permission_handler/permission_handler.dart';

import '../generated/l10n.dart';

enum LocationPermissionStatus {
unknown,
notDetermined,
denied,
whenInUse,
always,
locationNotEnabled
}

class LocationPermissions {
late LocationPermissionStatus permissionStatus =
LocationPermissionStatus.notDetermined;

LocationPermissions(this.permissionStatus);
}

class LocationPermissionDialog {
Future getLocationPermissions() async {
//get android version, on V11 you need 'always' permissions to use location, when app is not in Foreground
double? platformVersion;
if (Platform.isAndroid) {
var androidDeviceInfo = await DeviceInfoPlugin().androidInfo;
platformVersion = double.tryParse(androidDeviceInfo.version.release!);
}
var isAndroidPlatformGreater09BuildQ =
Platform.isAndroid && platformVersion != null && platformVersion >= 10;

var permissionWithService = Permission.location;
var locationPermission = await permissionWithService.status;

if (locationPermission == PermissionStatus.denied) {
  var prominentDisclosureResult =
      await FlutterPlatformAlert.showCustomAlert(
          windowTitle: Localize.current.requestLocationPermissionTitle,
          text: isAndroidPlatformGreater09BuildQ
              ? Localize.current
                  .prominentdisclosuretrackingprealertandroidFromAndroid_V11
              : Localize.current
                  .prominentdisclosuretrackingprealertandroidToAndroid_V10x,
          iconStyle: IconStyle.information,
          positiveButtonTitle: Localize.current.change,
          negativeButtonTitle: Localize.current.deny);
  if (prominentDisclosureResult == CustomButton.negativeButton) {
    //user denies request
    return LocationPermissionStatus.denied;
  } else {
    //Change permissions
    var reqpermStatus = await permissionWithService.request();
    if (reqpermStatus == PermissionStatus.granted) {
      var isAlways = await Permission.locationAlways.status;
      if (isAlways == PermissionStatus.granted) {
        return LocationPermissionStatus.always;
      }
      var whenInUse = await Permission.location.status;
      if (whenInUse == PermissionStatus.granted) {
        if (isAndroidPlatformGreater09BuildQ) {
          await requestAlwaysOnAndroid();
        }
        return getPermissionsStatus();
      }
    }
  }
}

//LocationPermissions are not denied - find out if always is granted
var isAlways = await Permission.locationAlways.status;
var whenInUse = await Permission.locationWhenInUse.status;

//for app background we need always on Android build_Q from V10 //not when in use
if (whenInUse == PermissionStatus.granted &&
    isAlways == PermissionStatus.denied &&
    isAndroidPlatformGreater09BuildQ) {
  await requestAlwaysOnAndroid();
  return await getPermissionsStatus();
}

//other cases no Android > V10(build_Q)
//always includes when in use
if (isAlways == PermissionStatus.granted) {
  return LocationPermissionStatus.always;
}

if (whenInUse == PermissionStatus.granted) {
  return LocationPermissionStatus.whenInUse;
}

if (locationPermission == PermissionStatus.permanentlyDenied) {
  requestAndOpenAppSettings();
}

//unkown state
return LocationPermissionStatus.unknown;
}

Future requestAlwaysOnAndroid() async {
var prominentDisclosureResult = await FlutterPlatformAlert.showCustomAlert(
windowTitle: Localize.current.onlyWhenInUseEnabled,
text: Localize.current.enableAlwaysLocationInfotext,
iconStyle: IconStyle.information,
positiveButtonTitle: Localize.current.changetoalways,
negativeButtonTitle: Localize.current.leavewheninuse);
if (prominentDisclosureResult == CustomButton.negativeButton) {
return getPermissionsStatus();
} else {
var permissionWithService = Permission.locationAlways;
var res = await permissionWithService.request();
if (res == PermissionStatus.granted) {
return LocationPermissionStatus.always;
}
if (res == PermissionStatus.permanentlyDenied) {
FLog.warning(
text: 'requestAlwaysOnAndroid permissions permanentlyDenied');

    var permanentDeniedResult = await FlutterPlatformAlert.showCustomAlert(
        windowTitle: Localize.current.alwaysPermantlyDenied,
        text: Localize.current.tryOpenAppSettings,
        iconStyle: IconStyle.information,
        positiveButtonTitle: Localize.current.openOperatingSystemSettings,
        negativeButtonTitle: Localize.current.leavewheninuse);
    if (permanentDeniedResult == CustomButton.positiveButton) {
      var res = await openAppSettings();
      if (res == false) {
        Fluttertoast.showToast(
            msg: Localize.current.couldNotOpenAppSettings);
        FLog.warning(
            text:
                'App settings could not opened while always location permissions are permanentlyDenied');
      }
    }
  }
}
return getPermissionsStatus();

}

Future getPermissionsStatus() async {
var isAlways = await Permission.locationAlways.status;
if (isAlways == PermissionStatus.granted) {
return LocationPermissionStatus.always;
}
var whenInUse = await Permission.locationWhenInUse.status;
if (whenInUse == PermissionStatus.granted) {
return LocationPermissionStatus.whenInUse;
}
return LocationPermissionStatus.denied;
}

Future requestAndOpenAppSettings() async {
var permanentDeniedResult = await FlutterPlatformAlert.showCustomAlert(
windowTitle: Localize.current.alwaysPermantlyDenied,
text: Localize.current.tryOpenAppSettings,
iconStyle: IconStyle.information,
positiveButtonTitle: Localize.current.yes,
negativeButtonTitle: Localize.current.no);
if (permanentDeniedResult == CustomButton.positiveButton) {
var res = await openAppSettings();
if (res == false) {
Fluttertoast.showToast(msg: Localize.current.couldNotOpenAppSettings);
FLog.warning(
text:
'Appsettings could not opened while always location permissions are permanentlyDenied');
return false;
}
return true;
}
return false;
}
}
`

and in my locationprovider following code snippet

`
if (_isTracking) {
_stopTracking();
} else {
var grantedPermissions =
await LocationPermissionDialog().getLocationPermissions();
//firstTime it can only request while using app
//check for 2nd time to request always in use

  if (Platform.isAndroid &&
      await DeviceId.isAndroidPlatformGreater09BuildQ() &&
      grantedPermissions == LocationPermissionStatus.always) {
    _background = true;
  }
  if (Platform.isAndroid &&
      !await DeviceId.isAndroidPlatformGreater09BuildQ()) {
    _background = true;
  }

  if (Platform.isIOS) {
    _background = true; //not working when not set
  }

  if (grantedPermissions == LocationPermissionStatus.whenInUse ||
      grantedPermissions == LocationPermissionStatus.always) {
    _startTracking();
  } else {
....}

}
`

@matejhocevar
Copy link

Hey!

I got similar problem like you described. I managed to solve it putting additional permissions to AndroidManifest.xml file:

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

More about how to properly setup Android platform is available in the docs: https://docs.page/Lyokone/flutterlocation/installation/android#background-location

@jakobleck
Copy link
Author

Hey @matejhocevar,
by a similar problem do you mean an identical error message? Was it reproducible in your case and can you provide info how to? I personally would be hesitant to just add those permissions without knowing how to reproduce the bug and thus without knowing whether this is fixing it in the application I'm working on.

@anirudhsharma392
Copy link

Any update on this? am still getting this error on prod.

@jakobleck
Copy link
Author

What I did was indeed to fix the deprecation warning of the splash screen as suggested by @xunreal75 . Cf. the instructions on https://docs.flutter.dev/development/platform-integration/android/splash-screen-migration. I haven't seen the problem since. However, since there was no definite way of reproduction for the crash, I am not sure that this solved the original issue.

@bartekpacia
Copy link
Collaborator

Please use the latest v5 version. This problem should be fixed in there. This problem also looks similar to #674.

https://pub.dev/packages/location

Repository owner locked and limited conversation to collaborators Aug 4, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

5 participants