poolet
poolet

Reputation: 371

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

Upvotes: 4

Views: 12212

Answers (2)

HartWoom
HartWoom

Reputation: 587

@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";
   }
}

Upvotes: 2

Alan
Alan

Reputation: 687

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

Upvotes: 3

Related Questions