Skip to content

Commit

Permalink
v1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
aMarCruz committed Jul 23, 2018
1 parent 8bb26ca commit dcd7849
Show file tree
Hide file tree
Showing 10 changed files with 157 additions and 86 deletions.
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
flow-typed/
test/
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@ buck-out/

package-lock.json
yarn.lock
*.tgz
9 changes: 9 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.idea
.gradle
local.properties
*.iml
*.log
*.bak
build/
test/
.vscode/
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
## react-native-cross-settings changes

### 2018-03-19 v1.0.0

- Flow types added (not sure if correctly).
- Better support for `long` & `double` values (the range of `long` is still limited by the RN Bridge).
- Remove react-native from peerDependencies, since this library must work in versions prior to 0.50.
- The default `buildToolsVersion` was changed 26.0.3 and `compileSdkVersion`/`targetSdkVersion` to 26.

### 2018-03-19 v0.2.0

- Changed minSdkVersion version to 16 - Thanks to @wayne1203
Expand Down
62 changes: 49 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@

React Native `Settings` module for both Android & iOS.

\* For React Native 0.50+

## Installation

```bash
Expand All @@ -27,6 +25,7 @@ const watchId = Settings.watchKeys('strvar', () => {
console.log('strvar changed.');
});

// If you never saved a value in "strvar", this is undefined.
console.log('restored setting:', Settings.get('strvar'));
// => undefined

Expand All @@ -35,8 +34,8 @@ Settings.set({ strvar: 'First setting' });
console.log('new setting:', Settings.get('strvar'));
// => "First setting"

// Cannot remove a value, but you can set it to `null`.
// Next time you App start, the value will be undefined.
// You cann't remove a value, but you can set it to null.
// Next time your App start, the value will be undefined.
Settings.set({ strvar: null });
console.log('new setting:', Settings.get('strvar'));
// => null
Expand All @@ -54,30 +53,67 @@ See React Native [Settings](https://facebook.github.io/react-native/docs/setting

### Methods

- **get()**<br>
`static get(key: string) => number | string | value | null`
- **get()**

```typescript
static get(key: string) => number | string | value | null
```

- **set()**

```typescript
static set(settings: { [key: string]: number | string | boolean | null } ) => void
```

- **set()**<br>
`static set(settings: { [key: string]: number | string | boolean | null } ) => void`
- **watchKeys()**

- **watchKeys()**<br>
`static watchKeys(keys: string | string[], callback: () => any) => any`
```typescript
static watchKeys(keys: string | string[], callback: () => any) => number
```

- **clearWatch()**<br>
`static clearWatch(watchId: any) => void`
- **clearWatch()**

```typescript
static clearWatch(watchId: number) => void
```

### NOTE

In Android, valid value types to store are `boolean`, `string`, and `number`.

If you pass `null` as value, the key will be removed in the next session.

PRs and stars are welcome ;)
If you want to save other types use the appropriate conversion:

```js
// Storing a Date object:
Settings.set({ myDate: new Date().toJSON() })
// Retrieve
const myDate = new Date(Settings.get('myDate'))
// Storing an array
Settings.set({ myArray: JSON.stringify([1,2,3]) })
// Retrieve
const myArray = JSON.parse(Settings.get('myArray') || '[]')
```

## Changes in v1.0

- Flow types added (not sure if correctly).
- Better support for `long` & `double` values (the range of `long` is still limited by the RN Bridge).
- Remove react-native from peerDependencies, since this library must work in versions prior to 0.50.
- The default `buildToolsVersion` was changed 26.0.3 and `compileSdkVersion`/`targetSdkVersion` to 26.

## TODO

[ ] Support Array

## License

The [MIT License](LICENCE) (MIT)

PRs and stars are welcome ;)

[npm-image]: https://img.shields.io/npm/v/react-native-cross-settings.svg
[npm-url]: https://www.npmjs.com/package/react-native-cross-settings
[license-image]: https://img.shields.io/npm/l/express.svg
Expand Down
12 changes: 8 additions & 4 deletions android/build.gradle
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
def DEFAULT_COMPILE_SDK_VERSION = 26
def DEFAULT_BUILD_TOOLS_VERSION = "26.0.3"
def DEFAULT_TARGET_SDK_VERSION = 26

buildscript {
repositories {
jcenter()
Expand All @@ -10,13 +14,13 @@ buildscript {
apply plugin: 'com.android.library'

android {
compileSdkVersion 26
buildToolsVersion "27.0.3"
compileSdkVersion rootProject.hasProperty('compileSdkVersion') ? rootProject.compileSdkVersion : DEFAULT_COMPILE_SDK_VERSION
buildToolsVersion rootProject.hasProperty('buildToolsVersion') ? rootProject.buildToolsVersion : DEFAULT_BUILD_TOOLS_VERSION
defaultConfig {
minSdkVersion 16
targetSdkVersion 26
targetSdkVersion rootProject.hasProperty('targetSdkVersion') ? rootProject.targetSdkVersion : DEFAULT_TARGET_SDK_VERSION
versionCode 1
versionName "0.2.0"
// versionName "0.3.0"
}

lintOptions {
Expand Down
76 changes: 49 additions & 27 deletions android/src/main/java/io/amarcruz/rnsettings/RNSettingsModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class RNSettingsModule extends ReactContextBaseJavaModule {

private static final String TAG = "RNSettings";
private static final String PREFS_NAME = "RNSettrinsPrefsFile";
private static final String CHANGED_EVENT = "settings_updated";
private static final String CHANGED_EVENT = "settingsUpdated";

private ReactApplicationContext mReactContext;

Expand Down Expand Up @@ -55,11 +55,7 @@ public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
final Map<String, ?> settings = prefs.getAll();

constants.put("CHANGED_EVENT", CHANGED_EVENT);

if (settings != null) {
constants.put("settings", makeMap(settings));
}
constants.put("settings", makeMap(settings));

return constants;
}
Expand All @@ -70,23 +66,30 @@ public Map<String, Object> getConstants() {
private static Map<String, Object> makeMap(final Map<String, ?> src) {
final Map<String, Object> map = new HashMap<>();

for (Map.Entry<String, ?> entry : src.entrySet()) {
final String key = entry.getKey();
final Object value = entry.getValue();

try {
if (value != null && (
value instanceof Boolean ||
value instanceof Integer ||
value instanceof Long ||
value instanceof Float ||
value instanceof String
)) {
map.put(key, value);
if (src != null) {
for (Map.Entry<String, ?> entry : src.entrySet()) {
final String key = entry.getKey();
final Object value = entry.getValue();

if (value == null) {
continue;
}

try {
if (value instanceof Long) {
map.put(key, Double.longBitsToDouble((long) value));
} else if ((
value instanceof Boolean ||
value instanceof Integer ||
value instanceof Float || /* keep this for compatibility */
value instanceof String
)) {
map.put(key, value);
}
} catch (Exception e) {
Log.e(TAG, "Reading setting " + key + " generates error.");
e.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, "Reading setting " + key + " generates error.");
e.printStackTrace();
}
}

Expand Down Expand Up @@ -120,8 +123,7 @@ public void setValues(final ReadableMap map) {
editor.putBoolean(key, map.getBoolean(key));
break;
case Number:
// Can be int or double.
editor.putFloat(key, (float) map.getDouble(key));
storeNumber(editor, key, map.getDouble(key));
break;
case String:
editor.putString(key, map.getString(key));
Expand All @@ -137,6 +139,21 @@ public void setValues(final ReadableMap map) {
}
}

/*
RN ReadableMap has no a `getLong` method, so type Long is used with `doubleToRawLongBits`
for storing Double values, as SharedPreferences.Editor has no `putDouble`.
*/
private void storeNumber(final SharedPreferences.Editor editor, final String key, final double number) {
// Can be long, float, or double.
if (number == (int) number || Double.isNaN(number)) {
Log.e(TAG, "Saving " + key + " as int.");
editor.putInt(key, (int) number);
} else {
Log.e(TAG, "Saving " + key + " as double.");
editor.putLong(key, Double.doubleToRawLongBits(number));
}
}

private OnSharedPreferenceChangeListener listener = new OnSharedPreferenceChangeListener() {

public void onSharedPreferenceChanged(SharedPreferences pref, String key) {
Expand All @@ -156,10 +173,15 @@ public void onSharedPreferenceChanged(SharedPreferences pref, String key) {
map.putString(key, str);
} catch (ClassCastException e1) {
try {
Double num = (double) pref.getFloat(key, 0f);
map.putDouble(key, num);
int num = pref.getInt(key, 0);
map.putInt(key, num);
} catch (ClassCastException e2) {
map.putBoolean(key, pref.getBoolean(key, false));
try {
map.putBoolean(key, pref.getBoolean(key, false));
} catch (ClassCastException e3) {
long bits = pref.getLong(key, 0L);
map.putDouble(key, Double.longBitsToDouble(bits));
}
}
} catch (Exception e) {
ok = false;
Expand Down
14 changes: 14 additions & 0 deletions index.js.flow
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// @flow

export type RNSettingsTypes = boolean | string | number | null;
export type RNSettingsSet = { [key: string]: RNSettingsTypes };

declare interface RNSettings {
get(key: string): RNSettingsTypes;
set(settings: RNSettingsSet): void;
watchKeys(keys: string | Array<string>, watcher: () => any): number;
clearWatch(watchId: number): void;
}

declare var Settings: RNSettings;
export default Settings;
8 changes: 1 addition & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "react-native-cross-settings",
"description": "React Native `Settings` module for both Android & iOS.",
"version": "0.2.0",
"version": "1.0.0",
"license": "MIT",
"main": "./index.js",
"typings": "./index.d.ts",
Expand All @@ -13,12 +13,6 @@
"type": "git",
"url": "https://github.com/aMarCruz/react-native-cross-settings.git"
},
"peerDependencies": {
"react-native": ">=0.50.0"
},
"devDependencies": {
"react-native": ">=0.50.0"
},
"dependencies": {
"invariant": "^2.2.3"
}
Expand Down
Loading

0 comments on commit dcd7849

Please sign in to comment.