Example usage for android.app Activity RESULT_CANCELED

List of usage examples for android.app Activity RESULT_CANCELED

Introduction

In this page you can find the example usage for android.app Activity RESULT_CANCELED.

Prototype

int RESULT_CANCELED

To view the source code for android.app Activity RESULT_CANCELED.

Click Source Link

Document

Standard activity result: operation canceled.

Usage

From source file:devcoin.wallet.ui.SendCoinsFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.send_coins_fragment, container);

    receivingAddressView = (AutoCompleteTextView) view.findViewById(R.id.send_coins_receiving_address);
    receivingAddressView.setAdapter(new AutoCompleteAddressAdapter(activity, null));
    receivingAddressView.setOnFocusChangeListener(receivingAddressListener);
    receivingAddressView.addTextChangedListener(receivingAddressListener);

    receivingStaticView = view.findViewById(R.id.send_coins_receiving_static);
    receivingStaticAddressView = (TextView) view.findViewById(R.id.send_coins_receiving_static_address);
    receivingStaticLabelView = (TextView) view.findViewById(R.id.send_coins_receiving_static_label);

    receivingStaticView.setOnFocusChangeListener(new OnFocusChangeListener() {
        private ActionMode actionMode;

        @Override//from w w  w. j  a v  a 2s .  co  m
        public void onFocusChange(final View v, final boolean hasFocus) {
            if (hasFocus)
                actionMode = activity.startActionMode(new ReceivingAddressActionMode());
            else
                actionMode.finish();
        }
    });

    final CurrencyAmountView btcAmountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_amount_btc);
    btcAmountView.setCurrencySymbol(btcShift == 0 ? Constants.CURRENCY_CODE_BTC : Constants.CURRENCY_CODE_MBTC);
    btcAmountView.setInputPrecision(btcShift == 0 ? Constants.BTC_MAX_PRECISION : Constants.MBTC_MAX_PRECISION);
    btcAmountView.setHintPrecision(btcPrecision);
    btcAmountView.setShift(btcShift);

    final CurrencyAmountView localAmountView = (CurrencyAmountView) view
            .findViewById(R.id.send_coins_amount_local);
    localAmountView.setInputPrecision(Constants.LOCAL_PRECISION);
    localAmountView.setHintPrecision(Constants.LOCAL_PRECISION);
    amountCalculatorLink = new CurrencyCalculatorLink(btcAmountView, localAmountView);

    bluetoothEnableView = (CheckBox) view.findViewById(R.id.send_coins_bluetooth_enable);
    bluetoothEnableView.setChecked(bluetoothAdapter != null && bluetoothAdapter.isEnabled());
    bluetoothEnableView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            if (isChecked && !bluetoothAdapter.isEnabled()) {
                // try to enable bluetooth
                startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
                        REQUEST_CODE_ENABLE_BLUETOOTH);
            }
        }
    });

    bluetoothMessageView = (TextView) view.findViewById(R.id.send_coins_bluetooth_message);

    sentTransactionView = (ListView) view.findViewById(R.id.send_coins_sent_transaction);
    sentTransactionListAdapter = new TransactionsListAdapter(activity, wallet, application.maxConnectedPeers(),
            false);
    sentTransactionView.setAdapter(sentTransactionListAdapter);

    viewGo = (Button) view.findViewById(R.id.send_coins_go);
    viewGo.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            validateReceivingAddress(true);
            validateAmounts(true);

            if (everythingValid())
                handleGo();
        }
    });

    viewCancel = (Button) view.findViewById(R.id.send_coins_cancel);
    viewCancel.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (state == State.INPUT)
                activity.setResult(Activity.RESULT_CANCELED);

            activity.finish();
        }
    });

    popupMessageView = (TextView) inflater.inflate(R.layout.send_coins_popup_message, container);

    popupAvailableView = inflater.inflate(R.layout.send_coins_popup_available, container);

    if (savedInstanceState != null) {
        restoreInstanceState(savedInstanceState);
    } else {
        final Intent intent = activity.getIntent();
        final String action = intent.getAction();
        final Uri intentUri = intent.getData();
        final String scheme = intentUri != null ? intentUri.getScheme() : null;

        if ((Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
                && intentUri != null && "devcoin".equals(scheme))
            initStateFromBitcoinUri(intentUri);
        else if (intent.hasExtra(SendCoinsActivity.INTENT_EXTRA_ADDRESS))
            initStateFromIntentExtras(intent.getExtras());
    }

    return view;
}

From source file:com.github.socialc0de.gsw.android.MainActivity.java

/**
 * Handles the results from activities launched to select an account and to install Google Play
 * Services./*from  ww  w.j  a v a  2s . c o  m*/
 */

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case REQUEST_ACCOUNT_PICKER:
        if (data != null && data.getExtras() != null) {
            String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
            if (accountName != null) {
                onSignedIn(accountName);
            }
        } else if (!SIGN_IN_REQUIRED) {
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle(R.string.are_you_sure);
            alert.setMessage(R.string.not_all_features);
            alert.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    startMainActivity();
                }
            });
            alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
                }
            });
            alert.show();

        }
        break;
    case REQUEST_GOOGLE_PLAY_SERVICES:
        if (resultCode != Activity.RESULT_OK) {
            checkGooglePlayServicesAvailable();
        }
        break;
    }

    if (requestCode == REQUEST_CODE_PAYMENT) {
        if (resultCode == Activity.RESULT_OK) {
            PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
            if (confirm != null) {
                try {
                    Log.i(TAG, confirm.toJSONObject().toString(4));
                    Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
                    /**
                     *  TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
                     * or consent completion.
                     * See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                     * for more details.
                     *
                     * For sample mobile backend interactions, see
                     * https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
                     */
                    Toast.makeText(getApplicationContext(), "PaymentConfirmation info received from PayPal",
                            Toast.LENGTH_LONG).show();

                } catch (JSONException e) {
                    Log.e(TAG, "an extremely unlikely failure occurred: ", e);
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "The user canceled.");
        } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
            Log.i(TAG, "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
        }
    } else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
        if (resultCode == Activity.RESULT_OK) {
            PayPalAuthorization auth = data
                    .getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
            if (auth != null) {
                try {
                    Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));

                    String authorization_code = auth.getAuthorizationCode();
                    Log.i("FuturePaymentExample", authorization_code);

                    Toast.makeText(getApplicationContext(), "Future Payment code received from PayPal",
                            Toast.LENGTH_LONG).show();

                } catch (JSONException e) {
                    Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i("FuturePaymentExample", "The user canceled.");
        } else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
            Log.i("FuturePaymentExample",
                    "Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
        }
    } else if (requestCode == REQUEST_CODE_PROFILE_SHARING) {
        if (resultCode == Activity.RESULT_OK) {
            PayPalAuthorization auth = data
                    .getParcelableExtra(PayPalProfileSharingActivity.EXTRA_RESULT_AUTHORIZATION);
            if (auth != null) {
                try {
                    Log.i("ProfileSharingExample", auth.toJSONObject().toString(4));

                    String authorization_code = auth.getAuthorizationCode();
                    Log.i("ProfileSharingExample", authorization_code);

                    Toast.makeText(getApplicationContext(), "Profile Sharing code received from PayPal",
                            Toast.LENGTH_LONG).show();

                } catch (JSONException e) {
                    Log.e("ProfileSharingExample", "an extremely unlikely failure occurred: ", e);
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i("ProfileSharingExample", "The user canceled.");
        } else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
            Log.i("ProfileSharingExample",
                    "Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
        }
    }
}

From source file:com.mikroe.hexiwear_android.DeviceScanActivity.java

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // User chose not to enable Bluetooth.
    if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
        finish();//from   w ww . j  ava2s  .  c  o  m
        return;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

From source file:com.money.manager.ex.common.CategoryListFragment.java

@Override
protected void setResult() {
    if (Intent.ACTION_PICK.equals(mAction)) {
        if (getExpandableListAdapter() == null)
            return;

        Intent result = null;/*www  .  j  a v  a  2 s .c  o  m*/

        if (getExpandableListAdapter() instanceof CategoryExpandableListAdapter) {
            CategoryExpandableListAdapter adapter = (CategoryExpandableListAdapter) getExpandableListAdapter();
            int categId = adapter.getIdGroupChecked();
            int subCategId = adapter.getIdChildChecked();

            if (categId == ExpandableListView.INVALID_POSITION)
                return;

            for (int groupIndex = 0; groupIndex < mCategories.size(); groupIndex++) {
                if (mCategories.get(groupIndex).getId() == categId) {
                    // Get subcategory
                    if (subCategId != ExpandableListView.INVALID_POSITION) {
                        for (int child = 0; child < mSubCategories.get(mCategories.get(groupIndex))
                                .size(); child++) {
                            if (mSubCategories.get(mCategories.get(groupIndex)).get(child)
                                    .getSubCategId() == subCategId) {
                                result = new Intent();
                                result.putExtra(CategoryListActivity.INTENT_RESULT_CATEGID, categId);
                                result.putExtra(CategoryListActivity.INTENT_RESULT_CATEGNAME, mSubCategories
                                        .get(mCategories.get(groupIndex)).get(child).getCategName().toString());
                                result.putExtra(CategoryListActivity.INTENT_RESULT_SUBCATEGID, subCategId);
                                result.putExtra(CategoryListActivity.INTENT_RESULT_SUBCATEGNAME,
                                        mSubCategories.get(mCategories.get(groupIndex)).get(child)
                                                .getSubcategoryName().toString());
                                break;
                            }
                        }
                    } else {
                        result = new Intent();
                        result.putExtra(CategoryListActivity.INTENT_RESULT_CATEGID, categId);
                        result.putExtra(CategoryListActivity.INTENT_RESULT_CATEGNAME,
                                mCategories.get(groupIndex).getName());
                        result.putExtra(CategoryListActivity.INTENT_RESULT_SUBCATEGID, subCategId);
                        result.putExtra(CategoryListActivity.INTENT_RESULT_SUBCATEGNAME, "");
                    }
                }
            }
        }

        if (result != null) {
            result.putExtra(CategoryListActivity.KEY_REQUEST_ID, this.requestId);

            getActivity().setResult(Activity.RESULT_OK, result);
        } else {
            getActivity().setResult(Activity.RESULT_CANCELED);
        }
    }
}

From source file:com.cmput301w17t07.moody.CreateMoodActivity.java

/**
 * Method handles user interface response to when a user adds an image to their mood
 * from either their camera or their gallery. <br>
 *
 * Knowledge and logic of onActivityResult referenced and taken from <br>
 * link: http://blog.csdn.net/AndroidStudioo/article/details/52077597 <br>
 * author: AndroidStudio 2016-07-31 11:15 <br>
 * taken by Xin Huang 2017-03-04 15:30 <br>
 * @param requestCode          integer indicating the kind of action taken by the user <br>
 * @param resultCode <br>/*from  w  ww. jav a2 s .co  m*/
 * @param data <br>
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data == null) {
        finish(); //no data return
    }
    if (requestCode == 0) {
        //get pic from local photo
        try {
            bitmap = data.getParcelableExtra("data");
            if (bitmap == null) {//if pic is not so big use original one
                try {
                    InputStream inputStream = getContentResolver().openInputStream(data.getData());
                    bitmap = BitmapFactory.decodeStream(inputStream);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } catch (RuntimeException e) {
            Intent intent = new Intent(getApplicationContext(), CreateMoodActivity.class);
            startActivity(intent);
        }

    } else if (requestCode == 1) {
        try {
            bitmap = (Bitmap) data.getExtras().get("data");
        } catch (Exception e) {
            Intent intent = new Intent(getApplicationContext(), CreateMoodActivity.class);
            startActivity(intent);
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        try {
            Intent intent = new Intent(getApplicationContext(), CreateMoodActivity.class);
            startActivity(intent);
        } catch (RuntimeException e) {
        }

    }
    mImageView.setImageBitmap(bitmap);

}

From source file:com.nbplus.vbroadlauncher.fragment.LoadIoTDevicesDialogFragmentStatus.java

/**
 * Receive the result from a previous call to
 * {@link #startActivityForResult(Intent, int)}.  This follows the
 * related Activity API as described there in
 * {@link Activity#onActivityResult(int, int, Intent)}.
 *
 * @param requestCode The integer request code originally supplied to
 *                    startActivityForResult(), allowing you to identify who this
 *                    result came from.//from  ww w.  jav a 2s .  c  om
 * @param resultCode  The integer result code returned by the child activity
 *                    through its setResult().
 * @param data        An Intent, which can return result data to the caller
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(TAG, ">>> onActivityResult...");
    switch (requestCode) {
    case Constants.START_ACTIVITY_REQUEST_ENABLE_BT:
        // User chose not to enable Bluetooth.
        if (resultCode == Activity.RESULT_CANCELED) {
            dismissDialogFragment();

            Intent sendIntent = new Intent();
            sendIntent.setAction(Constants.ACTION_IOT_DEVICE_LIST);
            sendIntent.putExtra(Constants.EXTRA_IOT_DEVICE_CANCELED, true);
            LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(sendIntent);
        } else {
            ((BaseActivity) getActivity()).showProgressDialog();
            IoTInterface.getInstance().getDevicesList(DeviceTypes.ALL, LoadIoTDevicesDialogFragmentStatus.this);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ((BaseActivity) getActivity()).dismissProgressDialog();
                }
            }, 6000);
        }
        break;
    }
}

From source file:org.apache.cordova.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits.//from  w w  w.j  a  v a2s . com
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity())
                                + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    if (!this.saveToPhotoAlbum) {
                        uri = Uri.fromFile(
                                new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()),
                                        System.currentTimeMillis() + ".jpg"));
                    } else {
                        uri = getUriFromMediaStore();
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && rotate == 0) {
                        writeUncompressedImage(uri);

                        this.callbackContext.success(uri.toString());
                    } else {
                        bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // Add compressed version of captured image to returned media store Uri
                        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                        os.close();

                        // Restore exif data to file
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.callbackContext.success(uri.toString());
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();

            // If you ask for video or all media type you will automatically get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                this.callbackContext.success(uri.toString());
            } else {
                // This is a special case to just return the path as no scaling,
                // rotating or compression needs to be done
                if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                        && destType == FILE_URI && !this.correctOrientation) {
                    this.callbackContext.success(uri.toString());
                } else {
                    // Get the path to the image. Makes loading so much easier.
                    String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
                    String mimeType = FileUtils.getMimeType(imagePath);
                    // Log.d(LOG_TAG, "Real path = " + imagePath);
                    // Log.d(LOG_TAG, "mime type = " + mimeType);
                    // If we don't have a valid image so quit.
                    if (imagePath == null || mimeType == null || !(mimeType.equalsIgnoreCase("image/jpeg")
                            || mimeType.equalsIgnoreCase("image/png"))) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to retrieve path to picture!");
                        return;
                    }
                    Bitmap bitmap = getScaledBitmap(imagePath);
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

                    if (this.correctOrientation) {
                        String[] cols = { MediaStore.Images.Media.ORIENTATION };
                        Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
                                cols, null, null, null);
                        if (cursor != null) {
                            cursor.moveToPosition(0);
                            rotate = cursor.getInt(0);
                            cursor.close();
                        }
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            matrix.setRotate(rotate);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                        }
                    }

                    // If sending base64 image back
                    if (destType == DATA_URL) {
                        this.processPicture(bitmap);
                    }

                    // If sending filename back
                    else if (destType == FILE_URI) {
                        // Do we need to scale the returned file
                        if (this.targetHeight > 0 && this.targetWidth > 0) {
                            try {
                                // Create an ExifHelper to save the exif data that is lost during compression
                                String resizePath = DirectoryManager
                                        .getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
                                ExifHelper exif = new ExifHelper();
                                try {
                                    if (this.encodingType == JPEG) {
                                        exif.createInFile(resizePath);
                                        exif.readExifData();
                                        rotate = exif.getOrientation();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                OutputStream os = new FileOutputStream(resizePath);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                                os.close();

                                // Restore exif data to file
                                if (this.encodingType == JPEG) {
                                    exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
                                    exif.writeExifData();
                                }

                                // The resized image is cached by the app in order to get around this and not have to delete you
                                // application cache I'm adding the current system time to the end of the file url.
                                this.callbackContext
                                        .success("file://" + resizePath + "?" + System.currentTimeMillis());
                            } catch (Exception e) {
                                e.printStackTrace();
                                this.failPicture("Error retrieving image.");
                            }
                        } else {
                            this.callbackContext.success(uri.toString());
                        }
                    }
                    if (bitmap != null) {
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Called when the camera view exits./*from  w w  w  .  jav a 2  s  . c o m*/
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity())
                                + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    if (!this.saveToPhotoAlbum) {
                        uri = Uri.fromFile(
                                new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()),
                                        System.currentTimeMillis() + ".jpg"));
                    } else {
                        uri = getUriFromMediaStore();
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && rotate == 0) {
                        writeUncompressedImage(uri);

                        this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                    } else {
                        bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // Add compressed version of captured image to returned media store Uri
                        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                        os.close();

                        // Restore exif data to file
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();

            // If you ask for video or all media type you will automatically get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            } else {
                // This is a special case to just return the path as no scaling,
                // rotating or compression needs to be done
                if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                        && destType == FILE_URI && !this.correctOrientation) {
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                } else {
                    // Get the path to the image. Makes loading so much easier.
                    String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
                    Log.d(LOG_TAG, "Real path = " + imagePath);
                    // If we don't have a valid image so quit.
                    if (imagePath == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to retreive path to picture!");
                        return;
                    }
                    Bitmap bitmap = getScaledBitmap(imagePath);
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

                    if (this.correctOrientation) {
                        String[] cols = { MediaStore.Images.Media.ORIENTATION };
                        Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
                                cols, null, null, null);
                        if (cursor != null) {
                            cursor.moveToPosition(0);
                            rotate = cursor.getInt(0);
                            cursor.close();
                        }
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            matrix.setRotate(rotate);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                        }
                    }

                    // If sending base64 image back
                    if (destType == DATA_URL) {
                        this.processPicture(bitmap);
                    }

                    // If sending filename back
                    else if (destType == FILE_URI) {
                        // Do we need to scale the returned file
                        if (this.targetHeight > 0 && this.targetWidth > 0) {
                            try {
                                // Create an ExifHelper to save the exif data that is lost during compression
                                String resizePath = DirectoryManager
                                        .getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
                                ExifHelper exif = new ExifHelper();
                                try {
                                    if (this.encodingType == JPEG) {
                                        exif.createInFile(resizePath);
                                        exif.readExifData();
                                        rotate = exif.getOrientation();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                OutputStream os = new FileOutputStream(resizePath);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                                os.close();

                                // Restore exif data to file
                                if (this.encodingType == JPEG) {
                                    exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
                                    exif.writeExifData();
                                }

                                // The resized image is cached by the app in order to get around this and not have to delete you
                                // application cache I'm adding the current system time to the end of the file url.
                                this.success(
                                        new PluginResult(PluginResult.Status.OK,
                                                ("file://" + resizePath + "?" + System.currentTimeMillis())),
                                        this.callbackId);
                            } catch (Exception e) {
                                e.printStackTrace();
                                this.failPicture("Error retrieving image.");
                            }
                        } else {
                            this.success(new PluginResult(PluginResult.Status.OK, uri.toString()),
                                    this.callbackId);
                        }
                    }
                    if (bitmap != null) {
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:hashengineering.digitalcoin.wallet.ui.SendCoinsFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.send_coins_fragment, container);

    receivingAddressView = (AutoCompleteTextView) view.findViewById(R.id.send_coins_receiving_address);
    receivingAddressView.setAdapter(new AutoCompleteAddressAdapter(activity, null));
    receivingAddressView.setOnFocusChangeListener(receivingAddressListener);
    receivingAddressView.addTextChangedListener(receivingAddressListener);

    receivingStaticView = view.findViewById(R.id.send_coins_receiving_static);
    receivingStaticAddressView = (TextView) view.findViewById(R.id.send_coins_receiving_static_address);
    receivingStaticLabelView = (TextView) view.findViewById(R.id.send_coins_receiving_static_label);

    receivingStaticView.setOnFocusChangeListener(new OnFocusChangeListener() {
        private ActionMode actionMode;

        @Override/*from www  .j  av  a 2 s.  c  o  m*/
        public void onFocusChange(final View v, final boolean hasFocus) {
            if (hasFocus)
                actionMode = activity.startActionMode(new ReceivingAddressActionMode());
            else
                actionMode.finish();
        }
    });

    final CurrencyAmountView btcAmountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_amount_btc);
    btcAmountView.setCurrencySymbol(Constants.CURRENCY_CODE_BITCOIN);
    btcAmountView.setHintPrecision(btcPrecision);

    final CurrencyAmountView localAmountView = (CurrencyAmountView) view
            .findViewById(R.id.send_coins_amount_local);
    localAmountView.setHintPrecision(Constants.LOCAL_PRECISION);
    amountCalculatorLink = new CurrencyCalculatorLink(btcAmountView, localAmountView);

    bluetoothEnableView = (CheckBox) view.findViewById(R.id.send_coins_bluetooth_enable);
    bluetoothEnableView.setChecked(bluetoothAdapter != null && bluetoothAdapter.isEnabled());
    bluetoothEnableView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            if (isChecked && !bluetoothAdapter.isEnabled()) {
                // try to enable bluetooth
                startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
                        REQUEST_CODE_ENABLE_BLUETOOTH);
            }
        }
    });

    bluetoothMessageView = (TextView) view.findViewById(R.id.send_coins_bluetooth_message);

    sentTransactionView = (ListView) view.findViewById(R.id.send_coins_sent_transaction);
    sentTransactionListAdapter = new TransactionsListAdapter(activity, wallet, application.maxConnectedPeers(),
            false);
    sentTransactionView.setAdapter(sentTransactionListAdapter);

    viewGo = (Button) view.findViewById(R.id.send_coins_go);
    viewGo.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            validateReceivingAddress(true);
            validateAmounts(true);

            if (everythingValid())
                handleGo();
        }
    });

    viewCancel = (Button) view.findViewById(R.id.send_coins_cancel);
    viewCancel.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (state == State.INPUT)
                activity.setResult(Activity.RESULT_CANCELED);

            activity.finish();
        }
    });

    popupMessageView = (TextView) inflater.inflate(R.layout.send_coins_popup_message, container);

    popupAvailableView = inflater.inflate(R.layout.send_coins_popup_available, container);

    if (savedInstanceState != null) {
        restoreInstanceState(savedInstanceState);
    } else {
        final Intent intent = activity.getIntent();
        final String action = intent.getAction();
        final Uri intentUri = intent.getData();
        final String scheme = intentUri != null ? intentUri.getScheme() : null;

        if ((Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
                && intentUri != null && "bitcoin".equals(scheme))
            initStateFromBitcoinUri(intentUri);
        else if (intent.hasExtra(SendCoinsActivity.INTENT_EXTRA_ADDRESS))
            initStateFromIntentExtras(intent.getExtras());
    }

    return view;
}

From source file:org.apache.cordova.mediacapture.Capture.java

/**
 * Called when the video view exits./*from  w ww .j a  v a  2s .  c  o  m*/
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 * @throws JSONException
 */
public void onActivityResult(int requestCode, int resultCode, final Intent intent) {

    // Result received okay
    if (resultCode == Activity.RESULT_OK) {
        // An audio clip was requested
        if (requestCode == CAPTURE_AUDIO) {

            final Capture that = this;
            Runnable captureAudio = new Runnable() {

                @Override
                public void run() {
                    // Get the uri of the audio clip
                    Uri data = intent.getData();
                    // create a file object from the uri
                    results.put(createMediaFile(data));

                    if (results.length() >= limit) {
                        // Send Uri back to JavaScript for listening to audio
                        that.callbackContext
                                .sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
                    } else {
                        // still need to capture more audio clips
                        captureAudio();
                    }
                }
            };
            this.cordova.getThreadPool().execute(captureAudio);
        } else if (requestCode == CAPTURE_IMAGE) {
            // For some reason if I try to do:
            // Uri data = intent.getData();
            // It crashes in the emulator and on my phone with a null pointer exception
            // To work around it I had to grab the code from CameraLauncher.java

            final Capture that = this;
            Runnable captureImage = new Runnable() {
                @Override
                public void run() {
                    try {
                        // TODO Auto-generated method stub
                        // Create entry in media store for image
                        // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
                        ContentValues values = new ContentValues();
                        values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, IMAGE_JPEG);
                        Uri uri = null;
                        try {
                            uri = that.cordova.getActivity().getContentResolver().insert(
                                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                        } catch (UnsupportedOperationException e) {
                            LOG.d(LOG_TAG, "Can't write to external media storage.");
                            try {
                                uri = that.cordova.getActivity().getContentResolver().insert(
                                        android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                            } catch (UnsupportedOperationException ex) {
                                LOG.d(LOG_TAG, "Can't write to internal media storage.");
                                that.fail(createErrorObject(CAPTURE_INTERNAL_ERR,
                                        "Error capturing image - no media storage found."));
                                return;
                            }
                        }
                        FileInputStream fis = new FileInputStream(getTempDirectoryPath() + "/Capture.jpg");
                        OutputStream os = that.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        byte[] buffer = new byte[4096];
                        int len;
                        while ((len = fis.read(buffer)) != -1) {
                            os.write(buffer, 0, len);
                        }
                        os.flush();
                        os.close();
                        fis.close();

                        // Add image to results
                        results.put(createMediaFile(uri));

                        checkForDuplicateImage();

                        if (results.length() >= limit) {
                            // Send Uri back to JavaScript for viewing image
                            that.callbackContext
                                    .sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
                        } else {
                            // still need to capture more images
                            captureImage();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        that.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image."));
                    }
                }
            };
            this.cordova.getThreadPool().execute(captureImage);
        } else if (requestCode == CAPTURE_VIDEO) {

            final Capture that = this;
            Runnable captureVideo = new Runnable() {

                @Override
                public void run() {

                    Uri data = null;

                    if (intent != null) {
                        // Get the uri of the video clip
                        data = intent.getData();
                    }

                    if (data == null) {
                        File movie = new File(getTempDirectoryPath(), "Capture.avi");
                        data = Uri.fromFile(movie);
                    }

                    // create a file object from the uri
                    if (data == null) {
                        that.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Error: data is null"));
                    } else {
                        results.put(createMediaFile(data));

                        if (results.length() >= limit) {
                            // Send Uri back to JavaScript for viewing video
                            that.callbackContext
                                    .sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
                        } else {
                            // still need to capture more video clips
                            captureVideo(duration);
                        }
                    }
                }
            };
            this.cordova.getThreadPool().execute(captureVideo);
        }
    }
    // If canceled
    else if (resultCode == Activity.RESULT_CANCELED) {
        // If we have partial results send them back to the user
        if (results.length() > 0) {
            this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
        }
        // user canceled the action
        else {
            this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Canceled."));
        }
    }
    // If something else
    else {
        // If we have partial results send them back to the user
        if (results.length() > 0) {
            this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
        }
        // something bad happened
        else {
            this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Did not complete!"));
        }
    }
}