Java Code Examples for com.facebook.react.bridge.WritableNativeMap

The following are top voted examples for showing how to use com.facebook.react.bridge.WritableNativeMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: react-native-ibeacons   File: BeaconsAndroidModule.java   Source Code and License 8 votes vote down vote up
private WritableMap createRangingResponse(Collection<Beacon> beacons, Region region) {
    WritableMap map = new WritableNativeMap();
    map.putString("identifier", region.getUniqueId());
    map.putString("uuid", region.getId1() != null ? region.getId1().toString() : "");
    WritableArray a = new WritableNativeArray();
    for (Beacon beacon : beacons) {
        WritableMap b = new WritableNativeMap();
        b.putString("uuid", beacon.getId1().toString());
        b.putInt("major", beacon.getId2().toInt());
        b.putInt("minor", beacon.getId3().toInt());
        b.putInt("rssi", beacon.getRssi());
        b.putDouble("distance", beacon.getDistance());
        b.putString("proximity", getProximity(beacon.getDistance()));
        a.pushMap(b);
    }
    map.putArray("beacons", a);
    return map;
}
 
Example 2
Project: RNLearn_Project1   File: CatalystNativeJavaToJSArgumentsTestCase.java   Source Code and License 7 votes vote down vote up
public void testStringWithMultibyteUTF8Characters() {
  TestJavaToJSArgumentsModule jsModule = mInstance.getJSModule(TestJavaToJSArgumentsModule.class);

  WritableNativeMap map = new WritableNativeMap();
  map.putString("two-bytes", "\u00A2");
  map.putString("three-bytes", "\u20AC");
  map.putString("four-bytes", "\uD83D\uDE1C");
  map.putString(
      "mixed",
      "\u017C\u00F3\u0142\u0107 g\u0119\u015Bl\u0105 \u6211 \uD83D\uDE0E ja\u017A\u0107");

  jsModule.receiveMapWithMultibyteUTF8CharacterString(map);
  waitForBridgeAndUIIdle();
  mAssertModule.verifyAssertsAndReset();

  WritableArray array = new WritableNativeArray();
  array.pushString("\u00A2");
  array.pushString("\u20AC");
  array.pushString("\uD83D\uDE1C");
  array.pushString(
      "\u017C\u00F3\u0142\u0107 g\u0119\u015Bl\u0105 \u6211 \uD83D\uDE0E ja\u017A\u0107");

  jsModule.receiveArrayWithMultibyteUTF8CharacterString(array);
  waitForBridgeAndUIIdle();
  mAssertModule.verifyAssertsAndReset();
}
 
Example 3
Project: react-native-camera-android-simple   File: ImageFileUtils.java   Source Code and License 6 votes vote down vote up
public static void addToGalleryAndNotify(Context context, File imageFile, final Promise promise) {
    final WritableMap response = new WritableNativeMap();
    response.putString("path", Uri.fromFile(imageFile).toString());

    // borrowed from react-native CameraRollManager, it finds and returns the 'internal'
    // representation of the image uri that was just saved.
    // e.g. content://media/external/images/media/123
    MediaScannerConnection.scanFile(
            context,
            new String[]{imageFile.getAbsolutePath()},
            null,
            new MediaScannerConnection.OnScanCompletedListener() {
                @Override
                public void onScanCompleted(String path, Uri uri) {
                    promise.resolve(response);
                }
            });
}
 
Example 4
Project: taplytics-react-native   File: TaplyticsReactModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void getSessionInfo(final Promise callback) {
    Taplytics.getSessionInfo(new SessionInfoRetrievedListener() {
        @Override
        public void sessionInfoRetrieved(HashMap hashMap) {
            WritableMap resultData = new WritableNativeMap();
            if(hashMap.containsKey("session_id")){
                resultData.putString("session_id", (String) hashMap.get("session_id"));
            }
            if(hashMap.containsKey("appUser_id")){
                resultData.putString("appUser_id", (String) hashMap.get("appUser_id"));
            }

            callback.resolve(resultData);
        }
    });
}
 
Example 5
Project: react-native-simple-download-manager   File: Downloader.java   Source Code and License 6 votes vote down vote up
public WritableMap checkDownloadStatus(long downloadId) {

        DownloadManager.Query downloadQuery = new DownloadManager.Query();
        downloadQuery.setFilterById(downloadId);
        Cursor cursor = downloadManager.query(downloadQuery);
        HashMap<String, String> result = new HashMap<>();
        if (cursor.moveToFirst()) {
            result = getDownloadStatus(cursor, downloadId);
        } else {
            result.put("status", "UNKNOWN");
            result.put("reason", "COULD_NOT_FIND");
            result.put("downloadId", String.valueOf(downloadId));
        }
        WritableMap wmap = new WritableNativeMap();
        for (HashMap.Entry<String, String> entry : result.entrySet()) {
            wmap.putString(entry.getKey(), entry.getValue());
        }
        return wmap;
    }
 
Example 6
Project: react-native-android-library-humaniq-api   File: DownloadModule.java   Source Code and License 6 votes vote down vote up
/**
 * Checks download progress.
 */
private void checkProgress() {
  DownloadManager.Query query = new DownloadManager.Query();
  query.setFilterById(enqueue);
  Cursor cursor = dm.query(query);
  if (!cursor.moveToFirst()) {
    cursor.close();
    return;
  }
  long reference = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));

  int bytes_downloaded =
      cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
  int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

  int progress = (int) ((bytes_downloaded * 100l) / bytes_total);
      WritableMap writableMap = new WritableNativeMap();
      writableMap.putInt("progress", progress);
      sendEvent(writableMap);

  if(progress >= 100) {
    future.cancel(true);
  }
}
 
Example 7
Project: react-native-camera   File: RCTCameraModule.java   Source Code and License 6 votes vote down vote up
private void resolveImage(final File imageFile, int width, int height, final Promise promise, boolean addToMediaStore) {
    final WritableMap response = new WritableNativeMap();
    response.putString("path", Uri.fromFile(imageFile).toString());
    response.putInt("width", width);
    response.putInt("height", height);

    if(addToMediaStore) {
        // borrowed from react-native CameraRollManager, it finds and returns the 'internal'
        // representation of the image uri that was just saved.
        // e.g. content://media/external/images/media/123
        MediaScannerConnection.scanFile(
                _reactContext,
                new String[]{imageFile.getAbsolutePath()},
                null,
                null);
    }

    promise.resolve(response);
}
 
Example 8
Project: react-native-huashi-100u   File: HsOtgModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void auth(Promise promise) {
    if (HSinterface == null){
        promise.reject("-1", "init failed");
        return;
    }
    int ret = HSinterface.Authenticate();
    WritableMap result = new WritableNativeMap();
    if (ret == 1){
        result.putString("code", ret+"");
        result.putString("msg", "success");
        promise.resolve(result);
    }else if (ret == 2){
        result.putString("code", ret+"");
        result.putString("msg", "auth failed");
        promise.resolve(result);
    }else if (ret == 0){
        promise.reject("0", "connect failed");
    }
}
 
Example 9
Project: react-native-fast-image   File: FastImageViewManager.java   Source Code and License 6 votes vote down vote up
@Override
public boolean onException(
        Exception e,
        GlideUrl uri,
        Target<GlideDrawable> target,
        boolean isFirstResource
) {
    OkHttpProgressGlideModule.forget(uri.toStringUrl());
    if (!(target instanceof ImageViewTarget)) {
        return false;
    }
    ImageViewWithUrl view = (ImageViewWithUrl) ((ImageViewTarget) target).getView();
    ThemedReactContext context = (ThemedReactContext) view.getContext();
    RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class);
    int viewId = view.getId();
    eventEmitter.receiveEvent(viewId, REACT_ON_ERROR_EVENT, new WritableNativeMap());
    eventEmitter.receiveEvent(viewId, REACT_ON_LOAD_END_EVENT, new WritableNativeMap());
    return false;
}
 
Example 10
Project: react-native-fast-image   File: FastImageViewManager.java   Source Code and License 6 votes vote down vote up
@Override
public boolean onResourceReady(
        GlideDrawable resource,
        GlideUrl uri,
        Target<GlideDrawable> target,
        boolean isFromMemoryCache,
        boolean isFirstResource
) {
    if (!(target instanceof ImageViewTarget)) {
        return false;
    }
    ImageViewWithUrl view = (ImageViewWithUrl) ((ImageViewTarget) target).getView();
    ThemedReactContext context = (ThemedReactContext) view.getContext();
    RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class);
    int viewId = view.getId();
    eventEmitter.receiveEvent(viewId, REACT_ON_LOAD_EVENT, new WritableNativeMap());
    eventEmitter.receiveEvent(viewId, REACT_ON_LOAD_END_EVENT, new WritableNativeMap());
    return false;
}
 
Example 11
Project: react-native-fused-location   File: FusedLocationModule.java   Source Code and License 6 votes vote down vote up
private WritableMap convertLocationToJSON(Location l) {
    WritableMap params = new WritableNativeMap();
    params.putDouble("latitude", l.getLatitude());
    params.putDouble("longitude", l.getLongitude());
    params.putDouble("accuracy", l.getAccuracy());
    params.putDouble("altitude", l.getAltitude());
    params.putDouble("bearing", l.getBearing());
    params.putString("provider", l.getProvider());
    params.putDouble("speed", l.getSpeed());
    params.putString("timestamp", Long.toString(l.getTime()));
    boolean isMock = false;
    if (android.os.Build.VERSION.SDK_INT >= 18) {
        isMock = l.isFromMockProvider();
    } else {
        isMock = !Settings.Secure.getString(getReactApplicationContext().getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0");
    }
    params.putBoolean("mocked", isMock);
    return params;
}
 
Example 12
Project: react-native-connectivity-status   File: RNConnectivityStatusModule.java   Source Code and License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
  final String action = intent.getAction();

  if (action != null && action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
    final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
            BluetoothAdapter.ERROR);
    boolean active = false;
    switch (state) {
      case BluetoothAdapter.STATE_OFF:
        active = false;
        break;
      case BluetoothAdapter.STATE_ON:
        active = true;
        break;
    }

    final WritableMap eventMap = new WritableNativeMap();
    eventMap.putString(EVENT_TYPE, "bluetooth");
    eventMap.putBoolean(EVENT_STATUS, active);
    getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(RN_CONNECTIVITY_STATUS_TOPIC, eventMap);
  }
}
 
Example 13
Project: RNLearn_Project1   File: ReactInstanceManager.java   Source Code and License 6 votes vote down vote up
private void attachMeasuredRootViewToInstance(
    ReactRootView rootView,
    CatalystInstance catalystInstance) {
  Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachMeasuredRootViewToInstance");
  UiThreadUtil.assertOnUiThread();

  // Reset view content as it's going to be populated by the application content from JS
  rootView.removeAllViews();
  rootView.setId(View.NO_ID);

  UIManagerModule uiManagerModule = catalystInstance.getNativeModule(UIManagerModule.class);
  int rootTag = uiManagerModule.addMeasuredRootView(rootView);
  rootView.setRootViewTag(rootTag);
  @Nullable Bundle launchOptions = rootView.getLaunchOptions();
  WritableMap initialProps = Arguments.makeNativeMap(launchOptions);
  String jsAppModuleName = rootView.getJSModuleName();

  WritableNativeMap appParams = new WritableNativeMap();
  appParams.putDouble("rootTag", rootTag);
  appParams.putMap("initialProps", initialProps);
  catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams);
  rootView.onAttachedToReactInstance();
  Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
 
Example 14
Project: RNLearn_Project1   File: Arguments.java   Source Code and License 6 votes vote down vote up
private static void addEntry(WritableNativeMap nativeMap, String key, Object value) {
  value = makeNativeObject(value);
  if (value == null) {
    nativeMap.putNull(key);
  } else if (value instanceof Boolean) {
    nativeMap.putBoolean(key, (Boolean) value);
  } else if (value instanceof Integer) {
    nativeMap.putInt(key, (Integer) value);
  } else if (value instanceof Number) {
    nativeMap.putDouble(key, ((Number) value).doubleValue());
  } else if (value instanceof String) {
    nativeMap.putString(key, (String) value);
  } else if (value instanceof WritableNativeArray) {
    nativeMap.putArray(key, (WritableNativeArray) value);
  } else if (value instanceof WritableNativeMap) {
    nativeMap.putMap(key, (WritableNativeMap) value);
  } else {
    throw new IllegalArgumentException("Could not convert " + value.getClass());
  }
}
 
Example 15
Project: RNLearn_Project1   File: ShareTestCase.java   Source Code and License 6 votes vote down vote up
public void testShowBasicShareDialog() {
  final WritableMap content = new WritableNativeMap();
  content.putString("message", "Hello, ReactNative!");
  final WritableMap options = new WritableNativeMap();

  IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CHOOSER);
  intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
  ActivityMonitor monitor = getInstrumentation().addMonitor(intentFilter, null, true);

  getTestModule().showShareDialog(content, options);

  waitForBridgeAndUIIdle();
  getInstrumentation().waitForIdleSync();

  assertEquals(1, monitor.getHits());
  assertEquals(1, mRecordingModule.getOpened());
  assertEquals(0, mRecordingModule.getErrors());

}
 
Example 16
Project: RNLearn_Project1   File: DatePickerDialogTestCase.java   Source Code and License 6 votes vote down vote up
public void testCallback() throws Throwable {
  final WritableMap options = new WritableNativeMap();
  options.putDouble("date", getDateInMillis(2020, 5, 6));

  final DialogFragment datePickerFragment = showDialog(options);

  runTestOnUiThread(
      new Runnable() {
        @Override
        public void run() {
          ((DatePickerDialog) datePickerFragment.getDialog())
              .getButton(DialogInterface.BUTTON_POSITIVE).performClick();
        }
      });

  getInstrumentation().waitForIdleSync();
  waitForBridgeAndUIIdle();

  assertEquals(0, mRecordingModule.getErrors());
  assertEquals(1, mRecordingModule.getDates().size());
  assertEquals(2020, (int) mRecordingModule.getDates().get(0)[0]);
  assertEquals(5, (int) mRecordingModule.getDates().get(0)[1]);
  assertEquals(6, (int) mRecordingModule.getDates().get(0)[2]);
}
 
Example 17
Project: RNLearn_Project1   File: CatalystNativeJavaToJSArgumentsTestCase.java   Source Code and License 6 votes vote down vote up
public void testMapWithArrays() {
  WritableNativeMap map = new WritableNativeMap();
  WritableNativeArray a1 = new WritableNativeArray();
  WritableNativeArray a2 = new WritableNativeArray();
  a1.pushDouble(3);
  a1.pushDouble(1);
  a1.pushDouble(4);
  a2.pushDouble(1);
  a2.pushDouble(9);
  map.putArray("array1", a1);
  map.putArray("array2", a2);

  mInstance.getJSModule(TestJavaToJSArgumentsModule.class).receiveMapWithArrays(map);
  waitForBridgeAndUIIdle();
  mAssertModule.verifyAssertsAndReset();
}
 
Example 18
Project: RNLearn_Project1   File: CatalystNativeJavaToJSArgumentsTestCase.java   Source Code and License 6 votes vote down vote up
public void testMapWithNullStringValue() {
  WritableNativeMap map = new WritableNativeMap();
  map.putString("string", null);
  map.putArray("array", null);
  map.putMap("map", null);

  WritableNativeArray array = new WritableNativeArray();
  array.pushString(null);
  array.pushArray(null);
  array.pushMap(null);

  mInstance.getJSModule(TestJavaToJSArgumentsModule.class)
      .receiveMapAndArrayWithNullValues(map, array);
  waitForBridgeAndUIIdle();
  mAssertModule.verifyAssertsAndReset();
}
 
Example 19
Project: RNLearn_Project1   File: Arguments.java   Source Code and License 6 votes vote down vote up
private static void addEntry(WritableNativeMap nativeMap, String key, Object value) {
  value = makeNativeObject(value);
  if (value == null) {
    nativeMap.putNull(key);
  } else if (value instanceof Boolean) {
    nativeMap.putBoolean(key, (Boolean) value);
  } else if (value instanceof Integer) {
    nativeMap.putInt(key, (Integer) value);
  } else if (value instanceof Number) {
    nativeMap.putDouble(key, ((Number) value).doubleValue());
  } else if (value instanceof String) {
    nativeMap.putString(key, (String) value);
  } else if (value instanceof WritableNativeArray) {
    nativeMap.putArray(key, (WritableNativeArray) value);
  } else if (value instanceof WritableNativeMap) {
    nativeMap.putMap(key, (WritableNativeMap) value);
  } else {
    throw new IllegalArgumentException("Could not convert " + value.getClass());
  }
}
 
Example 20
Project: RNLearn_Project1   File: JavaModuleWrapper.java   Source Code and License 6 votes vote down vote up
@DoNotStrip
public NativeArray getConstants() {
  BaseJavaModule baseJavaModule = getModule();
  ReactMarker.logMarker(GET_CONSTANTS_START, getName());
  SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "Map constants")
    .arg("moduleName", getName())
    .flush();
  Map<String, Object> map = baseJavaModule.getConstants();
  Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);

  SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "WritableNativeMap constants")
    .arg("moduleName", getName())
    .flush();
  ReactMarker.logMarker(CONVERT_CONSTANTS_START, getName());
  WritableNativeMap writableNativeMap;
  try {
    writableNativeMap = Arguments.makeNativeMap(map);
  } finally {
    Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
  }
  WritableNativeArray array = new WritableNativeArray();
  array.pushMap(writableNativeMap);
  ReactMarker.logMarker(CONVERT_CONSTANTS_END);
  ReactMarker.logMarker(GET_CONSTANTS_END);
  return array;
}
 
Example 21
Project: RNLearn_Project1   File: ShareTestCase.java   Source Code and License 6 votes vote down vote up
public void testShowBasicShareDialog() {
  final WritableMap content = new WritableNativeMap();
  content.putString("message", "Hello, ReactNative!");
  final WritableMap options = new WritableNativeMap();

  IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CHOOSER);
  intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
  ActivityMonitor monitor = getInstrumentation().addMonitor(intentFilter, null, true);

  getTestModule().showShareDialog(content, options);

  waitForBridgeAndUIIdle();
  getInstrumentation().waitForIdleSync();

  assertEquals(1, monitor.getHits());
  assertEquals(1, mRecordingModule.getOpened());
  assertEquals(0, mRecordingModule.getErrors());

}
 
Example 22
Project: RNLearn_Project1   File: DatePickerDialogTestCase.java   Source Code and License 6 votes vote down vote up
public void testCallback() throws Throwable {
  final WritableMap options = new WritableNativeMap();
  options.putDouble("date", getDateInMillis(2020, 5, 6));

  final DialogFragment datePickerFragment = showDialog(options);

  runTestOnUiThread(
      new Runnable() {
        @Override
        public void run() {
          ((DatePickerDialog) datePickerFragment.getDialog())
              .getButton(DialogInterface.BUTTON_POSITIVE).performClick();
        }
      });

  getInstrumentation().waitForIdleSync();
  waitForBridgeAndUIIdle();

  assertEquals(0, mRecordingModule.getErrors());
  assertEquals(1, mRecordingModule.getDates().size());
  assertEquals(2020, (int) mRecordingModule.getDates().get(0)[0]);
  assertEquals(5, (int) mRecordingModule.getDates().get(0)[1]);
  assertEquals(6, (int) mRecordingModule.getDates().get(0)[2]);
}
 
Example 23
Project: RNLearn_Project1   File: CatalystNativeJavaToJSArgumentsTestCase.java   Source Code and License 6 votes vote down vote up
public void testMapWithArrays() {
  WritableNativeMap map = new WritableNativeMap();
  WritableNativeArray a1 = new WritableNativeArray();
  WritableNativeArray a2 = new WritableNativeArray();
  a1.pushDouble(3);
  a1.pushDouble(1);
  a1.pushDouble(4);
  a2.pushDouble(1);
  a2.pushDouble(9);
  map.putArray("array1", a1);
  map.putArray("array2", a2);

  mInstance.getJSModule(TestJavaToJSArgumentsModule.class).receiveMapWithArrays(map);
  waitForBridgeAndUIIdle();
  mAssertModule.verifyAssertsAndReset();
}
 
Example 24
Project: RNLearn_Project1   File: CatalystNativeJavaToJSArgumentsTestCase.java   Source Code and License 6 votes vote down vote up
public void testMapWithNullStringValue() {
  WritableNativeMap map = new WritableNativeMap();
  map.putString("string", null);
  map.putArray("array", null);
  map.putMap("map", null);

  WritableNativeArray array = new WritableNativeArray();
  array.pushString(null);
  array.pushArray(null);
  array.pushMap(null);

  mInstance.getJSModule(TestJavaToJSArgumentsModule.class)
      .receiveMapAndArrayWithNullValues(map, array);
  waitForBridgeAndUIIdle();
  mAssertModule.verifyAssertsAndReset();
}
 
Example 25
Project: RNLearn_Project1   File: CatalystNativeJavaToJSArgumentsTestCase.java   Source Code and License 6 votes vote down vote up
public void testStringWithMultibyteUTF8Characters() {
  TestJavaToJSArgumentsModule jsModule = mInstance.getJSModule(TestJavaToJSArgumentsModule.class);

  WritableNativeMap map = new WritableNativeMap();
  map.putString("two-bytes", "\u00A2");
  map.putString("three-bytes", "\u20AC");
  map.putString("four-bytes", "\uD83D\uDE1C");
  map.putString(
      "mixed",
      "\u017C\u00F3\u0142\u0107 g\u0119\u015Bl\u0105 \u6211 \uD83D\uDE0E ja\u017A\u0107");

  jsModule.receiveMapWithMultibyteUTF8CharacterString(map);
  waitForBridgeAndUIIdle();
  mAssertModule.verifyAssertsAndReset();

  WritableArray array = new WritableNativeArray();
  array.pushString("\u00A2");
  array.pushString("\u20AC");
  array.pushString("\uD83D\uDE1C");
  array.pushString(
      "\u017C\u00F3\u0142\u0107 g\u0119\u015Bl\u0105 \u6211 \uD83D\uDE0E ja\u017A\u0107");

  jsModule.receiveArrayWithMultibyteUTF8CharacterString(array);
  waitForBridgeAndUIIdle();
  mAssertModule.verifyAssertsAndReset();
}
 
Example 26
Project: react-native-camera-face-detector   File: RCTCameraModule.java   Source Code and License 6 votes vote down vote up
private void resolveImage(final File imageFile, final Promise promise, boolean addToMediaStore) {
    final WritableMap response = new WritableNativeMap();
    response.putString("path", Uri.fromFile(imageFile).toString());

    if(addToMediaStore) {
        // borrowed from react-native CameraRollManager, it finds and returns the 'internal'
        // representation of the image uri that was just saved.
        // e.g. content://media/external/images/media/123
        MediaScannerConnection.scanFile(
                _reactContext,
                new String[]{imageFile.getAbsolutePath()},
                null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                        if (uri != null) {
                            response.putString("mediaUri", uri.toString());
                        }

                        promise.resolve(response);
                    }
                });
    } else {
        promise.resolve(response);
    }
}
 
Example 27
Project: react-native-scandit   File: ReactBridgeHelpers.java   Source Code and License 6 votes vote down vote up
public static WritableMap convertJsonToMap(JSONObject jsonObject) throws JSONException {
    WritableMap map = new WritableNativeMap();

    Iterator<String> iterator = jsonObject.keys();
    while (iterator.hasNext()) {
        String key = iterator.next();
        Object value = jsonObject.get(key);
        if (value instanceof JSONObject) {
            map.putMap(key, convertJsonToMap((JSONObject) value));
        } else if (value instanceof JSONArray) {
            map.putArray(key, convertJsonToArray((JSONArray) value));
        } else if (value instanceof  Boolean) {
            map.putBoolean(key, (Boolean) value);
        } else if (value instanceof  Integer) {
            map.putInt(key, (Integer) value);
        } else if (value instanceof  Double) {
            map.putDouble(key, (Double) value);
        } else if (value instanceof String)  {
            map.putString(key, (String) value);
        } else {
            map.putString(key, value.toString());
        }
    }
    return map;
}
 
Example 28
Project: react-native-tensorflow   File: OutputConverter.java   Source Code and License 5 votes vote down vote up
public static WritableMap convert(Output output) {
    WritableNativeMap shapeMap = new WritableNativeMap();
    shapeMap.putInt("numDimensions", output.shape().numDimensions());

    WritableNativeMap map = new WritableNativeMap();
    map.putInt("index", output.index());
    map.putString("dataType", output.dataType().name());
    map.putMap("shape", shapeMap);

    return map;
}
 
Example 29
Project: react-native-twilio-chat   File: RCTConvert.java   Source Code and License 5 votes vote down vote up
public static WritableMap jsonToWritableMap(JSONObject jsonObject) {
    WritableMap writableMap = new WritableNativeMap();

    if (jsonObject == null) {
        return null;
    }


    Iterator<String> iterator = jsonObject.keys();
    if (!iterator.hasNext()) {
        return null;
    }


    try {
        while (iterator.hasNext()) {
            String key = iterator.next();
            Object value = jsonObject.get(key);
            if (value == null) {
                writableMap.putNull(key);
            } else if (value instanceof Boolean) {
                writableMap.putBoolean(key, (Boolean) value);
            } else if (value instanceof Integer) {
                writableMap.putInt(key, (Integer) value);
            } else if (value instanceof Double) {
                writableMap.putDouble(key, (Double) value);
            } else if (value instanceof String) {
                writableMap.putString(key, (String) value);
            } else if (value instanceof JSONObject) {
                writableMap.putMap(key, jsonToWritableMap((JSONObject) value));
            } else if (value instanceof JSONArray) {
                writableMap.putArray(key, jsonArrayToWritableArray((JSONArray) value));
            }
        }
    } catch (JSONException ex){
            // Do nothing and fail silently
    }

    return writableMap;
}
 
Example 30
Project: react-native-huashi-100u   File: HsOtgModule.java   Source Code and License 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    HSinterface = (HSInterface) service;
    int i = 2;
    while (i > 0) {
        i--;
        int ret = HSinterface.init();
        if (ret == 1) {
            i = 0;
            WritableMap result = new WritableNativeMap();
            String sam = HSinterface.GetSAM();
            result.putString("code", "1");
            result.putString("sam", sam);
            mPromise.resolve(result);
            return;
        } else {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
                mPromise.reject("0", "connect failed");
            }
            continue;
        }
    }
    mPromise.reject("0", "connect failed");
}
 
Example 31
Project: react-native-fast-image   File: FastImageViewManager.java   Source Code and License 5 votes vote down vote up
@Override
public void onProgress(String key, long bytesRead, long expectedLength) {
    List<ImageViewWithUrl> viewsForKey = VIEWS_FOR_URLS.get(key);
    if (viewsForKey != null) {
        for (ImageViewWithUrl view: viewsForKey) {
            WritableMap event = new WritableNativeMap();
            event.putInt("loaded", (int) bytesRead);
            event.putInt("total", (int) expectedLength);
            ThemedReactContext context = (ThemedReactContext) view.getContext();
            RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class);
            int viewId = view.getId();
            eventEmitter.receiveEvent(viewId, REACT_ON_PROGRESS_EVENT, event);
        }
    }
}
 
Example 32
Project: react-native-event-bridge   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onEventCallback(final String name, final ReadableMap info, final MSREventBridgeReceiverCallback callback) {
    Log.d(ReactConstants.TAG, this.getClass().getName() + ": Received event with callback: ".concat(name));

    final String activityClassName = this.getClass().getSimpleName();

    // Example how to load some async data
    if (name.equals(LoadDataEventName)) {
        final int count = info.getInt("count");

        // Simulate some data loading delay
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                WritableArray array = new WritableNativeArray();
                for (int i = 0; i < count; i++) {
                    array.pushString("Row " + i + " - " + activityClassName);
                }
                callback.onSuccess(array);
            }
        }, 2000);

        return;
    }

    // Emit callback
    WritableMap map = new WritableNativeMap();
    map.putString("key", "value");
    callback.onSuccess(map);
}
 
Example 33
Project: react-native-ibeacons   File: BeaconsAndroidModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getMonitoredRegions(Callback callback) {
    WritableArray array = new WritableNativeArray();
    for (Region region: mBeaconManager.getMonitoredRegions()) {
        WritableMap map = new WritableNativeMap();
        map.putString("identifier", region.getUniqueId());
        map.putString("uuid", region.getId1().toString());
        map.putInt("major", region.getId2() != null ? region.getId2().toInt() : 0);
        map.putInt("minor", region.getId3() != null ? region.getId3().toInt() : 0);
        array.pushMap(map);
    }
    callback.invoke(array);
}
 
Example 34
Project: react-native-ibeacons   File: BeaconsAndroidModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getRangedRegions(Callback callback) {
    WritableArray array = new WritableNativeArray();
    for (Region region: mBeaconManager.getRangedRegions()) {
        WritableMap map = new WritableNativeMap();
        map.putString("region", region.getUniqueId());
        map.putString("uuid", region.getId1().toString());
        array.pushMap(map);
    }
    callback.invoke(array);
}
 
Example 35
Project: react-native-ibeacons   File: BeaconsAndroidModule.java   Source Code and License 5 votes vote down vote up
private WritableMap createMonitoringResponse(Region region) {
    WritableMap map = new WritableNativeMap();
    map.putString("identifier", region.getUniqueId());
    map.putString("uuid", region.getId1().toString());
    map.putInt("major", region.getId2() != null ? region.getId2().toInt() : 0);
    map.putInt("minor", region.getId3() != null ? region.getId3().toInt() : 0);
    return map;
}
 
Example 36
Project: react-native-connectivity-status   File: RNConnectivityStatusModule.java   Source Code and License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
  final boolean locationEnabled = intent.getAction() != null
          && intent.getAction().matches(LocationManager.PROVIDERS_CHANGED_ACTION)
          && checkLocation();

  final WritableMap eventMap = new WritableNativeMap();
  eventMap.putString(EVENT_TYPE, "location");
  eventMap.putBoolean(EVENT_STATUS, locationEnabled);
  getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(RN_CONNECTIVITY_STATUS_TOPIC, eventMap);
}
 
Example 37
Project: RNLearn_Project1   File: TimePickerDialogModule.java   Source Code and License 5 votes vote down vote up
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
  if (!mPromiseResolved && getReactApplicationContext().hasActiveCatalystInstance()) {
    WritableMap result = new WritableNativeMap();
    result.putString("action", ACTION_TIME_SET);
    result.putInt("hour", hour);
    result.putInt("minute", minute);
    mPromise.resolve(result);
    mPromiseResolved = true;
  }
}
 
Example 38
Project: RNLearn_Project1   File: TimePickerDialogModule.java   Source Code and License 5 votes vote down vote up
@Override
public void onDismiss(DialogInterface dialog) {
  if (!mPromiseResolved && getReactApplicationContext().hasActiveCatalystInstance()) {
    WritableMap result = new WritableNativeMap();
    result.putString("action", ACTION_DISMISSED);
    mPromise.resolve(result);
    mPromiseResolved = true;
  }
}
 
Example 39
Project: RNLearn_Project1   File: CameraRollManager.java   Source Code and License 5 votes vote down vote up
private static void putPageInfo(Cursor photos, WritableMap response, int limit) {
  WritableMap pageInfo = new WritableNativeMap();
  pageInfo.putBoolean("has_next_page", limit < photos.getCount());
  if (limit < photos.getCount()) {
    photos.moveToPosition(limit - 1);
    pageInfo.putString(
        "end_cursor",
        photos.getString(photos.getColumnIndex(Images.Media.DATE_TAKEN)));
  }
  response.putMap("page_info", pageInfo);
}
 
Example 40
Project: RNLearn_Project1   File: CameraRollManager.java   Source Code and License 5 votes vote down vote up
private static void putEdges(
    ContentResolver resolver,
    Cursor photos,
    WritableMap response,
    int limit) {
  WritableArray edges = new WritableNativeArray();
  photos.moveToFirst();
  int idIndex = photos.getColumnIndex(Images.Media._ID);
  int mimeTypeIndex = photos.getColumnIndex(Images.Media.MIME_TYPE);
  int groupNameIndex = photos.getColumnIndex(Images.Media.BUCKET_DISPLAY_NAME);
  int dateTakenIndex = photos.getColumnIndex(Images.Media.DATE_TAKEN);
  int widthIndex = IS_JELLY_BEAN_OR_LATER ? photos.getColumnIndex(Images.Media.WIDTH) : -1;
  int heightIndex = IS_JELLY_BEAN_OR_LATER ? photos.getColumnIndex(Images.Media.HEIGHT) : -1;
  int longitudeIndex = photos.getColumnIndex(Images.Media.LONGITUDE);
  int latitudeIndex = photos.getColumnIndex(Images.Media.LATITUDE);

  for (int i = 0; i < limit && !photos.isAfterLast(); i++) {
    WritableMap edge = new WritableNativeMap();
    WritableMap node = new WritableNativeMap();
    boolean imageInfoSuccess =
        putImageInfo(resolver, photos, node, idIndex, widthIndex, heightIndex);
    if (imageInfoSuccess) {
      putBasicNodeInfo(photos, node, mimeTypeIndex, groupNameIndex, dateTakenIndex);
      putLocationInfo(photos, node, longitudeIndex, latitudeIndex);

      edge.putMap("node", node);
      edges.pushMap(edge);
    } else {
      // we skipped an image because we couldn't get its details (e.g. width/height), so we
      // decrement i in order to correctly reach the limit, if the cursor has enough rows
      i--;
    }
    photos.moveToNext();
  }
  response.putArray("edges", edges);
}