如何正确读取Android上的AsyncStorage

时间:2018-01-08 13:11:58

标签: android react-native redux asyncstorage redux-persist

似乎可以从Android(本机)访问AsyncStorage;但是我仍然在努力做这项工作。

在我的React Native应用程序中,我有类似的内容:

商品

const config = {
  ...
}

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


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

用户缩减器

export class Actions {
    ...
}

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

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

从商店获取用户

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

现在,当我尝试从Android获得相同的用户时问题开始了,我所有的挫败尝试都是这样:

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

由于用户是一个对象,我不知道这是否是获取'first_name'的正确方法,我尝试获取'user'但是没有用。

我开始认为我应该使用react-native-sqlite-storage来了解我的数据结构,但我不知道我是否能够在Android上访问该数据库。

PS:我想访问AsyncStorage而不是SharedPreferences

Lib版本

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

有些问题不起作用

2 个答案:

答案 0 :(得分:3)

AsyncStorage它是一个独特的JSON对象,而我期待很多行keyvalue;这就是我失去原因的原因。

首先我继续查询

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

然后我检查以避免空指针

if (catalystLocalStorage.moveToFirst()) {

然后我做了提取

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

我确信可能有更好的方法来做到这一点,但是我知道我很好。

如果你有更好的想法,请留下你的想法。

<强>更新

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 "";
        }
    }
}

致电班级

AsyncStorage as = new AsyncStorage(context);
as.getFullname()

答案 1 :(得分:0)

我的应用程序中的闹钟有问题,我决定在Android端使用AsyncStorage,然后使用下面的代码,我可以从AsyncStorage中获取所有值并生成在我的应用程序的AsyncStorage中注册的所有警报。 / p>

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