Example usage for android.content ClipData getItemAt

List of usage examples for android.content ClipData getItemAt

Introduction

In this page you can find the example usage for android.content ClipData getItemAt.

Prototype

public Item getItemAt(int index) 

Source Link

Document

Return a single item inside of the clip data.

Usage

From source file:org.mozilla.gecko.GeckoAppShell.java

static String getClipboardText() {
    getHandler().post(new Runnable() {
        @SuppressWarnings("deprecation")
        public void run() {
            Context context = GeckoApp.mAppContext;
            String text = null;/*from w  w w .  j  ava2s .co m*/
            if (Build.VERSION.SDK_INT >= 11) {
                android.content.ClipboardManager cm = (android.content.ClipboardManager) context
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                if (cm.hasPrimaryClip()) {
                    ClipData clip = cm.getPrimaryClip();
                    if (clip != null) {
                        ClipData.Item item = clip.getItemAt(0);
                        text = item.coerceToText(context).toString();
                    }
                }
            } else {
                android.text.ClipboardManager cm = (android.text.ClipboardManager) context
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                if (cm.hasText())
                    text = cm.getText().toString();
            }
            try {
                sClipboardQueue.put(text != null ? text : EMPTY_STRING);
            } catch (InterruptedException ie) {
            }
        }
    });
    try {
        String ret = sClipboardQueue.take();
        return (EMPTY_STRING.equals(ret) ? null : ret);
    } catch (InterruptedException ie) {
    }
    return null;
}

From source file:com.stfalcon.contentmanager.ContentManager.java

private void handleFileContent(final Intent intent) {
    List<String> uris = new ArrayList<>();
    if (intent.getDataString() != null) {
        String uri = intent.getDataString();
        uris.add(uri);/*from   w  ww . j a v a  2  s  .  c  o  m*/
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        if (intent.getClipData() != null) {
            ClipData clipData = intent.getClipData();
            for (int i = 0; i < clipData.getItemCount(); i++) {
                ClipData.Item item = clipData.getItemAt(i);
                Log.d("TAG", "Item [" + i + "]: " + item.getUri().toString());
                uris.add(item.getUri().toString());
            }
        }
    }
    if (intent.hasExtra("uris")) {
        ArrayList<Uri> paths = intent.getParcelableArrayListExtra("uris");
        for (int i = 0; i < paths.size(); i++) {
            uris.add(paths.get(i).toString());
        }
    }

    //TODO Handle multiple file choose
    processFile(uris.get(0));
}

From source file:com.fbartnitzek.tasteemall.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.v(LOG_TAG, "onActivityResult, hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode
            + "], resultCode = [" + resultCode + "], data = [" + data + "]");

    if (requestCode == REQUEST_EXPORT_DIR_CODE
            || requestCode == REQUEST_IMPORT_FILES_CODE && resultCode == AppCompatActivity.RESULT_OK) {
        Uri uri;//from  ww w.  jav  a  2  s  .c  o  m
        if (data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {

            List<File> files = new ArrayList<>();
            // For JellyBean and above
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                ClipData clip = data.getClipData();

                if (clip != null) {
                    for (int i = 0; i < clip.getItemCount(); i++) {
                        uri = clip.getItemAt(i).getUri();
                        //                            Log.v(LOG_TAG, "onActivityResult, uri=" + uri + ", hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
                        files.add(new File(uri.getPath()));
                        // Do something with the URI
                    }
                }
                // For Ice Cream Sandwich
            } else {
                ArrayList<String> paths = data.getStringArrayListExtra(FilePickerActivity.EXTRA_PATHS);

                if (paths != null) {
                    for (String path : paths) {
                        uri = Uri.parse(path); // TODO: might be useless conversion...
                        //                            Log.v(LOG_TAG, "onActivityResult, uri=" + uri + ", hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
                        files.add(new File(uri.getPath()));
                    }
                }
            }

            if (!files.isEmpty() && requestCode == REQUEST_IMPORT_FILES_CODE) {

                // TODO: refactor afterwards without mFiles
                // new ImportFilesTask(MPA.this, MPA.this).execute(files.toArray(new File[files.size()]));

                mFiles = files;
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("which import shall be used?")
                        .setPositiveButton("class-based", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new ImportFilesTask(MainActivity.this, MainActivity.this)
                                        .execute(mFiles.toArray(new File[mFiles.size()]));
                                mFiles = null;
                            }
                        })
                        //                            .setNegativeButton("old", new DialogInterface.OnClickListener() {
                        //                                @Override
                        //                                public void onClick(DialogInterface dialog, int which) {
                        //                                    new ImportFilesOldFormatTask(MainActivity.this, MainActivity.this)
                        //                                            .execute(mFiles.toArray(new File[mFiles.size()]));
                        //                                    mFiles = null;
                        //                                }
                        //                            });
                        .setNegativeButton("all-in-1", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                // multiple all-in-1-files?
                                new ImportAllInOneFileTask(MainActivity.this, MainActivity.this)
                                        .execute(mFiles.get(0));
                                mFiles = null;
                                // to get all easier:
                                // either all ids are known or lots of parallel stuff...
                                // dialog with warning!
                                // task won't help => needs Dialog everywhere... => Task
                                // merge is to complicated for now :-p

                            }
                        });
                builder.show();
            }

        } else {
            //                Log.v(LOG_TAG, "onActivityResult - single file, hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
            uri = data.getData();
            // Do something with the URI
            if (uri != null && requestCode == REQUEST_EXPORT_DIR_CODE) {
                //somehow it returned a filepath (confusing use of multiple flag...
                new ExportToDirTask(this, this).execute(new File(uri.getPath()));
            }

        }

    } else if (requestCode == REQUEST_EDIT_PRODUCER_GEOCODE && resultCode == AppCompatActivity.RESULT_OK) {

        if (mProducerLocationUris == null) {
            Log.e(LOG_TAG, "onActivityResult mProducerLocationUris == null! - should never happen...");
            return;
        }

        if (mProducerLocationUris.isEmpty()) {
            if (mReviewLocationUris != null && !mReviewLocationUris.isEmpty()) {
                showReviewLocationGeocodeDialog(true);
            } else {
                Toast.makeText(MainActivity.this, "all geocoding done", Toast.LENGTH_SHORT).show();
                restartCurrentFragmentLoader();
            }
        } else {
            showProducerGeocodeDialog(true);
        }

    } else if (requestCode == REQUEST_EDIT_REVIEW_LOCATION_GEOCODE
            && resultCode == AppCompatActivity.RESULT_OK) {
        if (mReviewLocationUris == null) {
            Log.e(LOG_TAG, "onActivityResult mReviewLocationUris == null! - should never happen");
            return;
        }

        if (mReviewLocationUris.isEmpty()) {
            Toast.makeText(MainActivity.this, "all geocoding done", Toast.LENGTH_SHORT).show();
            restartCurrentFragmentLoader();
        } else {
            showReviewLocationGeocodeDialog(true);
        }
    } else if (requestCode == ADD_REVIEW_REQUEST && resultCode == Activity.RESULT_OK && data != null) {
        // TODO bugfix: refresh current pager
        startActivity(new Intent(this, ShowReviewActivity.class).setData(data.getData()));
    }

    super.onActivityResult(requestCode, resultCode, data);
}

From source file:jackpal.androidterm.RemoteInterface.java

protected void handleIntent() {
    TermService service = getTermService();
    if (service == null) {
        finish();/*from   ww w.  ja va  2 s .  c o  m*/
        return;
    }

    Intent myIntent = getIntent();
    String action = myIntent.getAction();

    if (action == null) {
        finish();
        return;
    }
    ClipData clipData = myIntent.getClipData();
    if ((AndroidCompat.SDK >= 19 && action.equals(Intent.ACTION_SEND) && myIntent.hasExtra(Intent.EXTRA_STREAM))
            || (action.equals(Intent.ACTION_SEND) && clipData != null)
            || (action.equals("android.intent.action.VIEW")) || (action.equals("android.intent.action.EDIT"))
            || (action.equals("android.intent.action.PICK"))
            || (action.equals("com.googlecode.android_scripting.action.EDIT_SCRIPT"))) {
        String url = null;
        Uri uri = null;
        if (clipData != null) {
            uri = clipData.getItemAt(0).getUri();
            if (uri == null) {
                openText(clipData.getItemAt(0).getText());
                finish();
                return;
            }
        } else if (AndroidCompat.SDK >= 19 && action.equals(Intent.ACTION_SEND)
                && myIntent.hasExtra(Intent.EXTRA_STREAM)) {
            Object extraStream = myIntent.getExtras().get(Intent.EXTRA_STREAM);
            if (extraStream instanceof Uri) {
                uri = (Uri) extraStream;
            }
        } else {
            uri = myIntent.getData();
        }
        String intentCommand = "sh ";
        if (mSettings.getInitialCommand().matches("(.|\n)*(^|\n)-vim\\.app(.|\n)*")) {
            intentCommand = ":e ";
        }
        boolean flavorVim = intentCommand.matches("^:.*");
        if (uri != null && uri.toString().matches("^file:///.*") && flavorVim) {
            String path = uri.getPath();
            if (new File(path).canRead()) {
                path = path.replaceAll(Term.SHELL_ESCAPE, "\\\\$1");
                String command = "\u001b" + intentCommand + path;
                // Find the target window
                mReplace = true;
                mHandle = switchToWindow(mHandle, command);
                mReplace = false;
            }
            finish();
        } else if (AndroidCompat.SDK >= 19 && uri != null && uri.getScheme() != null
                && uri.getScheme().equals("content") && flavorVim) {
            Context context = this;
            String command = null;
            String path = Term.getPath(context, uri);
            if (path != null) {
                path = path.replaceAll(Term.SHELL_ESCAPE, "\\\\$1");
                command = "\u001b" + intentCommand + path;
            } else if (getContentResolver() != null) {
                try {
                    Cursor cursor = getContentResolver().query(uri, null, null, null, null, null);
                    path = Term.handleOpenDocument(uri, cursor);
                } catch (Exception e) {
                    alert(e.toString() + "\n" + this.getString(R.string.storage_read_error));
                    finish();
                }
                if (path == null) {
                    alert(this.getString(R.string.storage_read_error));
                    finish();
                } else {
                    File dir = Term.getScratchCacheDir(this);
                    SyncFileObserver sfo = new SyncFileObserver(path);
                    sfo.setConTentResolver(this.getContentResolver());
                    path = dir.toString() + path;
                    String fname = new File(path).getName();
                    if (path.equals("") || !sfo.putUriAndLoad(uri, path)) {
                        alert(fname + "\n" + this.getString(R.string.storage_read_error));
                        finish();
                    }
                    path = path.replaceAll(Term.SHELL_ESCAPE, "\\\\$1");
                    command = "\u001b" + intentCommand + path;
                }
            }
            // Find the target window
            mReplace = true;
            mHandle = switchToWindow(mHandle, command);
            mReplace = false;
            finish();
        } else if (action.equals("com.googlecode.android_scripting.action.EDIT_SCRIPT")) {
            url = myIntent.getExtras().getString("com.googlecode.android_scripting.extra.SCRIPT_PATH");
        } else if (myIntent.getScheme() != null && myIntent.getScheme() != null
                && myIntent.getScheme().equals("file")) {
            if (myIntent.getData() != null)
                url = myIntent.getData().getPath();
        }
        if (url != null) {
            String command = "sh ";
            if (mSettings.getInitialCommand().matches("(.|\n)*(^|\n)-vim\\.app(.|\n)*")) {
                command = ":e ";
            }
            if (command.matches("^:.*")) {
                url = url.replaceAll(Term.SHELL_ESCAPE, "\\\\$1");
                command = "\u001b" + command + url;
                // Find the target window
                mReplace = true;
                mHandle = switchToWindow(mHandle, command);
                mReplace = false;
            } else if ((mHandle != null) && (url.equals(mFname))) {
                // Target the request at an existing window if open
                command = command + url;
                mHandle = switchToWindow(mHandle, command);
            } else {
                // Open a new window
                command = command + url;
                mHandle = openNewWindow(command);
            }
            mFname = url;

            Intent result = new Intent();
            result.putExtra(EXTRA_WINDOW_HANDLE, mHandle);
            setResult(RESULT_OK, result);
        }
    } else if (action.equals(Intent.ACTION_SEND) && myIntent.hasExtra(Intent.EXTRA_TEXT)) {
        openText(myIntent.getExtras().getCharSequence(Intent.EXTRA_TEXT));
    } else {
    }

    finish();
}

From source file:com.farmerbb.notepad.activity.MainActivity.java

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override//  w  w  w.  j  av  a2 s .c  o m
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {

    if (resultCode == RESULT_OK && resultData != null) {
        successful = true;

        if (requestCode == IMPORT) {
            Uri uri = resultData.getData();
            ClipData clipData = resultData.getClipData();

            if (uri != null)
                successful = importNote(uri);
            else if (clipData != null)
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    successful = importNote(clipData.getItemAt(i).getUri());
                }

            // Show toast notification
            showToast(successful
                    ? (uri == null ? R.string.notes_imported_successfully : R.string.note_imported_successfully)
                    : R.string.error_importing_notes);

            // Send broadcast to NoteListFragment to refresh list of notes
            Intent listNotesIntent = new Intent();
            listNotesIntent.setAction("com.farmerbb.notepad.LIST_NOTES");
            LocalBroadcastManager.getInstance(this).sendBroadcast(listNotesIntent);
        } else if (requestCode == EXPORT) {
            try {
                saveExportedNote(loadNote(filesToExport[fileBeingExported].toString()), resultData.getData());
            } catch (IOException e) {
                successful = false;
            }

            fileBeingExported++;
            if (fileBeingExported < filesToExport.length)
                reallyExportNotes();
            else
                showToast(successful
                        ? (fileBeingExported == 1 ? R.string.note_exported_to : R.string.notes_exported_to)
                        : R.string.error_exporting_notes);

            File fileToDelete = new File(getFilesDir() + File.separator + "exported_note");
            fileToDelete.delete();
        } else if (requestCode == EXPORT_TREE) {
            DocumentFile tree = DocumentFile.fromTreeUri(this, resultData.getData());

            for (Object exportFilename : filesToExport) {
                try {
                    DocumentFile file = tree.createFile("text/plain",
                            generateFilename(loadNoteTitle(exportFilename.toString())));

                    if (file != null)
                        saveExportedNote(loadNote(exportFilename.toString()), file.getUri());
                    else
                        successful = false;
                } catch (IOException e) {
                    successful = false;
                }
            }

            showToast(successful ? R.string.notes_exported_to : R.string.error_exporting_notes);
        }
    }
}

From source file:com.mb.android.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == PURCHASE_REQUEST) {
        if (resultCode == RESULT_OK) {

            if (currentProduct.getEmbyFeatureCode() != null) {

                AppstoreRegRequest request = new AppstoreRegRequest();
                request.setStore(intent.getStringExtra("store"));
                request.setApplication(AppPackageName);
                request.setProduct(currentProduct.getSku());
                request.setFeature(currentProduct.getEmbyFeatureCode());
                request.setType(currentProduct.getProductType().toString());
                if (intent.getStringExtra("storeId") != null)
                    request.setStoreId(intent.getStringExtra("storeId"));
                request.setStoreToken(intent.getStringExtra("storeToken"));
                request.setEmail(purchaseEmail);
                request.setAmt(currentProduct.getPrice());

                RespondToWebView(String.format("window.IapManager.onPurchaseComplete("
                        + jsonSerializer.SerializeToString(request) + ");"));
            } else {
                // no emby feature - just report success
                RespondToWebView(String.format("window.IapManager.onPurchaseComplete(true);"));
            }//from www.ja  va  2 s  .com
        } else {
            RespondToWebView(String.format("window.IapManager.onPurchaseComplete(false);"));
        }
    }

    else if (requestCode == REQUEST_DIRECTORY_SAF && resultCode == Activity.RESULT_OK) {

        Uri uri = intent.getData();
        final int takeFlags = intent.getFlags()
                & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // Check for the freshest data.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getContentResolver().takePersistableUriPermission(uri, takeFlags);
        }
        RespondToWebviewWithSelectedPath(uri);
    } else if (requestCode == REQUEST_DIRECTORY && resultCode == RESULT_OK) {

        if (intent.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {
            // For JellyBean and above
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                ClipData clip = intent.getClipData();

                if (clip != null) {
                    for (int i = 0; i < clip.getItemCount(); i++) {
                        Uri uri = clip.getItemAt(i).getUri();
                        RespondToWebviewWithSelectedPath(uri);
                    }
                }
                // For Ice Cream Sandwich
            } else {
                ArrayList<String> paths = intent.getStringArrayListExtra(FilePickerActivity.EXTRA_PATHS);

                if (paths != null) {
                    for (String path : paths) {
                        Uri uri = Uri.parse(path);
                        RespondToWebviewWithSelectedPath(uri);
                    }
                }
            }

        } else {
            Uri uri = intent.getData();
            // Do something with the URI
            if (uri != null) {
                RespondToWebviewWithSelectedPath(uri);
            }
        }
    }

    else if (requestCode == VIDEO_PLAYBACK) {

        /*boolean completed = resultCode == RESULT_OK;
        boolean error = resultCode == RESULT_OK ? false : (intent == null ? true : intent.getBooleanExtra("error", false));
                
        long positionMs = intent == null || completed ? 0 : intent.getLongExtra("position", 0);
        String currentSrc = intent == null ? null : intent.getStringExtra(VideoPlayerActivity.PLAY_EXTRA_ITEM_LOCATION);
                
        if (currentSrc == null) {
        currentSrc = "";
        }
                
        RespondToWebView(String.format("VideoRenderer.Current.onActivityClosed(%s, %s, %s, '%s');", !completed, error, positionMs, currentSrc));*/
    }
}

From source file:com.android.talkback.SpeechController.java

/**
 * Copies the last phrase spoken by TalkBack to clipboard
 *///from w w  w .  ja  v  a  2 s  .c o  m
public boolean copyLastUtteranceToClipboard(FeedbackItem item) {
    if (item == null) {
        return false;
    }

    final ClipboardManager clipboard = (ClipboardManager) mService.getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText(null, item.getAggregateText());
    clipboard.setPrimaryClip(clip);

    // Verify that we actually have the utterance on the clipboard
    clip = clipboard.getPrimaryClip();
    if (clip != null && clip.getItemCount() > 0 && clip.getItemAt(0).getText() != null) {
        speak(mService.getString(R.string.template_text_copied,
                clip.getItemAt(0).getText().toString()) /* text */, QUEUE_MODE_INTERRUPT /* queue mode */,
                0 /* flags */, null /* speech params */);
        return true;
    } else {
        return false;
    }
}

From source file:com.stanleyidesis.quotograph.ui.activity.LWQSettingsActivity.java

@SuppressWarnings("WrongConstant")
@SuppressLint("NewApi")
@Override//from  ww  w  .j av a2  s  .co  m
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_SAVE) {
        changeState(stateSaveSkipCompleted);
        return;
    } else if (requestCode == IabConst.PURCHASE_REQUEST_CODE) {
        LWQApplication.getIabHelper().handleActivityResult(requestCode, resultCode, data);
    } else if (requestCode == REQUEST_CODE_ALBUM) {
        if (resultCode != RESULT_OK) {
            return;
        }
        List<String> resultUris = new ArrayList<>();
        //            final int takeFlags = data.getFlags()
        //                    & Intent.FLAG_GRANT_READ_URI_PERMISSION;
        if (data.getClipData() != null) {
            ClipData clipData = data.getClipData();
            for (int i = 0; i < clipData.getItemCount(); i++) {
                Uri imageUri = clipData.getItemAt(i).getUri();
                //                    getContentResolver().takePersistableUriPermission(imageUri, takeFlags);
                resultUris.add(imageUri.toString());
            }
        } else if (data.getData() != null) {
            Uri imageUri = data.getData();
            //                getContentResolver().takePersistableUriPermission(imageUri, takeFlags);
            resultUris.add(imageUri.toString());
        }
        chooseImageSourceModule.onImagesRecovered(resultUris);
    }
    super.onActivityResult(requestCode, resultCode, data);
}

From source file:im.vector.activity.RoomActivity.java

@SuppressLint("NewApi")
private void sendMediasIntent(final Intent data) {
    // sanity check
    if ((null == data) && (null == mLatestTakePictureCameraUri)) {
        return;//from  w  w w  . j a  v a2  s.  c om
    }

    ArrayList<Uri> uris = new ArrayList<Uri>();

    if (null != data) {
        ClipData clipData = null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            clipData = data.getClipData();
        }

        // multiple data
        if (null != clipData) {
            int count = clipData.getItemCount();

            for (int i = 0; i < count; i++) {
                ClipData.Item item = clipData.getItemAt(i);
                Uri uri = item.getUri();

                if (null != uri) {
                    uris.add(uri);
                }
            }

        } else if (null != data.getData()) {
            uris.add(data.getData());
        }
    } else if (null != mLatestTakePictureCameraUri) {
        uris.add(Uri.parse(mLatestTakePictureCameraUri));
        mLatestTakePictureCameraUri = null;
    }

    // check the extras
    if (0 == uris.size()) {
        Bundle bundle = data.getExtras();

        // sanity checks
        if (null != bundle) {
            if (bundle.containsKey(Intent.EXTRA_STREAM)) {
                Object streamUri = bundle.get(Intent.EXTRA_STREAM);

                if (streamUri instanceof Uri) {
                    uris.add((Uri) streamUri);
                }
            } else if (bundle.containsKey(Intent.EXTRA_TEXT)) {
                this.sendMessage(bundle.getString(Intent.EXTRA_TEXT));
            }
        } else {
            uris.add(mLatestTakePictureCameraUri == null ? null : Uri.parse(mLatestTakePictureCameraUri));
            mLatestTakePictureCameraUri = null;
        }
    }

    if (0 != uris.size()) {
        sendMedias(uris);
    }
}

From source file:org.kontalk.ui.AbstractComposeFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // image from storage/picture from camera
    // since there are like up to 3 different ways of doing this...
    if (requestCode == SELECT_ATTACHMENT_OPENABLE || requestCode == SELECT_ATTACHMENT_PHOTO) {
        if (resultCode == Activity.RESULT_OK) {
            Uri[] uris = null;//w  ww.ja v  a2  s .c  o  m
            String[] mimes = null;

            // returning from camera
            if (requestCode == SELECT_ATTACHMENT_PHOTO) {
                if (mCurrentPhoto != null) {
                    Uri uri = Uri.fromFile(mCurrentPhoto);
                    // notify media scanner
                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    mediaScanIntent.setData(uri);
                    getActivity().sendBroadcast(mediaScanIntent);
                    mCurrentPhoto = null;

                    uris = new Uri[] { uri };
                }
            } else {
                if (mCurrentPhoto != null) {
                    mCurrentPhoto.delete();
                    mCurrentPhoto = null;
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && data.getClipData() != null) {
                    ClipData cdata = data.getClipData();
                    uris = new Uri[cdata.getItemCount()];

                    for (int i = 0; i < uris.length; i++) {
                        ClipData.Item item = cdata.getItemAt(i);
                        uris[i] = item.getUri();
                    }
                } else {
                    uris = new Uri[] { data.getData() };
                    mimes = new String[] { data.getType() };
                }

                // SAF available, request persistable permissions
                if (MediaStorage.isStorageAccessFrameworkAvailable()) {
                    for (Uri uri : uris) {
                        if (uri != null && !"file".equals(uri.getScheme())) {
                            MediaStorage.requestPersistablePermissions(getActivity(), uri);
                        }
                    }
                }
            }

            for (int i = 0; uris != null && i < uris.length; i++) {
                Uri uri = uris[i];
                if (uri == null)
                    continue;

                String mime = (mimes != null && mimes.length >= uris.length) ? mimes[i] : null;

                if (mime == null || mime.startsWith("*/") || mime.endsWith("/*")) {
                    mime = MediaStorage.getType(getActivity(), uri);
                    Log.v(TAG, "using detected mime type " + mime);
                }

                if (ImageComponent.supportsMimeType(mime))
                    sendBinaryMessage(uri, mime, true, ImageComponent.class);
                else if (VCardComponent.supportsMimeType(mime))
                    sendBinaryMessage(uri, VCardComponent.MIME_TYPE, false, VCardComponent.class);
                else
                    Toast.makeText(getActivity(), R.string.send_mime_not_supported, Toast.LENGTH_LONG).show();
            }
        }
        // operation aborted
        else {
            // delete photo :)
            if (mCurrentPhoto != null) {
                mCurrentPhoto.delete();
                mCurrentPhoto = null;
            }
        }
    }
    // contact card (vCard)
    else if (requestCode == SELECT_ATTACHMENT_CONTACT) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                Uri vcardUri = null;

                // get lookup key
                final Cursor c = getContext().getContentResolver().query(uri,
                        new String[] { Contacts.LOOKUP_KEY }, null, null, null);
                if (c != null) {
                    try {
                        if (c.moveToFirst()) {
                            String lookupKey = c.getString(0);
                            vcardUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);
                        }
                    } catch (Exception e) {
                        Log.w(TAG, "unable to lookup selected contact. Did you grant me the permission?", e);
                        ReportingManager.logException(e);
                    } finally {
                        c.close();
                    }
                }

                if (vcardUri != null) {
                    sendBinaryMessage(vcardUri, VCardComponent.MIME_TYPE, false, VCardComponent.class);
                } else {
                    Toast.makeText(getContext(), R.string.err_no_contact, Toast.LENGTH_LONG).show();
                }
            }
        }
    }
    // invite user
    else if (requestCode == REQUEST_INVITE_USERS) {
        if (resultCode == Activity.RESULT_OK) {

            ArrayList<Uri> uris;
            Uri threadUri = data.getData();
            if (threadUri != null) {
                String userId = threadUri.getLastPathSegment();
                addUsers(new String[] { userId });
            } else if ((uris = data.getParcelableArrayListExtra("org.kontalk.contacts")) != null) {
                String[] users = new String[uris.size()];
                for (int i = 0; i < users.length; i++)
                    users[i] = uris.get(i).getLastPathSegment();
                addUsers(users);
            }

        }
    }
}