Java Code Examples for com.facebook.react.bridge.Promise.reject()

The following are Jave code examples for showing how to use reject() of the com.facebook.react.bridge.Promise class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: RNLearn_Project1   File: ShareModule.java   Source Code and License Vote up 7 votes
/**
 * Open a chooser dialog to send text content to other apps.
 *
 * Refer http://developer.android.com/intl/ko/training/sharing/send.html
 *
 * @param content the data to send
 * @param dialogTitle the title of the chooser dialog
 */
@ReactMethod
public void share(ReadableMap content, String dialogTitle, Promise promise) {
  if (content == null) {
    promise.reject(ERROR_INVALID_CONTENT, "Content cannot be null");
    return;
  }

  try {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setTypeAndNormalize("text/plain");

    if (content.hasKey("title")) {
      intent.putExtra(Intent.EXTRA_SUBJECT, content.getString("title"));
    }

    if (content.hasKey("message")) {
      intent.putExtra(Intent.EXTRA_TEXT, content.getString("message"));
    }

    Intent chooser = Intent.createChooser(intent, dialogTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    Activity currentActivity = getCurrentActivity();
    if (currentActivity != null) {
      currentActivity.startActivity(chooser);
    } else {
      getReactApplicationContext().startActivity(chooser);
    }
    WritableMap result = Arguments.createMap();
    result.putString("action", ACTION_SHARED);
    promise.resolve(result);
  } catch (Exception e) {
    promise.reject(ERROR_UNABLE_TO_OPEN_DIALOG, "Failed to open share dialog");
  }
}
 
Example 2
Project: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   Source Code and License Vote up 7 votes
@ReactMethod 
public void getAvailableLocales(Promise promise) {
	if(notReady(promise)) return;
	
	try {
		WritableArray localeList = Arguments.createArray();
		Locale[] localesArray = Locale.getAvailableLocales();
		for(Locale locale: localesArray) {
			int isAvailable = tts.isLanguageAvailable(locale);
			if(isAvailable == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
				WritableMap newLocale = returnMapForLocale(locale);
				localeList.pushMap(newLocale);
			}
		}

		promise.resolve(localeList);
	} catch(Exception e) {
		promise.reject("error", "Unable to retrieve locales for getAvailableLocales()", e);
	}
}
 
Example 3
Project: RNLearn_Project1   File: ShareModule.java   Source Code and License Vote up 6 votes
/**
 * Open a chooser dialog to send text content to other apps.
 *
 * Refer http://developer.android.com/intl/ko/training/sharing/send.html
 *
 * @param content the data to send
 * @param dialogTitle the title of the chooser dialog
 */
@ReactMethod
public void share(ReadableMap content, String dialogTitle, Promise promise) {
  if (content == null) {
    promise.reject(ERROR_INVALID_CONTENT, "Content cannot be null");
    return;
  }

  try {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setTypeAndNormalize("text/plain");

    if (content.hasKey("title")) {
      intent.putExtra(Intent.EXTRA_SUBJECT, content.getString("title"));
    }

    if (content.hasKey("message")) {
      intent.putExtra(Intent.EXTRA_TEXT, content.getString("message"));
    }

    Intent chooser = Intent.createChooser(intent, dialogTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    Activity currentActivity = getCurrentActivity();
    if (currentActivity != null) {
      currentActivity.startActivity(chooser);
    } else {
      getReactApplicationContext().startActivity(chooser);
    }
    WritableMap result = Arguments.createMap();
    result.putString("action", ACTION_SHARED);
    promise.resolve(result);
  } catch (Exception e) {
    promise.reject(ERROR_UNABLE_TO_OPEN_DIALOG, "Failed to open share dialog");
  }
}
 
Example 4
Project: react-native-datecs-printer   File: RNDatecsPrinterModule.java   Source Code and License Vote up 6 votes
/**
    * Disconnect printer
    *
    * @param promise
    */
@ReactMethod
public void disconnect(Promise promise){
	try {
		mmSocket.close();

		if (mPrinter != null) {
			mPrinter.release();
		}

		if (mProtocolAdapter != null) {
			mProtocolAdapter.release();
		}

		if(promise != null) promise.resolve("DISCONNECTED");
	} catch (Exception e) {
		if(promise != null) promise.reject("Erro: " + e.getMessage());
	}
}
 
Example 5
Project: react-native-geth   File: RNGethModule.java   Source Code and License Vote up 6 votes
/**
 * Create and send transaction.
 *
 * @param passphrase Passphrase
 * @param nonce      Account nonce (use -1 to use last known nonce)
 * @param toAddress  Address destination
 * @param amount     Amount
 * @param gasLimit   Gas limit
 * @param gasPrice   Gas price
 * @param data
 * @param promise    Promise
 * @return Return String transaction
 */
@ReactMethod
public void createAndSendTransaction(String passphrase, double nonce, String toAddress,
                                     double amount, double gasLimit, double gasPrice,
                                     String data, Promise promise) {
    try {
        Account acc = GethHolder.getAccount();
        Address fromAddress = acc.getAddress();
        BigInt chain = new BigInt(GethHolder.getNodeConfig().getEthereumNetworkID());
        Context ctx = new Context();

        if (nonce == -1) {
          nonce = GethHolder.getNode().getEthereumClient().getPendingNonceAt(ctx, fromAddress);
        }

        Transaction tx = new Transaction(
                (long) nonce,
                new Address(toAddress),
                new BigInt((long) amount),
                new BigInt((long) gasLimit),
                new BigInt((long) gasPrice),
                data.getBytes("UTF8"));

        // Sign a transaction with a single authorization
        Transaction signed = GethHolder.getKeyStore().signTxPassphrase(acc, passphrase, tx, chain);
        // Send it out to the network.
        GethHolder.getNode().getEthereumClient().sendTransaction(ctx, signed);
        promise.resolve(tx.toString());
    } catch (Exception e) {
        promise.reject(NEW_TRANSACTION_ERROR, e);
    }
}
 
Example 6
Project: react-native-tensorflow   File: RNTensorFlowGraphModule.java   Source Code and License Vote up 6 votes
@ReactMethod
public void toGraphDef(String id, Promise promise) {
    try {
        Graph graph = graphs.get(id);
        promise.resolve(Base64.encodeToString(graph.toGraphDef(), Base64.DEFAULT));
    } catch (Exception e) {
        promise.reject(e);
    }
}
 
Example 7
Project: react-native-tensorflow   File: RNTensorFlowGraphModule.java   Source Code and License Vote up 6 votes
@ReactMethod
public void close(String id, Promise promise) {
    try {
        Graph graph = graphs.get(id);
        graph.close();
        promise.resolve(true);
    } catch (Exception e) {
        promise.reject(e);
    }
}
 
Example 8
Project: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   Source Code and License Vote up 5 votes
@ReactMethod
public void speak(String utterance, String queueMode, Promise promise) {
	if(notReady(promise)) return;

	if(IS_DUCKING) {
		int amResult = audioManager.requestAudioFocus(afChangeListener, 
														AudioManager.STREAM_MUSIC, 
														AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);

		if(amResult != AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
			promise.reject("error", "Android AudioManager error, failed to request audio focus");
	}

	String utteranceId = Integer.toString(utterance.hashCode());

	int mode = TextToSpeech.QUEUE_ADD;
	if(queueMode.equals("ADD")) 
		mode = TextToSpeech.QUEUE_ADD;
	else if(queueMode.equals("FLUSH")) 
		mode = TextToSpeech.QUEUE_FLUSH;

	int speakResult = speak(utterance, mode, utteranceId);
	if(speakResult == TextToSpeech.SUCCESS) {
		promise.resolve(utteranceId);
	} else {
		promise.reject("error", "Unable to play. Error at speak(utterance, queueMode)");
	}
}
 
Example 9
Project: react-native-filesystem-v1   File: RNFileSystem.java   Source Code and License Vote up 5 votes
@ReactMethod
public void writeToFile(String relativePath, String content, boolean isAppend, String storage, Promise promise) {
  try {
    writeToFile(relativePath, content, isAppend, Storage.valueOf(storage));
    promise.resolve(true);
  } catch (IOException e) {
    promise.reject("ERROR", e.getMessage());
  }
}
 
Example 10
Project: react-native-sunmi-inner-printer   File: SunmiInnerPrinterModule.java   Source Code and License Vote up 5 votes
/**
 * 获取打印机板序列号
 */
@ReactMethod
public void getPrinterSerialNo(final Promise p) {
    try {
        p.resolve(getPrinterSerialNo());
    } catch (Exception e) {
        Log.i(TAG, "ERROR: " + e.getMessage());
        p.reject("" + 0, e.getMessage());
    }
}
 
Example 11
Project: react-native-cafe-bazaar   File: CafeBazaar.java   Source Code and License Vote up 5 votes
@ReactMethod
public void consume(String sku,final Promise promise){
  if(userInvo!=null){
    if(userInvo.hasPurchase(sku)){
      mHelper.consumeAsync(userInvo.getPurchase(sku),
      new IabHelper.OnConsumeFinishedListener() {
      public void onConsumeFinished(Purchase purchase, IabResult result) {
        WritableMap params = Arguments.createMap();
         if (result.isSuccess()) {
            // provision the in-app purchase to the user
            promise.resolve(gson.toJson(purchase));
         }
         else {
            // handle error
            promise.reject(E_CONSUME_FAILURE,result.getMessage());
         }
        }
     });
    }
    else{
      promise.reject(E_CONSUME_ERROR,"user did not purchase item");
    }
  }
  else{
    promise.reject(E_CONSUME_INITIAL,"inventory not loaded!");
  }
}
 
Example 12
Project: react-native-camera-face-detector   File: RCTCameraModule.java   Source Code and License Vote up 5 votes
private void record(final ReadableMap options, final Promise promise) {
    if (mRecordingPromise != null) {
        return;
    }

    mCamera = RCTCamera.getInstance().acquireCameraInstance(options.getInt("type"));
    if (mCamera == null) {
        promise.reject(new RuntimeException("No camera found."));
        return;
    }

    Throwable prepareError = prepareMediaRecorder(options);
    if (prepareError != null) {
        promise.reject(prepareError);
        return;
    }

    try {
        mMediaRecorder.start();
        MRStartTime =  System.currentTimeMillis();
        mRecordingOptions = options;
        mRecordingPromise = promise;  // only got here if mediaRecorder started
    } catch (Exception ex) {
        Log.e(TAG, "Media recorder start error.", ex);
        promise.reject(ex);
    }
}
 
Example 13
Project: RNLearn_Project1   File: PermissionsModule.java   Source Code and License Vote up 5 votes
/**
 * Check whether the app should display a message explaining why a certain permission is needed.
 * successCallback is called with true if the app should display a message, false otherwise.
 * This message is only displayed if the user has revoked this permission once before, and if the
 * permission dialog will be shown to the user (the user can choose to not be shown that dialog
 * again). For devices before Android M, this always returns false.
 * See {@link Activity#shouldShowRequestPermissionRationale}.
 */
@ReactMethod
public void shouldShowRequestPermissionRationale(final String permission, final Promise promise) {
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
    promise.resolve(false);
    return;
  }
  try {
    promise.resolve(getPermissionAwareActivity().shouldShowRequestPermissionRationale(permission));
  } catch (IllegalStateException e) {
    promise.reject(ERROR_INVALID_ACTIVITY, e);
  }
}
 
Example 14
Project: RNLearn_Project1   File: NetInfoModule.java   Source Code and License Vote up 5 votes
@ReactMethod
public void getCurrentConnectivity(Promise promise) {
  if (mNoNetworkPermission) {
    promise.reject(ERROR_MISSING_PERMISSION, MISSING_PERMISSION_MESSAGE, null);
    return;
  }
  promise.resolve(createConnectivityEventMap());
}
 
Example 15
Project: react-native-secure-key-store   File: RNSecureKeyStoreModule.java   Source Code and License Vote up 5 votes
@ReactMethod
public void get(String alias, Promise promise) {
  try {
    promise.resolve(getPlainText(alias));
  } catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
    promise.reject("404", "{\"code\":404,\"api-level\":" + Build.VERSION.SDK_INT + ",\"message\":" + fnfe.getMessage() + "}", fnfe);
  } catch (Exception e) {
    e.printStackTrace();
    Log.e(Constants.TAG, "Exception: " + e.getMessage());
    promise.reject("{\"code\":1,\"api-level\":" + Build.VERSION.SDK_INT + ",\"message\":" + e.getMessage() + "}");
  }
}
 
Example 16
Project: react-native-icon-badge   File: RNIconBadgeModule.java   Source Code and License Vote up 5 votes
@ReactMethod
public void getBadgeNumber(Promise promise) {
    try {
        promise.resolve(getBadge());
    } catch (Exception e) {
        e.printStackTrace();
        promise.reject("can not get badge number due to an exception occurs", e);
    }
}
 
Example 17
Project: react-native-geth   File: RNGethModule.java   Source Code and License Vote up 5 votes
/**
 * Sets the default account at the given index in the listAccounts.
 *
 * @param accID   index in the listAccounts
 * @param promise Promise
 * @return Return true if sets.
 */
@ReactMethod
public void setAccount(Integer accID, Promise promise) {
    try {
        Account acc = GethHolder.getKeyStore().getAccounts().get(accID);
        GethHolder.setAccount(acc);
        //accounts.set(0, acc);
        promise.resolve(true);
    } catch (Exception e) {
        promise.reject(SET_ACCOUNT_ERROR, e);
    }
}
 
Example 18
Project: react-native-threads   File: RNThreadModule.java   Source Code and License Vote up 5 votes
@ReactMethod
public void startThread(final String jsFileName, final Promise promise) {
  Log.d(TAG, "Starting web thread - " + jsFileName);

  String jsFileSlug = jsFileName.contains("/") ? jsFileName.replaceAll("/", "_") : jsFileName;

  JSBundleLoader bundleLoader = getDevSupportManager().getDevSupportEnabled()
          ? createDevBundleLoader(jsFileName, jsFileSlug)
          : createReleaseBundleLoader(jsFileName, jsFileSlug);

  try {
    ArrayList<ReactPackage> threadPackages = new ArrayList<ReactPackage>(Arrays.asList(additionalThreadPackages));
    threadPackages.add(0, new ThreadBaseReactPackage(getReactInstanceManager()));

    ReactContextBuilder threadContextBuilder = new ReactContextBuilder(getReactApplicationContext())
            .setJSBundleLoader(bundleLoader)
            .setDevSupportManager(getDevSupportManager())
            .setReactInstanceManager(getReactInstanceManager())
            .setReactPackages(threadPackages);

    JSThread thread = new JSThread(jsFileSlug);
    thread.runFromContext(
            getReactApplicationContext(),
            threadContextBuilder
    );
    threads.put(thread.getThreadId(), thread);
    promise.resolve(thread.getThreadId());
  } catch (Exception e) {
    promise.reject(e);
    getDevSupportManager().handleException(e);
  }
}
 
Example 19
Project: react-native-pgp   File: Module.java   Source Code and License Vote up 5 votes
@ReactMethod
public void generateKeyPair(final String userId, final int numBits, final String passphrase, Promise promise) {
  Log.d("ReactNativePGP", "generateKeyPair");
  try {
    WritableMap resultMap = Arguments.createMap();
    PGPKeyRingGenerator keyGenerator = PGPUtils.generateKeyRingGenerator(userId, numBits, passphrase.toCharArray());

    // public key
    PGPPublicKeyRing publicKeyRing              = keyGenerator.generatePublicKeyRing();
    ByteArrayOutputStream publicKeyOutputStream = new ByteArrayOutputStream();
    ArmoredOutputStream armoredPubOutputStream  = new ArmoredOutputStream(publicKeyOutputStream);

    publicKeyRing.encode(armoredPubOutputStream);
    armoredPubOutputStream.close();
    resultMap.putString("publicKey", publicKeyOutputStream.toString("UTF-8"));

    // private key
    PGPSecretKeyRing secretKeyRing               = keyGenerator.generateSecretKeyRing();
    ByteArrayOutputStream privateKeyOutputStream = new ByteArrayOutputStream();
    ArmoredOutputStream armoredPrivOutputStream  = new ArmoredOutputStream(privateKeyOutputStream);

    secretKeyRing.encode(armoredPrivOutputStream);
    armoredPrivOutputStream.close();
    resultMap.putString("privateKey", privateKeyOutputStream.toString("UTF-8"));
    resultMap.putString("fingerPrint", Utils.bytesToHex(secretKeyRing.getPublicKey().getFingerprint()));

    promise.resolve(resultMap);
  } catch(Exception e) {
    promise.reject(new Exception(e.getMessage()));
  }
}
 
Example 20
Project: react-native-huashi-100u   File: HsOtgModule.java   Source Code and License Vote up 4 votes
@ReactMethod
    public void read(Promise promise) {
        if (HSinterface == null){
            promise.reject("-1", "init failed");
            return;
        }
        int ret = HSinterface.ReadCard();
        if (ret == 1){
            //成功
            byte[] fp = new byte[1024];
            fp = HsOtgService.ic.getFpDate();
            String m_FristPFInfo = "";
            String m_SecondPFInfo = "";
            WritableMap result = new WritableNativeMap();
            result.putString("code", ret+"");
            if (fp[4] == (byte)0x01) {
                m_FristPFInfo = GetFPcode(fp[5])+","+fp[6];
//                m_FristPFInfo = String.format("指纹  信息:第一枚指纹注册成功。指位:%s。指纹质量:%d \n", GetFPcode(fp[5]), fp[6]);
            } else {
                m_FristPFInfo = "";
            }
            if (fp[512 + 4] == (byte)0x01) {
                m_SecondPFInfo = GetFPcode(fp[512 + 5])+","+fp[512 + 6];
//                m_SecondPFInfo = String.format("指纹  信息:第二枚指纹注册成功。指位:%s。指纹质量:%d \n", GetFPcode(fp[512 + 5]),
//                        fp[512 + 6]);
            } else {
                m_SecondPFInfo = "";
            }

            result.putString("firstFP", m_FristPFInfo);
            result.putString("secondFP", m_SecondPFInfo);
            result.putString("name", HsOtgService.ic.getPeopleName());
            result.putString("sex", HsOtgService.ic.getSex());
            result.putString("people", HsOtgService.ic.getPeople());
            result.putString("birthday", HsOtgService.ic.getBirthDay().toString());
            result.putString("address", HsOtgService.ic.getAddr());
            result.putString("id", HsOtgService.ic.getIDCard());
            result.putString("department", HsOtgService.ic.getDepartment());
            result.putString("startDate", HsOtgService.ic.getStrartDate());
            result.putString("endDate", HsOtgService.ic.getEndDate());
            promise.resolve(result);
        }else {
            //失败
            promise.reject("0", "read failed");
        }
    }