How to Read AsyncStorage on Android Correctly

為{幸葍}努か 提交于 2019-12-17 20:39:37

问题


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

  • Access AsyncStorage from native code
  • Can I access data stored in React Native's AsyncStorage from java layer?
  • React Native: How to use Java code to fetch data via React Native async storage

回答1:


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()



回答2:


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();
            }
        }


来源:https://stackoverflow.com/questions/48151030/how-to-read-asyncstorage-on-android-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!