Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

react native - How to Read AsyncStorage on Android Correctly

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...