I am storing few user preferences in React Native using AsyncStorage. Now, I need to get those preference from a background service. I can't access AsyncStorage from the Java layer. Is there a way to do it?
In iOS, We can import RCTAsyncLocalStorage.h and call _getValueForKey. But, I can't find a way to do it in Android.
I have following code which does the job.
import com.facebook.react.modules.storage.AsyncLocalStorageUtil;
import com.facebook.react.modules.storage.ReactDatabaseSupplier;
import android.database.sqlite.SQLiteDatabase;
.....
.....
SQLiteDatabase readableDatabase = null;
readableDatabase = ReactDatabaseSupplier.getInstance(this.getApplicationContext()).getReadableDatabase();
 if (readableDatabase != null) {
    String impl = AsyncLocalStorageUtil.getItemImpl(readableDatabase, "myTableName");
    Log.d(TAG, "impl: " + impl);
  }
====================
and to delete the DB
=====================
SQLiteDatabase database = ReactDatabaseSupplier.getInstance(getContext()).getWritableDatabase();
database.delete(CATALYST_LOCAL_STORAGE, null, null);
                        My solution is to use directly the ReactDatabaseSupplier class (my app doesn't use Rocksdb so I can be quite sure that the SQLite DB is always used as storage (and, I guess it will always prefer the SQLite database over local storage))
The database is a simple key-value DB (two columns, key and value), with a table name 'catalystLocalStorage' (you can try to read the ReactDatabaseSupplier#TABLE_NAME but it's protected, you can try using reflection, but I'm not sure it's worth the troubles)
Cursor catalystLocalStorage = null;
SQLiteDatabase readableDatabase = null;
try {
  readableDatabase = ReactDatabaseSupplier.getInstance(this.getApplicationContext()).getReadableDatabase();
  catalystLocalStorage = readableDatabase.query("catalystLocalStorage", new String[]{"value"}, "key = ?", new String[] { "keyName" }, null, null, null);
  final String value = catalystLocalStorage.getString(catalystLocalStorage.getColumnIndex("value"));
  [...]
} finally { 
  if (catalystLocalStorage != null) {
    catalystLocalStorage.close();
  }
  if (readableDatabase != null) {
    readableDatabase.close();
  }
}
It works to me, not sure how future-proof it can be
I tried to use the AsyncStorage from the java layer. But, I couldn't. So, I built a React Native plugin to access Android's Native SharedPreferences from the javascript layer. I have published it in the github (https://github.com/sriraman/react-native-shared-preferences) 
Now I'm using this SharedPreferences from both Java and React Native layer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With