2

It seems that it's possible access the AsyncStorage from Android (native); but I still struggling to make this work.

In my React Native application, I have something like:

Store

const config = {
  ...
}

export const reducers = {
  ...
  user: user
}


let rootReducer = combineReducers(reducers)
let reducer = persistReducer(config, rootReducer)

User Reducer

export class Actions {
    ...
}

const initialState = {
      first_name: : null,
      last_name: : null,
      email: null,
      addresses: [
          { ... }
      ]
    }
  }
}

export const reducer = (state = initialState, action) => {
  switch (action.type) {
    ...
  }
}

Getting the User from store

const user = store.getState().user
console.log(user.first_name) // Steve
...

Now the issue starts when I try to get the same user from Android, of all my frustrated attempts this is what I have:

try {
    readableDatabase = ReactDatabaseSupplier.getInstance(getReactApplicationContext()).getReadableDatabase();
    catalystLocalStorage = readableDatabase.query("catalystLocalStorage", new String[]{"value"}, "key = ?", new String[] { "full_name" }, null, null, null);
    String[] names = catalystLocalStorage.getColumnNames();
    if (catalystLocalStorage.moveToFirst()) {
        final String value = catalystLocalStorage.getString(catalystLocalStorage.getColumnIndex("value"));
        Log.d(TAG, value);
    }
} finally {
    if (catalystLocalStorage != null) {
        catalystLocalStorage.close();
    }

    if (readableDatabase != null) {
        readableDatabase.close();
    }
}

Since the User it's an object, I don't know if this is the right way to get the 'first_name', I tried get 'user' but didn't worked.

I'm starting to think that I should use react-native-sqlite-storage where I would know my data structure, but I don't know if I would be able to access that database on Android.

PS: I want access AsyncStorage not SharedPreferences


Lib Versions

react-native: 0.48.4
redux: 3.7.2
redux-persist: 5.4.0

Some questions that didn't work

Pablo
  • 1,953
  • 4
  • 28
  • 57

2 Answers2

8

AsyncStorage it's an unique JSON Object and instead I was expecting many rows of key and value; That's why I was getting null.

So first I continue with the query

catalystLocalStorage = readableDatabase.query("catalystLocalStorage", new String[]{"key", "value"}, null, null, null, null, null);

then I check to avoid null pointer

if (catalystLocalStorage.moveToFirst()) {

then I do the fetch

do {
    // JSONObject will ask for try catch
    JSONObject obj = new JSONObject(catalystLocalStorage.getString(catalystLocalStorage.getColumnIndex("value")));
} while(catalystLocalStorage.moveToNext());

I'm sure that may have better ways to do this, but right know I'm fine with that.

If you have better ideas please leave your thought.

UPDATE

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.modules.storage.ReactDatabaseSupplier;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;

public class AsyncStorage {

    public static String TAG = "RNAsyncStorage";
    public ReactApplicationContext context;
    public ArrayList<JSONObject> collection;
    public JSONObject data;
    public JSONObject user;

    Cursor catalystLocalStorage = null;
    SQLiteDatabase readableDatabase = null;

    public AsyncStorage (ReactApplicationContext context) {
        this.context = context;
        this.collection = new ArrayList<JSONObject>();
        this.fetch();
        this.setUser();
    }

    public void fetch() {
        try {
            readableDatabase = ReactDatabaseSupplier.getInstance(context).getReadableDatabase();
            catalystLocalStorage = readableDatabase.query("catalystLocalStorage", new String[]{"key", "value"}, null, null, null, null, null);

            if (catalystLocalStorage.moveToFirst()) {
                do {
                    try {
                        // one row with all AsyncStorage: { "user": { ... }, ... }
                        String json = catalystLocalStorage.getString(catalystLocalStorage.getColumnIndex("value"));
                        JSONObject obj = new JSONObject(json);

                        String user = obj.getString("user");

                        JSONObject res = new JSONObject();
                        res.put("user", new JSONObject(user));

                        collection.add(res);
                    } catch(Exception e) {
                        // do something
                    }
                } while(catalystLocalStorage.moveToNext());
            }
        } finally {
            if (catalystLocalStorage != null) {
                catalystLocalStorage.close();
            }

            if (readableDatabase != null) {
                readableDatabase.close();
            }

            data = this.collection.get(0);
        }
    }

    public String getFullname () {
        try {
            return user.getString("fullname");
        } catch (Exception e) {
            return "";
        }
    }
}

Calling the class

AsyncStorage as = new AsyncStorage(context);
as.getFullname()
Pablo
  • 1,953
  • 4
  • 28
  • 57
  • 1
    Its not easy to get the react application context anywhere in the app. Can you help me how did you get the react application context? – Tarun Jan 21 '20 at 15:08
  • @Tarun, oh I'm sorry but I'm not an expert so I would need to see what I did to help you with that. But since I moved on I'm working in another company and I don't have the original project. – Pablo Jan 21 '20 at 17:52
  • @Tarun I have the same issue, were you able to solve it? – Amogh Jahagirdar May 30 '20 at 17:57
1

I had a problem with alarm clock in my application and I decided to use AsyncStorage on Android side, then I use the code below and I could get all values from AsyncStorage and generate all alarms that was registered in my application's AsyncStorage.

SQLiteDatabase readableDatabase = null;
        readableDatabase = ReactDatabaseSupplier.getInstance(this.reactContext).getReadableDatabase();
        Cursor catalystLocalStorage = readableDatabase.query("catalystLocalStorage", null, null, null, null, null, null);
        try {
            List<AlarmeDTO> listaAlarmes = new ArrayList<>();
            if (catalystLocalStorage.moveToFirst()) {

                do {
                    //Ex: key: 01082019_0800
                    //value: [{executionDate: 2019-08-01T08:00}]
                    String key = catalystLocalStorage.getString(0);
                    String json = catalystLocalStorage.getString(1);

                    if (dados.length == 3) {
                        ...generate my alarms with key and json
                    }

                } while (catalystLocalStorage.moveToNext());

            }//2_31082019_0900 - [{"idPrescricaoMedicamento":35,"nomeMedicamento":"VITAMINA"}]

        } finally {
            if (catalystLocalStorage != null) {
                catalystLocalStorage.close();
            }

            if (readableDatabase != null) {
                readableDatabase.close();
            }
        }
  • I had to make a slight adjustment because I was using this in MainActivity.java, instead of `getInstance(this.reactContext)` I had to use `getInstance(getApplicationContext())`. Thanks this code helped a lot getting started. – hmajid2301 Jan 11 '20 at 19:37