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

Attempt to invoke interface method 'boolean android.content.SharedPreferences.contains(java.lang.String)' #380

Closed
tahitiangabriel opened this issue Mar 15, 2022 · 58 comments · Fixed by #508

Comments

@tahitiangabriel
Copy link

PlatformException(Exception encountered, read, java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.content.SharedPreferences.contains(java.lang.String)' on a null object reference at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin$b.run(SourceFile:24) 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.os.HandlerThread.run(HandlerThread.java:67) , null)

This issue was supposed to be fixed with #332 , but is still hapenning in 5.0.2

Only Android devices are affected by this issue.

@dustincatap
Copy link

I encountered a similar error. What I did was disabling backup in my AndroidManifest.xml:

        <application
        ...
            android:allowBackup="false"
            android:fullBackupContent="false">

@AlgoritmoDelCambio
Copy link

Hi everyone! I've been having this issue as well. As @tahitiangabriel say, it's mentioned in #332 but also in #53. This last one is the most similar to my error, as the people updating the app are getting this error that leaves the APP totally broken.

It seems that 5.0.2 is not resolving these issues as it appears that there are people reopening and commenting on these issues. In my case, not everybody gets the error, it's like 50/50, don't know if it may be linked to SO versions, iOS, Android or what...

I will try to add a button to "Clear cache" or automatically deleteKeys on error to see if it works but definitely is not the best option... Let's see if we find a solution soon 😢

@dustincatap Could you explain your solution and why should work? Don't know why backup could be causing trouble in here. Thanks!

@kzjn10
Copy link

kzjn10 commented May 7, 2022

E/FlutterSecureStoragePl( 6611): EncryptedSharedPreferences initialization failed
E/FlutterSecureStoragePl( 6611): com.google.crypto.tink.shaded.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
E/FlutterSecureStoragePl( 6611): 	at com.google.crypto.tink.shaded.protobuf.y.K(GeneratedMessageLite.java:10)
E/FlutterSecureStoragePl( 6611): 	at com.google.crypto.tink.shaded.protobuf.y.H(GeneratedMessageLite.java:2)
E/FlutterSecureStoragePl( 6611): 	at p4.c0.X(Keyset.java:1)
E/FlutterSecureStoragePl( 6611): 	at m4.d.a(SharedPrefKeysetReader.java:1)
E/FlutterSecureStoragePl( 6611): 	at i4.b.a(CleartextKeysetHandle.java:1)
E/FlutterSecureStoragePl( 6611): 	at m4.a$b.e(AndroidKeysetManager.java:4)
E/FlutterSecureStoragePl( 6611): 	at m4.a$b.f(AndroidKeysetManager.java:1)
E/FlutterSecureStoragePl( 6611): 	at m4.a$b.d(AndroidKeysetManager.java:3)
E/FlutterSecureStoragePl( 6611): 	at z0.a.b(EncryptedSharedPreferences.java:8)
E/FlutterSecureStoragePl( 6611): 	at z0.a.a(EncryptedSharedPreferences.java:1)
E/FlutterSecureStoragePl( 6611): 	at g7.d.s(FlutterSecureStoragePlugin.java:7)
E/FlutterSecureStoragePl( 6611): 	at g7.d.p(FlutterSecureStoragePlugin.java:8)
E/FlutterSecureStoragePl( 6611): 	at g7.d.b(FlutterSecureStoragePlugin.java:1)
E/FlutterSecureStoragePl( 6611): 	at g7.d$b.run(FlutterSecureStoragePlugin.java:23)
E/FlutterSecureStoragePl( 6611): 	at android.os.Handler.handleCallback(Handler.java:938)
E/FlutterSecureStoragePl( 6611): 	at android.os.Handler.dispatchMessage(Handler.java:99)
E/FlutterSecureStoragePl( 6611): 	at android.os.Looper.loopOnce(Looper.java:201)
E/FlutterSecureStoragePl( 6611): 	at android.os.Looper.loop(Looper.java:288)
E/FlutterSecureStoragePl( 6611): 	at android.os.HandlerThread.run(HandlerThread.java:67)
E/flutter ( 6611): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(Exception encountered, read, java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.content.SharedPreferences.contains(java.lang.String)' on a null object reference
E/flutter ( 6611): 	at g7.d$b.run(FlutterSecureStoragePlugin.java:24)
E/flutter ( 6611): 	at android.os.Handler.handleCallback(Handler.java:938)
E/flutter ( 6611): 	at android.os.Handler.dispatchMessage(Handler.java:99)
E/flutter ( 6611): 	at android.os.Looper.loopOnce(Looper.java:201)
E/flutter ( 6611): 	at android.os.Looper.loop(Looper.java:288)
E/flutter ( 6611): 	at android.os.HandlerThread.run(HandlerThread.java:67)
E/flutter ( 6611): , null)
E/flutter ( 6611): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607)
E/flutter ( 6611): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:177)
E/flutter ( 6611): <asynchronous suspension>
E/flutter ( 6611): #2      main (package:ddv_loyalty/main.dart:37)
E/flutter ( 6611): <asynchronous suspension>
E/flutter ( 6611): 

version 5.0.2 still error when build app release mode

@AlgoritmoDelCambio
Copy link

You are getting

E/FlutterSecureStoragePl( 6611): EncryptedSharedPreferences initialization failed

Initialization failed does not seem to be the same case that we are exposing here. Are you sure that you've reloaded properly your app after installing the library?

@kzjn10
Copy link

kzjn10 commented May 8, 2022

i happen when i build to physical device in Release mode

@Yotam124
Copy link

i happen when i build to physical device in Release mode

+1

@JapneetSingh-28
Copy link

I am also facing similar issue, issue: flutter PlatformException(Exception encountered, write, java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference

@Kang-Kim1
Copy link

Any further update on this issue?

@lucianosb
Copy link

I had this same error appear to me in a very specific scenario. I hope this report will bring some light in the issue.

My app was working fine during development until I tried to uninstall and install it again to be sure that everything was going to work properly. Then the error occurred. I was using the --release flag on build.

It seems to only happen on Android 11 (tried on two Xiaomi Mi 10T and on Samsung A31) on my code. I tried to reproduce this scenario on other Android versions (6, 9 and 12) but everything is running smoothly, even after reinstalling the app.

Firebase Crashlytics reports the error happening when I call .containsKey or .read when trying to read previously stored user data to determine whether to show Login Page or the main route.

@acoutts
Copy link

acoutts commented Aug 23, 2022

@juliansteenbakker can someone please take a closer look at this? This is affecting a ton of users and really hard to debug.

@acoutts
Copy link

acoutts commented Aug 24, 2022

I downgraded to 4.2.1 and disabling encryptedSharedPreferences fixed this for me.

@curogom-ksd
Copy link

curogom-ksd commented Sep 5, 2022

I have the same problem. Occurs continuously in release mode.
It's a complicated environment to debug, so it's hard to deal with... 😢

@curogom-ksd
Copy link

curogom-ksd commented Sep 5, 2022

@lucianosb

I solved this problem.

If your versions upper 5.0.0 & it was build to release mode, try to this code.

storage.read(key: 'key')
to
storage.read(key: 'key', aOption: AndroidOptions(encryptedSharedPreferences: true,)

@henry2man
Copy link

I've tried #380 (comment) and also an update to 6.0.0 but the main issue is still pressent.

@mogol For now this is blocker for our app :(

@TheCarpetMerchant
Copy link

@mogol Same thing. allowBackup is false, fullBackupContent is false, aOption: AndroidOptions(encryptedSharedPreferences: true,) is on every call.
The exception is happening on devices using Android 10 and above.
I'm mostly getting it when accessing EncryptedSharedPreferences during background work (using workmanager).

This issue is completely preventing users from using the app. Could share some thoughts on what the issue could be ? It clearly has to do with getting the app's context.

@TheCarpetMerchant
Copy link

One of my users unblocked himself by Force stopping the app then clearing data & cache. Didn't work for others but I have no way of knowing if they proceeded correctly or if this is really what unlocked that one user.

So it seems forcing a deletion solves the problem. Any way of doing this reliably @mogol ?

@mogol
Copy link
Owner

mogol commented Sep 12, 2022

I will check once more. But my previous attempts to reproduce and fix reliably were not very successful. So no promises 🤷‍♂️

@TheCarpetMerchant
Copy link

I have put resetOnError to true on all accesses, and the error still occurs.

@TheCarpetMerchant
Copy link

Alright, seem I'm getting contacted at least once a day by a user with this issue, I'm going to have to drop this package.

@mogol Please put a warning for the use of EncryptedSharedPreferences with this package. It is not stable and such a warning would have saved me a whole lot of trouble.
Best of luck man.

@hungnm1908
Copy link

I solved this problem with

static AndroidOptions _getAndroidOptions() => const AndroidOptions(
keyCipherAlgorithm: KeyCipherAlgorithm.RSA_ECB_OAEPwithSHA_256andMGF1Padding,
storageCipherAlgorithm: StorageCipherAlgorithm.AES_GCM_NoPadding,
);

@kamilzajacdeviniti
Copy link

kamilzajacdeviniti commented Sep 26, 2022

Any update in that topic? We are having few crashes on the daily basis. The error message looks similar:

java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference

We are using encryptedSharedPreferences option enabled.

@indraseptama
Copy link

Any update?

@kamilzajacdeviniti
Copy link

Our crash analysis tool shows us, that this situation mostly occurs on Android 6, especially on Huawei P8 Lite device. Maybe that will help?

@indraseptama
Copy link

Hello, any update? I'm still getting this error.

How to reproduce:

  1. Install apps from play store.
  2. Uninstall apps
  3. Install apps from play store again.
  4. Open apps, and when apps call the "read" method will catch this error.

@techouse
Copy link
Contributor

techouse commented Oct 6, 2022

@kamilzajacdeviniti
Copy link

kamilzajacdeviniti commented Oct 6, 2022

We are having this issue on the Android platform only - it's not related to iOS. As far as I know, the Android removes the data from the encrypted preferences once app is uninstalled.

@techouse
Copy link
Contributor

techouse commented Oct 6, 2022

We are having this issue on the Android platform only - it's not related to iOS. As far as I know, the Android removes the data from the encrypted preferences once app is uninstalled.

Not sure. What if the manifest has android:allowBackup="true"?

@jeff-odopass
Copy link

I'm wondering, do using both FlutterSecureStorage and SharedPreferences in the same app can cause this kind of errors ?

@jfahrenkrug
Copy link

@jeff-odopass That's a great question. We had the same combination in our app... Do you have some additional info as to why you suspect that that combination could cause problems?

@tattivitorino
Copy link

same here, for write, read and delete
one of my crashlytics logs in production

Non-fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: PlatformException(Exception encountered, write, java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference
	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin.write(FlutterSecureStoragePlugin.java:197)
	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin.access$300(FlutterSecureStoragePlugin.java:37)
	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin$MethodRunner.run(FlutterSecureStoragePlugin.java:289)
	at android.os.Handler.handleCallback(Handler.java:938)
	at android.os.Handler.dispatchMessage(Handler.java:99)
	at android.os.Looper.loopOnce(Looper.java:223)
	at android.os.Looper.loop(Looper.java:317)
	at android.os.HandlerThread.run(HandlerThread.java:67)
, null). Error thrown [PLATFORM-EXCEPTION] - STORAGE-SERVICE:WRITE.

Flutter 2.10.5
Storage 5.0.2

@acoutts
Copy link

acoutts commented Nov 28, 2022

The root issue is for some reason the shared preferences instance fails to create but the error is swallowed and ignored. We need to forward the error to dart so we can catch it and see what’s happening.
I’m still not sure how to reproduce the issue but if someone creates a PR to add more logging like that maybe we can finally get to the bottom of it.

@starlight173
Copy link

starlight173 commented Dec 19, 2022

I solved this problem with

static AndroidOptions _getAndroidOptions() => const AndroidOptions( keyCipherAlgorithm: KeyCipherAlgorithm.RSA_ECB_OAEPwithSHA_256andMGF1Padding, storageCipherAlgorithm: StorageCipherAlgorithm.AES_GCM_NoPadding, );

This really works but I don't know how. The interesting thing I have to mention is: this happens somehow randomly on a development device I used to test for year without any issue and then, once day it appears :D. No upgrade OS, nothing. Weird.

UPDATED: I got it again on the same device after a while. Not update anything.

@benjaminhorner
Copy link

Any update on this? I am facing the same thing one Android 13…

@mrohlof-protofy
Copy link

We also experience this behaviour when installing our app from Play Store, uninstall it and then install from Firebase App Tester. App start does not even get to splash screen but stays just white.

@dkobia
Copy link

dkobia commented Dec 22, 2022

This might have something to do with isolates, referenced here and calling DartPluginRegistrant.ensureInitialized(), which will run all Dart plugin registration or this on older versions of Flutter:

if (Platform.isAndroid) SharedPreferencesAndroid.registerWith();
if (Platform.isIOS) SharedPreferencesIOS.registerWith();

@0ttik
Copy link

0ttik commented Dec 26, 2022

Same issue here, the stacktrace is the following:

Plugin version is 6.1.0.

Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: PlatformException(Exception encountered, read, java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.content.SharedPreferences.contains(java.lang.String)' on a null object reference
	at com.it_nomads.fluttersecurestorage.FlutterSecureStorage.containsKey(FlutterSecureStorage.java:55)
	at com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin$MethodRunner.run(FlutterSecureStoragePlugin.java:155)
	at android.os.Handler.handleCallback(Handler.java:955)
	at android.os.Handler.dispatchMessage(Handler.java:102)
	at android.os.Looper.loopOnce(Looper.java:206)
	at android.os.Looper.loop(Looper.java:296)
	at android.os.HandlerThread.run(HandlerThread.java:67)
, null). Error thrown Caught error in a guarded zone..
       at StandardMethodCodec.decodeEnvelope(message_codecs.dart:653)
       at MethodChannel._invokeMethod(platform_channel.dart:296)
       at UserRepository.getUser(user_repository.dart:99)
       at new SplashBloc.<fn>.<fn>(splash_bloc.dart:22)
       at new SplashBloc.<fn>(splash_bloc.dart:18)
       at Bloc.on.<fn>.handleEvent(bloc.dart:226)

@avdept
Copy link

avdept commented Jan 10, 2023

Any updates? Getting this error using flutter oauth2 package.

@akashkamble012
Copy link

Hi there, I am facing the same issues with android 11 devices.
is there any solution to tackle this problem?
the package version is 7.0.1.
flutter version is 3.3.10

@humanolaranja
Copy link

Same issue here.
Just Android, just release mode

@jopmiddelkamp
Copy link

Hello, any update? I'm still getting this error.

How to reproduce:

  1. Install apps from play store.
  2. Uninstall apps
  3. Install apps from play store again.
  4. Open apps, and when apps call the "read" method will catch this error.

I feel like this happened to me too..

flutter: 3.3.10
package: 7.0.1
Android: 12
Model: Galaxy S10

Not sure if this is helpful information: I'm accessing the plugin before the the runApp is executed.

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  DartPluginRegistrant.ensureInitialized();
  SystemChrome.setEnabledSystemUIMode(
    SystemUiMode.manual,
    overlays: [
      SystemUiOverlay.bottom,
      SystemUiOverlay.top,
    ],
  );
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);

  var XxxxRepository = new XxxxRepository();
  
  await Future.wait([
    XxxxRepositry.init(),
  ]);
  
  runApp(App());
}
PlatformException(Exception encountered, read, java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.content.SharedPreferences.contains(java.lang.String)' on a null object reference
	at c4.a.b(Unknown Source:5)
	at c4.e$b.run(Unknown Source:221)
	at android.os.Handler.handleCallback(Handler.java:938)
	at android.os.Handler.dispatchMessage(Handler.java:99)
	at android.os.Looper.loopOnce(Looper.java:226)
	at android.os.Looper.loop(Looper.java:313)
	at android.os.HandlerThread.run(HandlerThread.java:67)
, null). Error thrown null.
       at StandardMethodCodec.decodeEnvelope(message_codecs.dart:653)
       at MethodChannel._invokeMethod(platform_channel.dart:296)
       at XxxxDataProvider.readToken(xxxx_data_provider.dart:13)
       at XxxxRepositoryImpl.init(xxxx_repository_impl.dart:22)
       at Future.wait.<fn>(wait.java)
       at .bootstrap(bootstrap.dart:62)
       at .main(main.dart:80)

@jonasbark
Copy link
Contributor

We encountered the issue every time on a specific Samsung phone.

During the investigation, I found that the Android code has baaaad behavior if it fails to create the encrypted preferences. No fallback is used then and that caused the NullPointerExceptions.

I created a PR to fix the issue:
#508

For us, the fallback works as expected now.

If any of you need it right now you can use:

dependency_overrides:

  flutter_secure_storage:
    git:
      url: https://github.com/jonasbark/flutter_secure_storage.git
      path: flutter_secure_storage

@TheCarpetMerchant
Copy link

@mogol I am re-iterating my advice from this comment on putting a warning on this package about the use of EncryptedSharedPreferences. This package is widely known and lots of devs will start using it only to later run into this bug. Putting up a warning about this specific use case could save a lot of people (literally all of us in this thread) from having bad problems with their app.

I have personally switched from this to using flutter_keychain, which has a much simpler implementation (though only stores string, but that's not really a problem) and I have encountered 0 problems with it so far.

@gibbsvjy007
Copy link

We are facing and similar issue where application is not working when we generate build using appbundle but works when we generate build using apk.
It is not working only on specific Samsung device (android 33)

Any solution? we are stucked and waiting for the solution. tried to apply @jonasbark solution but did not help

Thanks

@MatyasK
Copy link

MatyasK commented Feb 9, 2023

I'm still facing the same issue on release mode with flutter_secure_storage: ^7.0.1, with the latest flutter version.

@techouse
Copy link
Contributor

techouse commented Feb 9, 2023

I'm not sure this fix has been published yet by @juliansteenbakker.

@MatyasK can you try using the master branch?

@MatyasK
Copy link

MatyasK commented Feb 9, 2023

@techouse master branch was last updated over 2 years ago... are you sure this is the right solution?

@techouse
Copy link
Contributor

techouse commented Feb 9, 2023

@MatyasK my bad, the origin/develop branch.

@juliansteenbakker
Copy link
Collaborator

I just released v8.0.0

@thanhchelsea
Copy link

tôi xảy ra khi tôi xây dựng thiết bị vật lý ở chế độ Phát hành

how to resolve issue ?

@komaxx
Copy link

komaxx commented May 31, 2023

Still encountering this issue on Android 11 devices with v8.0.0

@DavidIjsud
Copy link

@komaxx how often do you get the same problem with this version V8.0.0 ? is it only on android 11 ? or other else?

@komaxx
Copy link

komaxx commented Jun 28, 2023

@DavidIjsud
So far, only Android 11, and just a handful of times. Debugging is a bit hard there, this is an internal enterprise app, so not a lot of users - and hard to get logs :/
But I know of 2 instances where I was able to verify that I've seen this bug again, with 8.0.0

@DavidIjsud
Copy link

got it, currently i am migrating to the last version and i hope , it does not crash frecuently.

@yogithesymbian
Copy link

[ build/release mode ]
i have same issue on some specify device .
my phone realm* android 10 its work,
but my security engineer using same device its happen

flutter_secure_storage: ^5.0.2
 flutter doctor -v
[✓] Flutter (Channel stable, 3.13.0, on macOS 14.0 23A344 darwin-arm64, locale en-ID)
    • Flutter version 3.13.0 on channel stable at /Users/yogiarifwidodo/dev/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision efbf63d9c6 (8 weeks ago), 2023-08-15 21:05:06 -0500
    • Engine revision 1ac611c64e
    • Dart version 3.1.0
    • DevTools version 2.25.0

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/yogiarifwidodo/Library/Android/sdk
    • Platform android-33, build-tools 30.0.3
    • ANDROID_HOME = /Users/yogiarifwidodo/Library/Android/sdk
    • Java binary at: /Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment Zulu11.48+21-CA (build 11.0.11+9-LTS)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.3.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14E300c
    • CocoaPods version 1.11.0

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions).

[✓] VS Code (version 1.83.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.74.0

[✓] Connected device (2 available)
    • macOS (desktop) • macos  • darwin-arm64   • macOS 14.0 23A344 darwin-arm64
    • Chrome (web)    • chrome • web-javascript • Google Chrome 117.0.5938.149

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.