Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ApplicationContext in ReactContextBaseJavaModule?

I am building a React Native Application, in a react native module in Android code I wish to access the path for cache files used by Android code.

At some point I am writing (from the native code) a json file in the cache of the app data, I use getApplicationContext() to get the context and apply getCacheDir() to get the path of the cache files.

In a class extending ReactContextBaseJavaModule I want to access the Application context to get the cache files path, but when invoking getApplicationContext() on the React context and using getCacheDir() the path returned is not the same as the one returned before.

What is the way to get the Global context in a react native module ?

Cheers

like image 738
poolet Avatar asked Nov 02 '25 05:11

poolet


2 Answers

ReactApplicationContext is passed in to the constructor of your class that extends ReactContextBaseJavaModule. You can call ReactApplicationContext.getApplicationContext() to get the ApplicationContext.

like image 198
Alan Avatar answered Nov 03 '25 19:11

Alan


@Alan answer is great but I wanted to add a code snippet for more clarity :

public class FlashModule extends ReactContextBaseJavaModule {
   Context context;

   FlashModule(ReactApplicationContext context) {
       super(context);
       this.context = context.getApplicationContext(); // This is where you get the context
   }

   @Override
   public String getName() {
      return "FlashModule";
   }
}

like image 40
HartWoom Avatar answered Nov 03 '25 19:11

HartWoom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!