Example usage for android.net Uri fromFile

List of usage examples for android.net Uri fromFile

Introduction

In this page you can find the example usage for android.net Uri fromFile.

Prototype

public static Uri fromFile(File file) 

Source Link

Document

Creates a Uri from a file.

Usage

From source file:com.example.zf_android.trade.ApplyDetailActivity.java

private void setupItem(LinearLayout item, int itemType, final String key, final String value) {
    switch (itemType) {
    case ITEM_EDIT: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        EditText etValue = (EditText) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);//  w w  w .  j  av  a2s. co  m
        if (!TextUtils.isEmpty(value))
            etValue.setText(value);
        break;
    }
    case ITEM_CHOOSE: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        TextView tvValue = (TextView) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        if (!TextUtils.isEmpty(value))
            tvValue.setText(value);
        break;
    }
    case ITEM_UPLOAD: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        final TextView tvValue = (TextView) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        tvValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uploadingTextView = tvValue;
                AlertDialog.Builder builder = new AlertDialog.Builder(ApplyDetailActivity.this);
                final String[] items = getResources().getStringArray(R.array.apply_detail_upload);
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0: {
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent, REQUEST_UPLOAD_IMAGE);
                            break;
                        }
                        case 1: {
                            String state = Environment.getExternalStorageState();
                            if (state.equals(Environment.MEDIA_MOUNTED)) {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                File outDir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                                if (!outDir.exists()) {
                                    outDir.mkdirs();
                                }
                                File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
                                photoPath = outFile.getAbsolutePath();
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
                                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                                startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                            } else {
                                CommonUtil.toastShort(ApplyDetailActivity.this,
                                        getString(R.string.toast_no_sdcard));
                            }
                            break;
                        }
                        }
                    }
                });
                builder.show();

            }
        });
        break;
    }
    case ITEM_VIEW: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        ImageButton ibView = (ImageButton) item.findViewById(R.id.apply_detail_view);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        ibView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(ApplyDetailActivity.this, ImageViewer.class);
                i.putExtra("url", value);
                i.putExtra("justviewer", true);
                startActivity(i);
            }
        });
    }
    }
}

From source file:com.remobile.filetransfer.FileTransfer.java

/**
 * Downloads a file form a given URL and saves it to the specified directory.
 *
 * @param source URL of the server to receive the file
 * @param target Full path of the file on the file system
 *///from  ww w  .  j a  v a 2 s  .  c  om
private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "download " + source + " to " + target);
    final CordovaResourceApi resourceApi = new CordovaResourceApi(getReactApplicationContext());

    final boolean trustEveryone = args.optBoolean(2);
    final String objectId = args.getString(3);
    final JSONObject headers = args.optJSONObject(4);

    final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));

    // Accept a path or a URI for the source.
    Uri tmpTarget = Uri.parse(target);
    final Uri targetUri = resourceApi
            .remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target)));

    int uriType = CordovaResourceApi.getUriType(sourceUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;
    if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
        Log.e(LOG_TAG, "Unsupported URI: " + sourceUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection connection = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            File file = null;
            PluginResult result = null;
            TrackingInputStream inputStream = null;
            boolean cached = false;

            OutputStream outputStream = null;
            try {
                CordovaResourceApi.OpenForReadResult readResult = null;

                file = resourceApi.mapUriToFile(targetUri);
                context.targetFile = file;

                Log.d(LOG_TAG, "Download file:" + sourceUri);

                FileProgressResult progress = new FileProgressResult();

                if (isLocalTransfer) {
                    readResult = resourceApi.openForRead(sourceUri);
                    if (readResult.length != -1) {
                        progress.setLengthComputable(true);
                        progress.setTotal(readResult.length);
                    }
                    inputStream = new SimpleTrackingInputStream(readResult.inputStream);
                } else {
                    // connect to server
                    // Open a HTTP connection to the URL based on protocol
                    connection = resourceApi.createHttpConnection(sourceUri);
                    if (useHttps && trustEveryone) {
                        // Setup the HTTPS connection class to trust everyone
                        HttpsURLConnection https = (HttpsURLConnection) connection;
                        oldSocketFactory = trustAllHosts(https);
                        // Save the current hostnameVerifier
                        oldHostnameVerifier = https.getHostnameVerifier();
                        // Setup the connection not to verify hostnames
                        https.setHostnameVerifier(DO_NOT_VERIFY);
                    }

                    connection.setRequestMethod("GET");

                    // This must be explicitly set for gzip progress tracking to work.
                    connection.setRequestProperty("Accept-Encoding", "gzip");

                    // Handle the other headers
                    if (headers != null) {
                        addHeadersToRequest(connection, headers);
                    }

                    connection.connect();
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
                        cached = true;
                        connection.disconnect();
                        Log.d(LOG_TAG, "Resource not modified: " + source);
                        JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection,
                                null);
                        result = new PluginResult(PluginResult.Status.ERROR, error);
                    } else {
                        if (connection.getContentEncoding() == null
                                || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
                            // Only trust content-length header if we understand
                            // the encoding -- identity or gzip
                            if (connection.getContentLength() != -1) {
                                progress.setLengthComputable(true);
                                progress.setTotal(connection.getContentLength());
                            }
                        }
                        inputStream = getInputStream(connection);
                    }
                }

                if (!cached) {
                    try {
                        synchronized (context) {
                            if (context.aborted) {
                                return;
                            }
                            context.connection = connection;
                        }

                        // write bytes to file
                        byte[] buffer = new byte[MAX_BUFFER_SIZE];
                        int bytesRead = 0;
                        outputStream = resourceApi.openOutputStream(targetUri);
                        while ((bytesRead = inputStream.read(buffer)) > 0) {
                            outputStream.write(buffer, 0, bytesRead);
                            // Send a progress event.
                            progress.setLoaded(inputStream.getTotalRawBytesRead());
                            FileTransfer.this.sendJSEvent("DownloadProgress-" + objectId,
                                    JsonConvert.jsonToReact(progress.toJSONObject()));
                        }
                    } finally {
                        synchronized (context) {
                            context.connection = null;
                        }
                        safeClose(inputStream);
                        safeClose(outputStream);
                    }

                    Log.d(LOG_TAG, "Saved file: " + target);

                    file = resourceApi.mapUriToFile(targetUri);
                    context.targetFile = file;
                    result = new PluginResult(PluginResult.Status.OK, targetUri.getPath());
                }

            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
            } catch (Throwable e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
                Log.e(LOG_TAG, error.toString(), e);
                result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
            } finally {
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (connection != null) {
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) connection;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }

                if (result == null) {
                    result = new PluginResult(PluginResult.Status.ERROR,
                            createFileTransferError(CONNECTION_ERR, source, target, connection, null));
                }
                // Remove incomplete download.
                if (!cached && result.status.ordinal() != PluginResult.Status.OK.ordinal() && file != null) {
                    file.delete();
                }
                context.sendPluginResult(result);
            }
        }
    });
}

From source file:cn.kangeqiu.kq.activity.ChatActivity.java

/**
 * ?/*from  w  w  w  .  ja  v  a  2 s .c om*/
 */
public void selectPicFromCamera() {
    if (!CommonUtils.isExitsSdcard()) {
        String st = getResources().getString(R.string.sd_card_does_not_exist);
        Toast.makeText(getApplicationContext(), st, 0).show();
        return;
    }

    cameraFile = new File(PathUtil.getInstance().getImagePath(),
            BaseApplication.getInstance().getUserName() + System.currentTimeMillis() + ".jpg");
    cameraFile.getParentFile().mkdirs();
    startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(cameraFile)), REQUEST_CODE_CAMERA);
}

From source file:com.ximai.savingsmore.save.activity.AddGoodsAcitivyt.java

private void openCamera() {
    Uri imageUri = null;/*from w  ww  .j  a  v  a  2  s. co  m*/
    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    ImageTools.deletePhotoAtPathAndName(FileSystem.getCachesDir(this, true).getAbsolutePath(),
            PreferencesUtils.getString(this, "tempName"));
    String fileName = String.valueOf(System.currentTimeMillis()) + ".jpg";
    PreferencesUtils.putString(this, "tempName", fileName);
    imageUri = Uri.fromFile(new File(FileSystem.getCachesDir(this, true).getAbsolutePath(), fileName));
    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(openCameraIntent, PICK_FROM_CAMERA);
}

From source file:com.qiscus.sdk.ui.fragment.QiscusBaseChatFragment.java

@Override
public void onFileDownloaded(File file, String mimeType) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        intent.setDataAndType(Uri.fromFile(file), mimeType);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    } else {/*from  ww  w. ja v a2  s. com*/
        intent.setDataAndType(FileProvider.getUriForFile(getActivity(), Qiscus.getProviderAuthorities(), file),
                mimeType);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        showError(getString(R.string.chat_error_no_handler));
    }
}

From source file:com.example.carsharing.ShortWayActivity.java

@Override
public void onResume() {

    super.onResume(); // Always call the superclass method first

    shortway.setBackgroundDrawable(getResources().getDrawable(R.color.blue_0099cc));
    // Get the Camera instance as the activity achieves full user focus
    Context phonenumber = ShortWayActivity.this;
    SharedPreferences filename = phonenumber.getSharedPreferences(getString(R.string.PreferenceDefaultName),
            Context.MODE_PRIVATE);
    UserPhoneNumber = filename.getString("refreshfilename", "0");
    drawernum.setText(UserPhoneNumber);//  w w  w  .j a  v a2 s  .com
    Context context = ShortWayActivity.this;
    SharedPreferences sharedPref = context.getSharedPreferences(UserPhoneNumber, Context.MODE_PRIVATE);
    String fullname = sharedPref.getString("refreshname", "");
    drawername.setText(fullname);
    File photoFile = new File(this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), UserPhoneNumber);
    if (photoFile.exists()) {
        photouri = Uri.fromFile(photoFile);
        drawericon.setImageURI(photouri);
    } else {
        drawericon.setImageResource(R.drawable.ic_launcher);
    }
}

From source file:com.sim2dial.dialer.ChatFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ADD_PHOTO && resultCode == Activity.RESULT_OK) {
        if (data != null && data.getExtras() != null && data.getExtras().get("data") != null) {
            Bitmap bm = (Bitmap) data.getExtras().get("data");
            showPopupMenuAskingImageSize(null, bm);
        } else if (data != null && data.getData() != null) {
            String filePath = getRealPathFromURI(data.getData());
            showPopupMenuAskingImageSize(filePath, null);
        } else if (imageToUploadUri != null) {
            String filePath = imageToUploadUri.getPath();
            showPopupMenuAskingImageSize(filePath, null);
        } else {// w w  w .j  a va  2 s. c  o  m
            File file = new File(Environment.getExternalStorageDirectory(),
                    getString(R.string.temp_photo_name));
            if (file.exists()) {
                imageToUploadUri = Uri.fromFile(file);
                String filePath = imageToUploadUri.getPath();
                showPopupMenuAskingImageSize(filePath, null);
            }
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java

public void processResult(Intent data, int resultCode) {
    if (null == mUploadMessage)
        nullValueHandler();/*  ww w .ja  v  a  2 s.  c o  m*/

    Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();

    String filePath = result.getPath();

    Uri fileUri = Uri.fromFile(new File(filePath));
    if (isMedia) {
        ContentResolver cR = WebPlugin.this.getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String type = mime.getExtensionFromMimeType(cR.getType(result));
        fileUri = Uri.parse(fileUri.toString() + "." + type);

        data.setData(fileUri);
        isMedia = false;
    }

    mUploadMessage.onReceiveValue(fileUri);
    mUploadMessage = null;
}