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:
ReactApplicationContext
from native Android class for the class instance.@ReactMethod
from native Android class.ReactContextBaseJavaModule
.Created a native android SharedPreferences
class that exposes all the shared preferences related methods.
class MySharedPreferences constructor(context: Context) {/getters and setters/}
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)
}}
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.