Java Code Examples for com.facebook.react.bridge.WritableArray#pushMap()

The following examples show how to use com.facebook.react.bridge.WritableArray#pushMap() . 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: ReactExoplayerView.java    From react-native-video with MIT License 6 votes vote down vote up
private WritableArray getTextTrackInfo() {
    WritableArray textTracks = Arguments.createArray();

    MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
    int index = getTrackRendererIndex(C.TRACK_TYPE_TEXT);
    if (info == null || index == C.INDEX_UNSET) {
        return textTracks;
    }

    TrackGroupArray groups = info.getTrackGroups(index);
    for (int i = 0; i < groups.length; ++i) {
         Format format = groups.get(i).getFormat(0);
         WritableMap textTrack = Arguments.createMap();
         textTrack.putInt("index", i);
         textTrack.putString("title", format.id != null ? format.id : "");
         textTrack.putString("type", format.sampleMimeType);
         textTrack.putString("language", format.language != null ? format.language : "");
         textTracks.pushMap(textTrack);
    }
    return textTracks;
}
 
Example 2
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 3
Source File: RNInstabugReactnativeModule.java    From Instabug-React-Native with MIT License 6 votes vote down vote up
private static WritableArray convertJsonToArray(JSONArray jsonArray) throws JSONException {
    WritableArray array = Arguments.createArray();

    for (int i = 0; i < jsonArray.length(); i++) {
        Object value = jsonArray.get(i);
        if (value instanceof JSONObject) {
            array.pushMap(convertJsonToMap((JSONObject) value));
        } else if (value instanceof  JSONArray) {
            array.pushArray(convertJsonToArray((JSONArray) value));
        } else if (value instanceof  Boolean) {
            array.pushBoolean((Boolean) value);
        } else if (value instanceof  Integer) {
            array.pushInt((Integer) value);
        } else if (value instanceof  Double) {
            array.pushDouble((Double) value);
        } else if (value instanceof String)  {
            array.pushString((String) value);
        }
    }
    return array;
}
 
Example 4
Source File: TouchesHelper.java    From react-native-GPay with MIT License 5 votes vote down vote up
/**
 * Creates catalyst pointers array in format that is expected by RCTEventEmitter JS module from
 * given {@param event} instance. This method use {@param reactTarget} parameter to set as a
 * target view id associated with current gesture.
 */
private static WritableArray createsPointersArray(int reactTarget, TouchEvent event) {
  WritableArray touches = Arguments.createArray();
  MotionEvent motionEvent = event.getMotionEvent();

  // Calculate the coordinates for the target view.
  // The MotionEvent contains the X,Y of the touch in the coordinate space of the root view
  // The TouchEvent contains the X,Y of the touch in the coordinate space of the target view
  // Subtracting them allows us to get the coordinates of the target view's top left corner
  // We then use this when computing the view specific touches below
  // Since only one view is actually handling even multiple touches, the values are all relative
  // to this one target view.
  float targetViewCoordinateX = motionEvent.getX() - event.getViewX();
  float targetViewCoordinateY = motionEvent.getY() - event.getViewY();

  for (int index = 0; index < motionEvent.getPointerCount(); index++) {
    WritableMap touch = Arguments.createMap();
    // pageX,Y values are relative to the RootReactView
    // the motionEvent already contains coordinates in that view
    touch.putDouble(PAGE_X_KEY, PixelUtil.toDIPFromPixel(motionEvent.getX(index)));
    touch.putDouble(PAGE_Y_KEY, PixelUtil.toDIPFromPixel(motionEvent.getY(index)));
    // locationX,Y values are relative to the target view
    // To compute the values for the view, we subtract that views location from the event X,Y
    float locationX = motionEvent.getX(index) - targetViewCoordinateX;
    float locationY = motionEvent.getY(index) - targetViewCoordinateY;
    touch.putDouble(LOCATION_X_KEY, PixelUtil.toDIPFromPixel(locationX));
    touch.putDouble(LOCATION_Y_KEY, PixelUtil.toDIPFromPixel(locationY));
    touch.putInt(TARGET_KEY, reactTarget);
    touch.putDouble(TIMESTAMP_KEY, event.getTimestampMs());
    touch.putDouble(POINTER_IDENTIFIER_KEY, motionEvent.getPointerId(index));
    touches.pushMap(touch);
  }

  return touches;
}
 
Example 5
Source File: FIRMessagingModule.java    From react-native-fcm with MIT License 5 votes vote down vote up
@ReactMethod
public void getScheduledLocalNotifications(Promise promise){
    ArrayList<Bundle> bundles = mFIRLocalMessagingHelper.getScheduledLocalNotifications();
    WritableArray array = Arguments.createArray();
    for(Bundle bundle:bundles){
        array.pushMap(Arguments.fromBundle(bundle));
    }
    promise.resolve(array);
}
 
Example 6
Source File: HeartrateHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
private void processDataSet(DataSet dataSet, WritableArray map) {

        //Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
        Format formatter = new SimpleDateFormat("EEE");
//        WritableMap stepMap = Arguments.createMap();

        for (DataPoint dp : dataSet.getDataPoints()) {
            WritableMap stepMap = Arguments.createMap();
            String day = formatter.format(new Date(dp.getStartTime(TimeUnit.MILLISECONDS)));
            int i = 0;

            for(Field field : dp.getDataType().getFields()) {
                i++;
                if (i > 1) continue;
                stepMap.putString("day", day);
                stepMap.putDouble("startDate", dp.getStartTime(TimeUnit.MILLISECONDS));
                stepMap.putDouble("endDate", dp.getEndTime(TimeUnit.MILLISECONDS));
                if (this.dataType == HealthDataTypes.TYPE_BLOOD_PRESSURE) {
                    stepMap.putDouble("value2", dp.getValue(HealthFields.FIELD_BLOOD_PRESSURE_DIASTOLIC).asFloat());
                    stepMap.putDouble("value", dp.getValue(HealthFields.FIELD_BLOOD_PRESSURE_SYSTOLIC).asFloat());
                } else {
                  stepMap.putDouble("value", dp.getValue(field).asFloat());
                }


                map.pushMap(stepMap);
            }
        }
    }
 
Example 7
Source File: RCTConvert.java    From react-native-twilio-ip-messaging with MIT License 5 votes vote down vote up
public static WritableArray Members(Member[] members) {
    WritableArray array = Arguments.createArray();

    for (Member m : members) {
        array.pushMap(Member(m));
    }

    return array;
}
 
Example 8
Source File: FontMetricsUtil.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static WritableArray getFontMetrics(CharSequence text, Layout layout, TextPaint paint, Context context) {
  DisplayMetrics dm = context.getResources().getDisplayMetrics();
  WritableArray lines = Arguments.createArray();
  // To calculate xHeight and capHeight we have to render an "x" and "T" and manually measure their height.
  // In order to get more precision than Android offers, we blow up the text size by 100 and measure it.
  // Luckily, text size affects rendering linearly, so we can do this trick.
  TextPaint paintCopy = new TextPaint(paint);
  paintCopy.setTextSize(paintCopy.getTextSize() * AMPLIFICATION_FACTOR);
  Rect capHeightBounds = new Rect();
  paintCopy.getTextBounds(CAP_HEIGHT_MEASUREMENT_TEXT, 0, CAP_HEIGHT_MEASUREMENT_TEXT.length(), capHeightBounds);
  double capHeight = capHeightBounds.height() / AMPLIFICATION_FACTOR / dm.density;
  Rect xHeightBounds = new Rect();
  paintCopy.getTextBounds(X_HEIGHT_MEASUREMENT_TEXT, 0, X_HEIGHT_MEASUREMENT_TEXT.length(), xHeightBounds);
  double xHeight = xHeightBounds.height() / AMPLIFICATION_FACTOR / dm.density;
  for (int i = 0; i < layout.getLineCount(); i++) {
    Rect bounds = new Rect();
    layout.getLineBounds(i, bounds);
    WritableMap line = Arguments.createMap();
    line.putDouble("x", layout.getLineLeft(i) / dm.density);
    line.putDouble("y", bounds.top / dm.density);
    line.putDouble("width", layout.getLineWidth(i) / dm.density);
    line.putDouble("height", bounds.height() / dm.density);
    line.putDouble("descender", layout.getLineDescent(i) / dm.density);
    line.putDouble("ascender", -layout.getLineAscent(i) / dm.density);
    line.putDouble("baseline", layout.getLineBaseline(i) / dm.density);
    line.putDouble("capHeight", capHeight);
    line.putDouble("xHeight", xHeight);
    line.putString(
        "text", text.subSequence(layout.getLineStart(i), layout.getLineEnd(i)).toString());
    lines.pushMap(line);
  }
  return lines;
}
 
Example 9
Source File: CalorieHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
private void processDataSet(DataSet dataSet, WritableArray map, boolean basalCalculation) {
    Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
    DateFormat dateFormat = DateFormat.getDateInstance();
    DateFormat timeFormat = DateFormat.getTimeInstance();
    Format formatter = new SimpleDateFormat("EEE");
    WritableMap stepMap = Arguments.createMap();


    for (DataPoint dp : dataSet.getDataPoints()) {
        Log.i(TAG, "Data point:");
        Log.i(TAG, "\tType: " + dp.getDataType().getName());
        Log.i(TAG, "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
        Log.i(TAG, "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));

        String day = formatter.format(new Date(dp.getStartTime(TimeUnit.MILLISECONDS)));
        Log.i(TAG, "Day: " + day);

        for (Field field : dp.getDataType().getFields()) {
            Log.i("History", "\tField: " + field.getName() +
                    " Value: " + dp.getValue(field));

            stepMap.putString("day", day);
            stepMap.putDouble("startDate", dp.getStartTime(TimeUnit.MILLISECONDS));
            stepMap.putDouble("endDate", dp.getEndTime(TimeUnit.MILLISECONDS));
            float basal = 0;
            if (basalCalculation) {
                try {
                    basal = getBasalAVG(dp.getEndTime(TimeUnit.MILLISECONDS));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            stepMap.putDouble("calorie", dp.getValue(field).asFloat() - basal);
            map.pushMap(stepMap);
        }
    }
}
 
Example 10
Source File: RNUnifiedContactsModule.java    From react-native-unified-contacts with MIT License 5 votes vote down vote up
@NonNull
private WritableArray getPhoneNumbersFromContact(int contactId) {
    WritableArray phoneNumbers = Arguments.createArray();

    Cursor phoneNumbersCursor = contentResolver.query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        null,
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
        null,
        null);

    while (phoneNumbersCursor.moveToNext()) {
        WritableMap phoneNumber = Arguments.createMap();

        String number           = getStringFromCursor( phoneNumbersCursor, ContactsContract.CommonDataKinds.Phone.NUMBER );
        String normalizedNumber = getStringFromCursor( phoneNumbersCursor, ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER );
        String label            = getStringFromCursor( phoneNumbersCursor, ContactsContract.CommonDataKinds.Phone.LABEL );

        int typeInt = getIntFromCursor( phoneNumbersCursor, ContactsContract.CommonDataKinds.Phone.TYPE );
        String type = String.valueOf(ContactsContract.CommonDataKinds.Phone.getTypeLabel(getCurrentActivity().getResources(), typeInt, ""));

        // NOTE: label is only set for custom Types, so to keep things consistent between iOS and Android
        // and to essentially give the user what they really want, which is the label, put type into label if it's null.
        if (label == null) label = type;

        phoneNumber.putString("stringValue", number);
        phoneNumber.putString("digits", normalizedNumber);
        phoneNumber.putString("label", label);
        phoneNumber.putString("type", type);

        phoneNumbers.pushMap(phoneNumber);
    }
    phoneNumbersCursor.close();
    return phoneNumbers;
}
 
Example 11
Source File: RCTConvert.java    From react-native-twilio-chat with MIT License 5 votes vote down vote up
public static WritableArray ChannelDescriptors(ArrayList<ChannelDescriptor> channels) {
    WritableArray array = Arguments.createArray();

    for (ChannelDescriptor c : channels) {
        array.pushMap(ChannelDescriptor(c));
    }

    return array;
}
 
Example 12
Source File: UserProfileBridge.java    From react-native-lock with MIT License 5 votes vote down vote up
private void add(UserIdentity identity, WritableArray into) {
    final WritableMap map = Arguments.createMap();
    map.putString("userId", identity.getId());
    map.putString("connection", identity.getConnection());
    map.putString("provider", identity.getProvider());
    map.putBoolean("social", identity.isSocial());
    put("profileData", identity.getProfileInfo(), map);
    into.pushMap(map);
}
 
Example 13
Source File: RNSyanImagePickerModule.java    From react-native-syan-image-picker with MIT License 5 votes vote down vote up
private void onGetResult(Intent data) {
    List<LocalMedia> tmpSelectList = PictureSelector.obtainMultipleResult(data);
    boolean isRecordSelected = cameraOptions.getBoolean("isRecordSelected");
    if (!tmpSelectList.isEmpty() && isRecordSelected) {
        selectList = tmpSelectList;
    }

    WritableArray imageList = new WritableNativeArray();
    boolean enableBase64 = cameraOptions.getBoolean("enableBase64");

    for (LocalMedia media : tmpSelectList) {
        imageList.pushMap(getImageResult(media, enableBase64));
    }
    invokeSuccessWithResult(imageList);
}
 
Example 14
Source File: SelectContactModule.java    From react-native-select-contact with MIT License 5 votes vote down vote up
private void addPhoneEntry(WritableArray phones, Cursor cursor, Activity activity) {
    String phoneNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
    int phoneType = cursor.getInt(cursor.getColumnIndex(Phone.TYPE));
    String phoneLabel = cursor.getString(cursor.getColumnIndex(Phone.LABEL));
    CharSequence typeLabel = Phone.getTypeLabel(activity.getResources(), phoneType, phoneLabel);

    WritableMap phoneEntry = Arguments.createMap();
    phoneEntry.putString("number", phoneNumber);
    phoneEntry.putString("type", String.valueOf(typeLabel));

    phones.pushMap(phoneEntry);
}
 
Example 15
Source File: RNMlKitModule.java    From react-native-firebase-mlkit with MIT License 5 votes vote down vote up
private WritableArray processCloudResult(FirebaseVisionText firebaseVisionText) {
    WritableArray data = Arguments.createArray();
    WritableMap info = Arguments.createMap();
    WritableMap coordinates = Arguments.createMap();
    List<FirebaseVisionText.TextBlock> blocks = firebaseVisionText.getTextBlocks();

    if (blocks.size() == 0) {
        return data;
    }

    for (int i = 0; i < blocks.size(); i++) {
        List<FirebaseVisionText.Line> lines = blocks.get(i).getLines();
        info = Arguments.createMap();
        coordinates = Arguments.createMap();

        Rect boundingBox = blocks.get(i).getBoundingBox();

        coordinates.putInt("top", boundingBox.top);
        coordinates.putInt("left", boundingBox.left);
        coordinates.putInt("width", boundingBox.width());
        coordinates.putInt("height", boundingBox.height());

        info.putMap("blockCoordinates", coordinates);
        info.putString("blockText", blocks.get(i).getText());

        for (int j = 0; j < lines.size(); j++) {
            List<FirebaseVisionText.Element> elements = lines.get(j).getElements();
            info.putString("lineText", lines.get(j).getText());

            for (int k = 0; k < elements.size(); k++) {
                info.putString("elementText", elements.get(k).getText());
            }
        }

        data.pushMap(info);
    }

    return data;
}
 
Example 16
Source File: InAppBillingBridge.java    From react-native-billing with MIT License 5 votes vote down vote up
@ReactMethod
public void getProductDetails(final ReadableArray productIds, final Promise promise) {
    if (bp != null) {
        try {
            ArrayList<String> productIdList = new ArrayList<>();
            for (int i = 0; i < productIds.size(); i++) {
                productIdList.add(productIds.getString(i));
            }

            List<SkuDetails> details = bp.getPurchaseListingDetails(productIdList);

            if (details != null) {
                WritableArray arr = Arguments.createArray();
                for (SkuDetails detail : details) {
                    if (detail != null) {
                        WritableMap map = Arguments.createMap();

                        map.putString("productId", detail.productId);
                        map.putString("title", detail.title);
                        map.putString("description", detail.description);
                        map.putBoolean("isSubscription", detail.isSubscription);
                        map.putString("currency", detail.currency);
                        map.putDouble("priceValue", detail.priceValue);
                        map.putString("priceText", detail.priceText);
                        arr.pushMap(map);
                    }
                }

                promise.resolve(arr);
            } else {
                promise.reject("EUNSPECIFIED", "Details was not found.");
            }
        } catch (Exception ex) {
            promise.reject("EUNSPECIFIED", "Failure on getting product details: " + ex.getMessage());
        }
    } else {
        promise.reject("EUNSPECIFIED", "Channel is not opened. Call open() on InAppBilling.");
    }
}
 
Example 17
Source File: RCTConvert.java    From react-native-twilio-chat with MIT License 5 votes vote down vote up
public static WritableArray Channels(ArrayList<Channel> channels) {
    WritableArray array = Arguments.createArray();

    for (Channel c : channels) {
        array.pushMap(Channel(c));
    }

    return array;
}
 
Example 18
Source File: RNUnifiedContactsModule.java    From react-native-unified-contacts with MIT License 4 votes vote down vote up
@NonNull
private WritableArray getPostalAddressesFromContact(int contactId) {
    WritableArray postalAddresses = Arguments.createArray();

    String   whereString = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
    String[] whereParams = new String[]{String.valueOf(contactId), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };

    Cursor postalAddressesCursor = contentResolver.query(
        ContactsContract.Data.CONTENT_URI,
        null,
        whereString,
        whereParams,
        null,
        null);

    while (postalAddressesCursor.moveToNext()) {
        WritableMap postalAddress = Arguments.createMap();

        String pobox            = getStringFromCursor( postalAddressesCursor, ContactsContract.CommonDataKinds.StructuredPostal.POBOX);
        String street           = getStringFromCursor( postalAddressesCursor, ContactsContract.CommonDataKinds.StructuredPostal.STREET);
        String neighborhood     = getStringFromCursor( postalAddressesCursor, ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD);
        String city             = getStringFromCursor( postalAddressesCursor, ContactsContract.CommonDataKinds.StructuredPostal.CITY);
        String region           = getStringFromCursor( postalAddressesCursor, ContactsContract.CommonDataKinds.StructuredPostal.REGION);
        String postcode         = getStringFromCursor( postalAddressesCursor, ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE);
        String country          = getStringFromCursor( postalAddressesCursor, ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY);
        String formattedAddress = getStringFromCursor( postalAddressesCursor, ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS);

        String label = getStringFromCursor( postalAddressesCursor, ContactsContract.CommonDataKinds.StructuredPostal.LABEL );

        int typeInt = getIntFromCursor( postalAddressesCursor, ContactsContract.CommonDataKinds.StructuredPostal.TYPE );
        String type = String.valueOf(ContactsContract.CommonDataKinds.StructuredPostal.getTypeLabel(getCurrentActivity().getResources(), typeInt, ""));

        // NOTE: label is only set for custom Types, so to keep things consistent between iOS and Android
        // and to essentially give the user what they really want, which is the label, put type into label if it's null.
        if (label == null) label = type;

        postalAddress.putString("pobox", pobox);
        postalAddress.putString("street", street);
        postalAddress.putString("neighborhood", neighborhood);
        postalAddress.putString("city", city);
        postalAddress.putString("state", region); // // TODO: Consider standardizing on "region" instead.
        postalAddress.putString("region", region); // Added in case Android devs are used to accessing it like this.
        postalAddress.putString("postalCode", postcode); // TODO: Consider standardizing on "postalCode" instead.
        postalAddress.putString("postcode", postcode); // Added in case Android devs are used to accessing it like this.
        postalAddress.putString("country", country);
        postalAddress.putString("stringValue", formattedAddress); // TODO: Consider standardizing on "formattedString" instead.
        postalAddress.putString("formattedAddress", formattedAddress); // Added in case Android devs are used to accessing it like this.
        postalAddress.putString("label", label);
        postalAddress.putString("type", type);

        postalAddresses.pushMap(postalAddress);
    }
    postalAddressesCursor.close();
    return postalAddresses;
}
 
Example 19
Source File: InAppBillingBridge.java    From react-native-billing with MIT License 4 votes vote down vote up
@ReactMethod
public void getSubscriptionDetails(final ReadableArray productIds, final Promise promise) {
    if (bp != null) {
        try {
            ArrayList<String> productIdList = new ArrayList<>();
            for (int i = 0; i < productIds.size(); i++) {
                productIdList.add(productIds.getString(i));
            }

            List<SkuDetails> details = bp.getSubscriptionListingDetails(productIdList);

            if (details != null) {
                WritableArray arr = Arguments.createArray();
                for (SkuDetails detail : details) {
                    if (detail != null) {
                        WritableMap map = Arguments.createMap();

                        map.putString("productId", detail.productId);
                        map.putString("title", detail.title);
                        map.putString("description", detail.description);
                        map.putBoolean("isSubscription", detail.isSubscription);
                        map.putString("currency", detail.currency);
                        map.putDouble("priceValue", detail.priceValue);
                        map.putString("priceText", detail.priceText);
                        map.putString("subscriptionPeriod", detail.subscriptionPeriod);
                        if (detail.subscriptionFreeTrialPeriod != null)
                            map.putString("subscriptionFreeTrialPeriod", detail.subscriptionFreeTrialPeriod);
                        map.putBoolean("haveTrialPeriod", detail.haveTrialPeriod);
                        map.putDouble("introductoryPriceValue", detail.introductoryPriceValue);
                        if (detail.introductoryPriceText != null)
                            map.putString("introductoryPriceText", detail.introductoryPriceText);
                        if (detail.introductoryPricePeriod != null)
                            map.putString("introductoryPricePeriod", detail.introductoryPricePeriod);
                        map.putBoolean("haveIntroductoryPeriod", detail.haveIntroductoryPeriod);
                        map.putInt("introductoryPriceCycles", detail.introductoryPriceCycles);
                        arr.pushMap(map);
                    }
                }

                promise.resolve(arr);
            } else {
                promise.reject("EUNSPECIFIED", "Details was not found.");
            }
        } catch (Exception ex) {
            promise.reject("EUNSPECIFIED", "Failure on getting product details: " + ex.getMessage());
        }
    } else {
        promise.reject("EUNSPECIFIED", "Channel is not opened. Call open() on InAppBilling.");
    }
}
 
Example 20
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;
}