Java Code Examples for com.facebook.react.bridge.WritableMap#putArray()

The following examples show how to use com.facebook.react.bridge.WritableMap#putArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RNUnifiedContactsModule.java    From react-native-unified-contacts with MIT License 7 votes vote down vote up
private WritableMap getContactDetailsFromContactId(int contactId) {
    WritableMap contactMap = Arguments.createMap();

    String contactIdAsString = Integer.toString(contactId);
    contactMap.putString( "identifier", contactIdAsString ); // TODO: Consider standardizing on "id" instead.
    contactMap.putInt( "id",         contactId ); // Provided for Android devs used to getting it like this. Maybe _ID is necessary as well.

    WritableMap names = getNamesFromContact(contactId);
    contactMap.merge( names );

    WritableMap thumbnail = getThumbnailFromContact(contactId);
    contactMap.merge( thumbnail );

    WritableMap organization = getOrganizationFromContact(contactId);
    contactMap.merge( organization );

    WritableArray phoneNumbers = getPhoneNumbersFromContact(contactId);
    contactMap.putArray( "phoneNumbers", phoneNumbers );

    WritableArray emailAddresses = getEmailAddressesFromContact(contactId);
    contactMap.putArray( "emailAddresses", emailAddresses );

    WritableArray postalAddresses = getPostalAddressesFromContact(contactId);
    contactMap.putArray( "postalAddresses", postalAddresses );

    WritableMap birthday = getBirthdayFromContact(contactId);
    contactMap.putMap( "birthday", birthday );

    // TODO: Instant Messenger entries.

    String note = getNoteFromContact(contactId);
    contactMap.putString( "note", note );

    return contactMap;
}
 
Example 2
Source File: MapUtil.java    From vinci with Apache License 2.0 7 votes vote down vote up
public static WritableMap toWritableMap(Map<String, Object> map) {
    WritableMap writableMap = Arguments.createMap();
    Iterator iterator = map.entrySet().iterator();

    while (iterator.hasNext()) {
        Map.Entry pair = (Map.Entry) iterator.next();
        Object value = pair.getValue();

        if (value == null) {
            writableMap.putNull((String) pair.getKey());
        } else if (value instanceof Boolean) {
            writableMap.putBoolean((String) pair.getKey(), (Boolean) value);
        } else if (value instanceof Double) {
            writableMap.putDouble((String) pair.getKey(), (Double) value);
        } else if (value instanceof Integer) {
            writableMap.putInt((String) pair.getKey(), (Integer) value);
        } else if (value instanceof String) {
            writableMap.putString((String) pair.getKey(), (String) value);
        } else if (value instanceof Map) {
            writableMap.putMap((String) pair.getKey(), MapUtil.toWritableMap((Map<String, Object>) value));
        } else if (value.getClass() != null && value.getClass().isArray()) {
            writableMap.putArray((String) pair.getKey(), ArrayUtil.toWritableArray((Object[]) value));
        }

        iterator.remove();
    }

    return writableMap;
}
 
Example 3
Source File: ReactVideoView.java    From react-native-video with MIT License 6 votes vote down vote up
public void onTimedMetaDataAvailable(MediaPlayer mp, TimedMetaData data) {
    WritableMap event = Arguments.createMap();

    try {
        String rawMeta  = new String(data.getMetaData(), "UTF-8");
        WritableMap id3 = Arguments.createMap();

        id3.putString(EVENT_PROP_METADATA_VALUE, rawMeta.substring(rawMeta.lastIndexOf("\u0003") + 1));
        id3.putString(EVENT_PROP_METADATA_IDENTIFIER, "id3/TDEN");

        WritableArray metadata = new WritableNativeArray();

        metadata.pushMap(id3);

        event.putArray(EVENT_PROP_METADATA, metadata);
        event.putDouble(EVENT_PROP_TARGET, getId());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    mEventEmitter.receiveEvent(getId(), Events.EVENT_TIMED_METADATA.toString(), event);
}
 
Example 4
Source File: Utils.java    From google-signin with MIT License 6 votes vote down vote up
static WritableMap getUserProperties(@NonNull GoogleSignInAccount acct) {
    Uri photoUrl = acct.getPhotoUrl();

    WritableMap user = Arguments.createMap();
    user.putString("id", acct.getId());
    user.putString("name", acct.getDisplayName());
    user.putString("givenName", acct.getGivenName());
    user.putString("familyName", acct.getFamilyName());
    user.putString("email", acct.getEmail());
    user.putString("photo", photoUrl != null ? photoUrl.toString() : null);

    WritableMap params = Arguments.createMap();
    params.putMap("user", user);
    params.putString("idToken", acct.getIdToken());
    params.putString("serverAuthCode", acct.getServerAuthCode());

    WritableArray scopes = Arguments.createArray();
    for (Scope scope : acct.getGrantedScopes()) {
        String scopeString = scope.toString();
        if (scopeString.startsWith("http")) {
            scopes.pushString(scopeString);
        }
    }
    params.putArray("scopes", scopes);
    return params;
}
 
Example 5
Source File: MapUtil.java    From Instabug-React-Native with MIT License 6 votes vote down vote up
public static WritableMap convertJsonToWritableMap(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, convertJsonToWritableMap((JSONObject) value));
        } else if (value instanceof  JSONArray) {
            map.putArray(key, ArrayUtil.convertJsonToWritableArray((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 6
Source File: TokenResponseFactory.java    From react-native-app-auth with MIT License 6 votes vote down vote up
public static final WritableMap tokenResponseToMap(TokenResponse response, AuthorizationResponse authResponse) {
    WritableMap map = Arguments.createMap();

    map.putString("accessToken", response.accessToken);
    map.putMap("authorizeAdditionalParameters", MapUtil.createAdditionalParametersMap(authResponse.additionalParameters));
    map.putMap("tokenAdditionalParameters", MapUtil.createAdditionalParametersMap(response.additionalParameters));
    map.putString("idToken", response.idToken);
    map.putString("refreshToken", response.refreshToken);
    map.putString("tokenType", response.tokenType);
    map.putArray("scopes", createScopeArray(authResponse.scope));

    if (response.accessTokenExpirationTime != null) {
        map.putString("accessTokenExpirationDate", DateUtil.formatTimestamp(response.accessTokenExpirationTime));
    }


    return map;
}
 
Example 7
Source File: BeaconsAndroidModule.java    From react-native-beacons-android with MIT License 6 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 8
Source File: ShowOptionsTest.java    From react-native-lock with MIT License 5 votes vote down vote up
@Test
public void testEmail() throws Exception {
    WritableMap options = new SimpleMap();

    SimpleArray connections = new SimpleArray();
    connections.pushString("email");
    connections.pushString("facebook");
    connections.pushString("twitter");
    options.putArray("connections", connections);

    ShowOptions showOptions = new ShowOptions(options);
    assertThat(showOptions.getConnectionType(), is(equalTo(LockReactModule.CONNECTION_EMAIL)));
    assertThat(Arrays.asList(showOptions.getConnections()), containsInAnyOrder("email", "twitter", "facebook"));
}
 
Example 9
Source File: ReactAztecFormattingChangeEvent.java    From react-native-aztec with GNU General Public License v2.0 5 votes vote down vote up
private WritableMap serializeEventData() {
    WritableMap eventData = Arguments.createMap();
    eventData.putInt("target", getViewTag());
    WritableArray newFormats = Arguments.fromArray(mFormats);
    eventData.putArray("formats", newFormats);
    return eventData;
}
 
Example 10
Source File: ShowOptionsTest.java    From react-native-lock with MIT License 5 votes vote down vote up
@Test
public void testSms() throws Exception {
    WritableMap options = new SimpleMap();

    SimpleArray connections = new SimpleArray();
    connections.pushString("sms");
    connections.pushString("facebook");
    connections.pushString("twitter");
    options.putArray("connections", connections);

    ShowOptions showOptions = new ShowOptions(options);
    assertThat(showOptions.getConnectionType(), is(equalTo(LockReactModule.CONNECTION_SMS)));
    assertThat(Arrays.asList(showOptions.getConnections()), containsInAnyOrder("sms", "twitter", "facebook"));
}
 
Example 11
Source File: Utils.java    From react-native-update with MIT License 5 votes vote down vote up
public static WritableMap convertJsonObjectToWriteable(JSONObject jsonObj) {
    WritableMap map = Arguments.createMap();
    Iterator<String> it = jsonObj.keys();
    while(it.hasNext()){
        String key = it.next();
        Object obj = null;
        try {
            obj = jsonObj.get(key);
        } catch (JSONException jsonException) {
            // Should not happen.
            throw new RuntimeException("Key " + key + " should exist in " + jsonObj.toString() + ".", jsonException);
        }

        if (obj instanceof JSONObject)
            map.putMap(key, convertJsonObjectToWriteable((JSONObject) obj));
        else if (obj instanceof JSONArray)
            map.putArray(key, convertJsonArrayToWriteable((JSONArray) obj));
        else if (obj instanceof String)
            map.putString(key, (String) obj);
        else if (obj instanceof Double)
            map.putDouble(key, (Double) obj);
        else if (obj instanceof Integer)
            map.putInt(key, (Integer) obj);
        else if (obj instanceof Boolean)
            map.putBoolean(key, (Boolean) obj);
        else if (obj == null)
            map.putNull(key);
        else
            throw new RuntimeException("Unrecognized object: " + obj);
    }

    return map;
}
 
Example 12
Source File: Peripheral.java    From react-native-ble-manager with Apache License 2.0 5 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
	super.onCharacteristicChanged(gatt, characteristic);
	try {
		String charString = characteristic.getUuid().toString();
		String service = characteristic.getService().getUuid().toString();
		NotifyBufferContainer buffer = this.bufferedCharacteristics
				.get(this.bufferedCharacteristicsKey(service, charString));
		byte[] dataValue = characteristic.getValue();
		if (buffer != null) {
			buffer.put(dataValue);
			// Log.d(BleManager.LOG_TAG, "onCharacteristicChanged-buffering: " +
			// buffer.size() + " from peripheral: " + device.getAddress());

			if (buffer.size().equals(buffer.maxCount)) {
				Log.d(BleManager.LOG_TAG, "onCharacteristicChanged sending buffered data " + buffer.size());

				// send'm and reset
				dataValue = buffer.items.array();
				buffer.resetBuffer();
			} else {
				return;
			}
		}
		Log.d(BleManager.LOG_TAG, "onCharacteristicChanged: " + BleManager.bytesToHex(dataValue)
				+ " from peripheral: " + device.getAddress());
		WritableMap map = Arguments.createMap();
		map.putString("peripheral", device.getAddress());
		map.putString("characteristic", charString);
		map.putString("service", service);
		map.putArray("value", BleManager.bytesToWritableArray(dataValue));
		sendEvent("BleManagerDidUpdateValueForCharacteristic", map);

	} catch (Exception e) {
		Log.d(BleManager.LOG_TAG, "onCharacteristicChanged ERROR: " + e.toString());
	}
}
 
Example 13
Source File: ArgumentUtils.java    From react-native-pjsip with GNU General Public License v3.0 5 votes vote down vote up
private static WritableMap fromJsonObject(JsonObject object) {
    WritableMap result = new WritableNativeMap();

    for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
        Object value = fromJson(entry.getValue());

        if (value instanceof WritableMap) {
            result.putMap(entry.getKey(), (WritableMap) value);
        } else if (value instanceof WritableArray) {
            result.putArray(entry.getKey(), (WritableArray) value);
        } else if (value instanceof String) {
            result.putString(entry.getKey(), (String) value);
        } else if (value instanceof LazilyParsedNumber) {
            result.putInt(entry.getKey(), ((LazilyParsedNumber) value).intValue());
        } else if (value instanceof Integer) {
            result.putInt(entry.getKey(), (Integer) value);
        } else if (value instanceof Double) {
            result.putDouble(entry.getKey(), (Double) value);
        } else if (value instanceof Boolean) {
            result.putBoolean(entry.getKey(), (Boolean) value);
        } else {
            Log.d("ArgumentUtils", "Unknown type: " + value.getClass().getName());
            result.putNull(entry.getKey());
        }
    }

    return result;
}
 
Example 14
Source File: Utils.java    From magnet-client with Mozilla Public License 2.0 4 votes vote down vote up
@Nullable
public static WritableMap jsonToWritableMap(JSONObject jsonObject) {
    WritableMap writableMap = new WritableNativeMap();

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

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

    while (iterator.hasNext()) {
        String key = iterator.next();

        try {
            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 15
Source File: RCTCameraViewFinder.java    From react-native-camera-face-detector with MIT License 4 votes vote down vote up
@Override
protected Void doInBackground(Void... ignored) {
    if (isCancelled()) {
        return null;
    }

    Camera.Size size = camera.getParameters().getPreviewSize();

    int width = size.width;
    int height = size.height;

    // rotate for zxing if orientation is portrait
    if (RCTCamera.getInstance().getActualDeviceOrientation() == 0) {
        byte[] rotated = new byte[imageData.length];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                rotated[x * height + height - y - 1] = imageData[x + y * width];
            }
        }
        width = size.height;
        height = size.width;
        imageData = rotated;
    }

    try {
        PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(imageData, width, height, 0, 0, width, height, false);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result = _multiFormatReader.decodeWithState(bitmap);

        ReactContext reactContext = RCTCameraModule.getReactContextSingleton();
        WritableMap event = Arguments.createMap();
        WritableArray resultPoints = Arguments.createArray();
        ResultPoint[] points = result.getResultPoints();
        if(points != null) {
            for (ResultPoint point : points) {
                WritableMap newPoint = Arguments.createMap();
                newPoint.putString("x", String.valueOf(point.getX()));
                newPoint.putString("y", String.valueOf(point.getY()));
                resultPoints.pushMap(newPoint);
            }
        }

        event.putArray("bounds", resultPoints);
        event.putString("data", result.getText());
        event.putString("type", result.getBarcodeFormat().toString());
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("CameraBarCodeReadAndroid", event);

    } catch (Throwable t) {
        // meh
    } finally {
        _multiFormatReader.reset();
        RCTCameraViewFinder.barcodeScannerTaskLock = false;
        return null;
    }
}
 
Example 16
Source File: SQLitePlugin.java    From react-native-sqlite-storage with MIT License 4 votes vote down vote up
/**
 * Get rows results from query cursor.
 *
 * @return results in string form
 */
private WritableMap executeSqlStatementNDK(String query, ReadableArray queryArgs,
                                           CallbackContext cbc) throws Exception {
    WritableMap rowsResult = Arguments.createMap();

    boolean hasRows;

    SQLiteStatement myStatement = null;
    try {
        try {
            myStatement = mydb.prepareStatement(query);
            if (queryArgs != null) {
                for (int i = 0; i < queryArgs.size(); ++i) {
                    ReadableType type = queryArgs.getType(i);
                    if (type == ReadableType.Number){
                        double tmp = queryArgs.getDouble(i);
                        if (tmp == (long) tmp) {
                            myStatement.bindLong(i + 1, (long) tmp);
                        } else {
                            myStatement.bindDouble(i + 1, tmp);
                        }
                    } else if (queryArgs.isNull(i)) {
                        myStatement.bindNull(i + 1);
                    } else {
                        myStatement.bindTextNativeString(i + 1, SQLitePluginConverter.getString(queryArgs,i,""));
                    }
                }
            }

            hasRows = myStatement.step();
        } catch (Exception ex) {
            FLog.e(TAG, "SQLitePlugin.executeSql[Batch]() failed", ex);
            throw ex;
        }

        // If query result has rows
        if (hasRows) {
            WritableArray rowsArrayResult = Arguments.createArray();
            String key;
            int colCount = myStatement.getColumnCount();

            // Build up JSON result object for each row
            do {
                WritableMap row = Arguments.createMap();
                for (int i = 0; i < colCount; ++i) {
                    key = myStatement.getColumnName(i);

                    switch (myStatement.getColumnType(i)) {
                        case SQLColumnType.NULL:
                            row.putNull(key);
                            break;

                        case SQLColumnType.REAL:
                            row.putDouble(key, myStatement.getColumnDouble(i));
                            break;

                        case SQLColumnType.INTEGER:
                            row.putDouble(key, myStatement.getColumnLong(i));
                            break;

                        case SQLColumnType.BLOB:
                        case SQLColumnType.TEXT:
                        default:
                            row.putString(key, myStatement.getColumnTextNativeString(i));
                    }

                }

                rowsArrayResult.pushMap(row);
            } while (myStatement.step());

            rowsResult.putArray("rows", rowsArrayResult);
        }
    } finally {
        if (myStatement != null) {
            myStatement.dispose();
        }
    }

    return rowsResult;
}
 
Example 17
Source File: Utils.java    From photo-viewer with Apache License 2.0 4 votes vote down vote up
@Nullable
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;
    }

    while (iterator.hasNext()) {
        String key = iterator.next();

        try {
            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 18
Source File: FirestackUtils.java    From react-native-firestack with MIT License 4 votes vote down vote up
public static WritableMap dataSnapshotToMap(String name, 
  String path, 
  DataSnapshot dataSnapshot) {
    WritableMap data = Arguments.createMap();

    data.putString("key", dataSnapshot.getKey());
    data.putBoolean("exists", dataSnapshot.exists());
    data.putBoolean("hasChildren", dataSnapshot.hasChildren());

    data.putDouble("childrenCount", dataSnapshot.getChildrenCount());
    if (!dataSnapshot.hasChildren()) {
      Object value = dataSnapshot.getValue();
      String type = value!=null ? value.getClass().getName() : "";
      switch (type) {
        case "java.lang.Boolean":
          data.putBoolean("value", (Boolean)value);
          break;
        case "java.lang.Long":
          Long longVal = (Long) value;
          data.putDouble("value", (double)longVal);
          break;
        case "java.lang.Double":
          data.putDouble("value", (Double) value);
          break;
        case "java.lang.String":
          data.putString("value",(String) value);
          break;
        default:
          data.putString("value", null);
      }
    } else{
      WritableMap valueMap = FirestackUtils.castSnapshotValue(dataSnapshot);
      data.putMap("value", valueMap);
    }

    // Child keys
    WritableArray childKeys = FirestackUtils.getChildKeys(dataSnapshot);
    data.putArray("childKeys", childKeys);

    Object priority = dataSnapshot.getPriority();
    if (priority == null) {
      data.putString("priority", null);
    } else {
      data.putString("priority", priority.toString());
    }

    WritableMap eventMap = Arguments.createMap();
    eventMap.putString("eventName", name);
    eventMap.putMap("snapshot", data);
    eventMap.putString("path", path);
    return eventMap;
}
 
Example 19
Source File: RNDataWedgeIntentsModule.java    From react-native-datawedge-intents with MIT License 4 votes vote down vote up
@Override
public void update(Observable observable, Object data) 
{            
  Intent intent = (Intent)data;

  if (intent.hasExtra("v2API"))
  {
      Bundle intentBundle = intent.getExtras();
      intentBundle.remove("com.symbol.datawedge.decode_data"); //  fb converter cannot cope with byte arrays
      intentBundle.remove("com.motorolasolutions.emdk.datawedge.decode_data"); //  fb converter cannot cope with byte arrays
      WritableMap map = Arguments.fromBundle(intentBundle);
      sendEvent(this.reactContext, "datawedge_broadcast_intent", map);
  }

  String action = intent.getAction();
  if (action.equals(ACTION_ENUMERATEDLISET)) 
  {
      Bundle b = intent.getExtras();
      String[] scanner_list = b.getStringArray(KEY_ENUMERATEDSCANNERLIST);
      WritableArray userFriendlyScanners = new WritableNativeArray();
      for (int i = 0; i < scanner_list.length; i++)
      {
          userFriendlyScanners.pushString(scanner_list[i]);
      }
      try
      {
        WritableMap enumeratedScannersObj = new WritableNativeMap();
        enumeratedScannersObj.putArray("Scanners", userFriendlyScanners);
        sendEvent(this.reactContext, "enumerated_scanners", enumeratedScannersObj);
      }
      catch (Exception e)
      {
          Toast.makeText(this.reactContext, "Error returning scanners", Toast.LENGTH_LONG).show();
          e.printStackTrace();
      }
  }
  else
  {
      //  Intent from the scanner (barcode has been scanned)
      String decodedSource = intent.getStringExtra(RECEIVED_SCAN_SOURCE);
      String decodedData = intent.getStringExtra(RECEIVED_SCAN_DATA);
      String decodedLabelType = intent.getStringExtra(RECEIVED_SCAN_TYPE);

      WritableMap scanData = new WritableNativeMap();
      scanData.putString("source", decodedSource);
      scanData.putString("data", decodedData);
      scanData.putString("labelType", decodedLabelType);
      sendEvent(this.reactContext, "barcode_scan", scanData);
  }
}
 
Example 20
Source File: RNMlKitModule.java    From react-native-firebase-mlkit with MIT License 4 votes vote down vote up
private WritableArray processFaceDetectionResult(List<FirebaseVisionFace> firebaseVisionFaces){
    WritableArray data = Arguments.createArray();

    if(firebaseVisionFaces.size() > 0){
        WritableMap info = Arguments.createMap();
        for (FirebaseVisionFace face : firebaseVisionFaces){
            info = Arguments.createMap();
            //face bounding box
            Rect faceBounding = face.getBoundingBox();

            WritableMap faceBox = Arguments.createMap();
            faceBox.putInt("top", faceBounding.top);
            faceBox.putInt("right", faceBounding.right);
            faceBox.putInt("bottom", faceBounding.bottom);
            faceBox.putInt("left", faceBounding.left);

            info.putMap("faceBoundingRect", faceBox);

            // If classification was enabled:
            if (face.getSmilingProbability() != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
                float smileProb = face.getSmilingProbability();
                info.putDouble("smileProbability", (double)smileProb);
            }
            if (face.getRightEyeOpenProbability() != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
                float rightEyeOpenProb = face.getRightEyeOpenProbability();
                info.putDouble("rightEyeOpenProbability", (double)rightEyeOpenProb);
            }

            // If face tracking was enabled:
            if (face.getTrackingId() != FirebaseVisionFace.INVALID_ID) {
                int id = face.getTrackingId();
                info.putInt("faceTrackingId", id);
            }
            //eyes
            info.putArray("leftEyeContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.LEFT_EYE));
            info.putArray("rightEyeContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.RIGHT_EYE));
            //face
            info.putArray("faceContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.FACE));
            //lower lip
            info.putArray("lowerLipBottomContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.LOWER_LIP_BOTTOM));
            info.putArray("lowerLipBottomContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.LOWER_LIP_TOP));
            //upper lip
            info.putArray("upperLipTopContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.UPPER_LIP_TOP));
            info.putArray("upperLipBottomContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.UPPER_LIP_BOTTOM));
            //nose
            info.putArray("noiseBottomContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.NOSE_BOTTOM));
            info.putArray("noiseBridgeContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.NOSE_BRIDGE));
            //left eyebrow
            info.putArray("leftEyeBrowBottomContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.LEFT_EYEBROW_BOTTOM));
            info.putArray("leftEyeBrowTopContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.LEFT_EYEBROW_TOP));
            // right eyebrow
            info.putArray("rightEyeBrowBottomContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.RIGHT_EYEBROW_BOTTOM));
            info.putArray("rightEyeBrowTopContourPoints", Utils.getContourPointsWritableArray(face, FirebaseVisionFaceContour.RIGHT_EYEBROW_TOP));



            data.pushMap(info);
        }
    }

    return data;
}