react-native-clipboard / clipboard

React Native Clipboard API for both iOS and Android.
MIT License
669 stars 118 forks source link

Error: Attempt to invoke virtual method 'android.content.ClipData$Item android.content.ClipData.getItemAt(int)' on a null object reference #248

Open thomas-dittmar-deferit opened 3 weeks ago

thomas-dittmar-deferit commented 3 weeks ago

Environment

System:
    OS: macOS 14.5
    CPU: (12) arm64 Apple M2 Pro
    Memory: 82.53 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.18.0 - ~/.nvm/versions/node/v18.18.0/bin/node
    Yarn: Not Found
    npm: 9.8.1 - ~/.nvm/versions/node/v18.18.0/bin/npm
    Watchman: 2024.04.29.00 - /opt/homebrew/bin/watchman
  Managers:
    CocoaPods: 1.15.2 - /Users/tom/.rvm/gems/ruby-3.2.2/bin/pod
  SDKs:
    iOS SDK:
      Platforms: DriverKit 23.5, iOS 17.5, macOS 14.5, tvOS 17.5, visionOS 1.2, watchOS 10.5
    Android SDK: Not Found
  IDEs:
    Android Studio: 2023.1 AI-231.9392.1.2311.11076708
    Xcode: 15.4/15F31d - /usr/bin/xcodebuild
  Languages:
    Java: 11.0.23 - /opt/homebrew/opt/openjdk@11/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 18.2.0 => 18.2.0 
    react-native: 0.71.19 => 0.71.19 
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found

Platforms

Android

Versions

Description

We use Sentry to record issues. All of the errors we see have been caused by the function getItemAt(0) in our case. The exact error message is in the title.

After investigating the issue it seems strange that when the function getItemAt(0) is invoked, an exception of null object reference can be thrown as there is a NULL and a getItemCount check (see below on line 6) in file ClipboardModule.java to prevent that exact scenario.

@ReactMethod
public void getString(Promise promise) {
  try {
    ClipboardManager clipboard = getClipboardService();
    ClipData clipData = clipboard.getPrimaryClip();
    if (clipData != null && clipData.getItemCount() >= 1) {
      ClipData.Item firstItem = clipboard.getPrimaryClip().getItemAt(0);
      promise.resolve("" + firstItem.getText());
    } else {
      promise.resolve("");
    }
  } catch (Exception e) {
    promise.reject(e);
  }
}

I wonder whether that issue could be prevented by using clipData instead of clipboard.getPrimaryClip() like that

if (clipData != null && clipData.getItemCount() >= 1) {
      ClipData.Item firstItem = clipData.getItemAt(0);

since clipData has been checked beforehand. But I could be wrong.

Reproducible Demo

N/A