dohooo / react-native-reanimated-carousel

🎠 React Native swiper/carousel component, fully implemented using reanimated v2, support to iOS/Android/Web. (Swiper/Carousel)
https://react-native-reanimated-carousel.vercel.app
MIT License
2.86k stars 329 forks source link

Error: Exception in HostFunction: Loss of precision during arithmetic conversion: (long) 18.450172312938385 #682

Closed Hatta-Food-Hub closed 2 months ago

Hatta-Food-Hub commented 2 months ago

Describe the bug In Android crasoul not working trowing 2 errors

  1. Error: Exception in HostFunction: Loss of precision during arithmetic conversion: (long) 18.450172312938385
  2. Current Activity is of incorrect class, expected AppCompatActivity, received null

To Reproduce just installed the library and placed the below code

Expected behavior IOS is working great

Screenshots const PAGE_WIDTH = Number(width.toFixed(2)); type TAnimationStyle = (value: number) => ViewStyle;

const BannersView = gestureHandlerRootHOC( ({ item = {}, showTitle = true, appMainData, appData, styles, appStyle, bannerPress = () => {}, isDarkMode = false, }: any) => { const ref = React.useRef(null); const animationStyle: TAnimationStyle = useCallback((value: number) => { "worklet"; const zIndex = interpolate(value, [-1, 0, 1], [10, 20, 30]); const translateX = interpolate( value, [-2, 0, 1], [-PAGE_WIDTH, 0, PAGE_WIDTH] );

  return {
    transform: [{ translateX }],
    zIndex,
  };
}, []);
console.log("PAGE_WIDTH =>,", PAGE_WIDTH);

let myBanner =
  item?.banner_images ||
  appMainData?.mobile_banners ||
  appData?.mobile_banners ||
  [];
const renderBanners = ({ item = {} }: any) => {
  const imageUrl =
    item?.banner_image_url ||
    getImageUrl(
      item?.image.image_fit,
      item?.image.image_path,
      appStyle?.homePageLayout === 5 ? "800/600" : "1200/1000"
    );

  return (
    <Pressable
      style={{ alignItems: "center" }}
      onPress={() => bannerPress(item)}
    >
      <Image
        source={{
          uri: imageUrl,
        }}
        priority="high"
        cachePolicy="memory-disk"
        style={{
          height:
            appStyle?.homePageLayout !== 5
              ? moderateScale(150)
              : height / 3.8,
          width: PAGE_WIDTH,
          // borderRadius: moderateScale(16),
          backgroundColor: isDarkMode
            ? Colors.whiteOpacity15
            : Colors.greyColor,
        }}
        contentFit="cover"
        contentPosition="center"
      />
    </Pressable>
  );
};
return !isEmpty(myBanner) ? (
  <View
    style={{
      marginBottom: moderateScaleVertical(0),
    }}
  >
    <Carousel
      ref={ref}
      loop
      autoPlay
      style={{
        width: PAGE_WIDTH,
        height: PAGE_WIDTH, }}
      width={PAGE_WIDTH}
      data={myBanner}
      renderItem={renderBanners}
      autoPlayInterval={3000}
      customAnimation={animationStyle}
    />
  </View>
) : (
  <React.Fragment />
);

} );

Screenshot_1727250653 Screenshot_1727250788 Versions (please complete the following information): "expo": "~51.0.28", "react": "18.2.0", "react-dom": "18.2.0", "react-native": "0.74.5",

Smartphone (please complete the following information):

Additional context Add any other context about the problem here.

dosubot[bot] commented 2 months ago

Hey @Hatta-Food-Hub! I'm here to help you with any bugs, questions, or contributions you have. Let's tackle this issue together!

To resolve the errors "Exception in HostFunction: Loss of precision during arithmetic conversion: (long) 18.450172312938385" and "Current Activity is of incorrect class, expected AppCompatActivity, received null" in your Android application, you can follow these steps:

  1. Loss of Precision Error: This error typically occurs when there is an attempt to cast a floating-point number to a long without proper handling. Ensure that any arithmetic operations involving floating-point numbers are correctly handled before casting to a long. For example:

    double value = 18.450172312938385;
    long longValue = (long) Math.round(value); // Use Math.round to avoid precision loss
  2. Incorrect Activity Class Error: The error "Current Activity is of incorrect class, expected AppCompatActivity, received null" suggests that the activity being referenced is not an instance of AppCompatActivity. Ensure that your MainActivity extends AppCompatActivity instead of ReactActivity. Modify your MainActivity as follows:

    package com.rnrc.example.bare;
    
    import android.os.Build;
    import android.os.Bundle;
    import androidx.appcompat.app.AppCompatActivity; // Import AppCompatActivity
    import com.facebook.react.ReactActivityDelegate;
    import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
    import com.facebook.react.defaults.DefaultReactActivityDelegate;
    import expo.modules.ReactActivityDelegateWrapper;
    
    public class MainActivity extends AppCompatActivity { // Extend AppCompatActivity
     @Override
     protected void onCreate(Bundle savedInstanceState) {
       setTheme(R.style.AppTheme);
       super.onCreate(null);
     }
    
     protected String getMainComponentName() {
       return "main";
     }
    
     protected ReactActivityDelegate createReactActivityDelegate() {
       return new ReactActivityDelegateWrapper(this, BuildConfig.IS_NEW_ARCHITECTURE_ENABLED, new DefaultReactActivityDelegate(
           this,
           getMainComponentName(),
           DefaultNewArchitectureEntryPoint.getFabricEnabled(),
           DefaultNewArchitectureEntryPoint.getConcurrentReactEnabled()
       ));
     }
    
     @Override
     public void invokeDefaultOnBackPressed() {
       if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
         if (!moveTaskToBack(false)) {
           super.invokeDefaultOnBackPressed();
         }
         return;
       }
       super.invokeDefaultOnBackPressed();
     }
    }

By making these changes, you should be able to resolve the errors related to precision loss and incorrect activity class [1].

To continue talking to Dosu, mention @dosu.

Hatta-Food-Hub commented 2 months ago

@dosu how to achieve this in expo

dosubot[bot] commented 2 months ago

To achieve this in an Expo project, follow these steps:

  1. Loss of Precision Error: Ensure that any arithmetic operations involving floating-point numbers are correctly handled before casting to a long. In JavaScript, you can use Math.round to avoid precision loss:

    const value = 18.450172312938385;
    const longValue = Math.round(value); // Use Math.round to avoid precision loss
  2. Incorrect Activity Class Error: This error is specific to native Android development and does not directly apply to Expo managed workflow. However, if you encounter similar issues, ensure that your Expo project is correctly configured to use react-native-reanimated and react-native-reanimated-carousel.

    Ensure your babel.config.js includes the react-native-reanimated/plugin:

    module.exports = function(api) {
     api.cache(true);
     return {
       presets: ['babel-preset-expo'],
       plugins: ['react-native-reanimated/plugin'],
     };
    };

    Additionally, ensure your Expo project is using a compatible version of Expo SDK (greater than 41) and has the necessary dependencies:

    "dependencies": {
     "expo": "~51.0.28",
     "react": "18.2.0",
     "react-dom": "18.2.0",
     "react-native": "0.74.5",
     "react-native-reanimated": "~3.10.1",
     "react-native-reanimated-carousel": "^3.5.1",
     "react-native-gesture-handler": "~2.12.0"
    }
  3. Webpack Configuration (if using Webpack with Expo): Adjust your Webpack configuration to ensure compatibility. Here is an example webpack.config.js:

    const path = require('path');
    const createExpoWebpackConfigAsync = require('@expo/webpack-config');
    const { resolver } = require('./metro.config');
    
    const root = path.resolve(__dirname, '../..');
    const app = path.resolve(__dirname, '../app');
    const node_modules = path.join(__dirname, 'node_modules');
    
    module.exports = async function (env, argv) {
     const config = await createExpoWebpackConfigAsync(env, argv);
     const isDev = process.env.NODE_ENV === 'development';
    
     if (!isDev) {
       config.output.publicPath = "/react-native-reanimated-carousel";
     }
    
     config.module.rules.push({
       test: /\.(js|jsx|ts|tsx)$/,
       include: path.resolve(root, 'src'),
       use: 'babel-loader',
     });
    
     config.module.rules.push({
       test: /\.(js|jsx|ts|tsx)$/,
       include: path.resolve(app, 'src'),
       use: 'babel-loader',
     });
    
     Object.assign(config.resolve.alias, {
       ...resolver.extraNodeModules,
       'react-native-web': path.join(node_modules, 'react-native-web'),
     });
    
     return config;
    };

By following these steps, you should be able to resolve the issues and ensure compatibility with Expo [1][2].

To continue talking to Dosu, mention @dosu.

Hatta-Food-Hub commented 2 months ago

so, the issue values should be rounded off not in points or decimals ....

sntg-p commented 3 weeks ago

@Hatta-Food-Hub Did you manage to fix this? Seems like a problem only when using the New Architecture, but since it was officially released with RN 0.76 I'm trying to get this to work with it.

thibaultcapelli commented 2 weeks ago

@sntg-p In this particular case I think it is cause of the zIndex value of the customAnimation.

I have the same issue with the parallax animation cause of the zIndex value too. I will open an issue with a PR to fix it.

sntg-p commented 2 weeks ago

@thibaultcapelli thanks for your comment and PR, I'll be using it as a patch until it gets merged!