1

I am new to React Native and working on an application which stores local data using Android SharedPreferences. I currently have SharedPreferences setup as ReactContextBaseJavaModule and am able to access all methods through @ReactMethod annotation from a React Native file.

I need to access the value from SharedPreference, defined as ReactContextBaseJavaModule, inside native Android module. Currently I am able to achieve that by updating a constant defined in native Android class(*.kt). Is there a better way to do this, i.e. ability to access methods defined inside ReactContextBaseJavaModule from Android classes or creating a wrapper for SharedPreference access?

I have tried to search for the solution in multiple platforms, and found solutions on how we can access native module from React Native files. I am unable to find the solution on two-way access to a ReactContextBaseJavaModule class.

The challenges I am facing:

  1. Unable to pass ReactApplicationContext from native Android class for the class instance.
  2. Unable to access methods annotated with @ReactMethod from native Android class.
  3. Injecting native Android class instance inside ReactContextBaseJavaModule.

1 Answer 1

0
  1. Created a native android SharedPreferences class that exposes all the shared preferences related methods.

    class MySharedPreferences constructor(context: Context) {/getters and setters/}

  2. Created a ReactContextBaseJavaModule as a bridge to React Native with exposed methods annotated with @ReactModule. Created an instance of Android native SharedPreferences inside init{} method.

     class MySharedPreferencesModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
      private var mySharedPreferences: BeaconSharedPreferences
    
     init {
         mySharedPreferences = MySharedPreferences(context = reactContext)
     }}
    
  3. Now I am able to access Android native SharedPreferences with an instance inside the Android class where I need to access the prefs values, and access/update values through the bridge to/from React Native.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.