Android Studio - 从Uri获取图像/视频文件名

时间:2015-06-29 02:25:02

标签: java android android-studio android-camera-intent

当我从Gallery中选择文件时,我收到了错误的文件名。我不知道我的代码有什么问题。非常感谢任何帮助

这是我的类AreaFragment extend Fragment

中的selectFile方法
public void selectFile(){
        final CharSequence[] items = {"Camera","Select image","Select video","Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Add file");
        builder.setIcon(R.drawable.ic_photo_black_24dp);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Camera")) {
                    Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(i, REQUEST_CAMERA);
                } else if (items[item].equals("Select image")) {
                    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    i.setType("image/*");
                    startActivityForResult(Intent.createChooser(i, "Select image"), PICK_IMAGE);
                } else if (items[item].equals("Select video")) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("video/*");
                    startActivityForResult(Intent.createChooser(intent, "Select video"), PICK_VIDEO);
                }else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

这是我的onActivityResult

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        final ImageView add_task_images = (ImageView) promptsView.findViewById(R.id.img_task_preview);
        final LinearLayout image_wrapper = (LinearLayout) promptsView.findViewById(R.id.image_task_wrapper);
        final VideoView video_task_preview = (VideoView) promptsView.findViewById(R.id.video_task_preview);
        final LinearLayout video_task_wrapper = (LinearLayout) promptsView.findViewById(R.id.video_task_wrapper);
        final TextView video_file_name = (TextView) promptsView.findViewById(R.id.video_file_name);
        final TextView image_file_name = (TextView) promptsView.findViewById(R.id.image_file_name);

        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {
                Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

                File destination = new File(Environment.getExternalStorageDirectory(),
                        System.currentTimeMillis() + ".jpg");

                FileOutputStream fo;
                try {
                    destination.createNewFile();
                    fo = new FileOutputStream(destination);
                    fo.write(bytes.toByteArray());
                    fo.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                selectedImagePath = destination.getPath();

                String img_name = destination.getName();
                image_file_name.setText("File name: " + img_name ); // Get the wrong file name

                image_wrapper.setVisibility(View.VISIBLE);
                add_task_images.setImageBitmap(thumbnail);

            } else if (requestCode == PICK_IMAGE) {
                Uri selectedImageUri = data.getData();
                String[] projection = {MediaStore.MediaColumns.DATA};
                Cursor cursor = getActivity().managedQuery(selectedImageUri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();

                selectedImagePath = cursor.getString(column_index);

                Bitmap bm;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(selectedImagePath, options);
                final int REQUIRED_SIZE = 200;
                int scale = 1;
                while (options.outWidth / scale / 2 >= REQUIRED_SIZE
                        && options.outHeight / scale / 2 >= REQUIRED_SIZE)
                    scale *= 2;
                options.inSampleSize = scale;
                options.inJustDecodeBounds = false;
                bm = BitmapFactory.decodeFile(selectedImagePath, options);
                add_task_images.setImageBitmap(bm);

                String path = selectedImageUri.getPath();
                File image_name = new File(path);
                image_file_name.setText("File name: " + image_name.getName()); // Get the wrong file name

                image_wrapper.setVisibility(View.VISIBLE);

            } else if(requestCode == PICK_VIDEO){

                Uri videoUri = data.getData();
                video_task_preview.setVideoURI(videoUri);

                String path = videoUri.getPath();
                File filepath = new File(path);
                video_file_name.setText("File name: " + filepath.getName()); //Get the wrong file name

                video_task_wrapper.setVisibility(View.VISIBLE);

            }
        }
    }

1 个答案:

答案 0 :(得分:0)

首先你需要获取媒体的有效路径,然后使用file.getName()来获取文件名,试试这个就行了。

if let slat = startlat {
    if let slng = self.startlng {
        if let elat = self.endlat {
            if let elng = self.endlng {
                Alamofire.request(.GET, "https://maps.googleapis.com/maps/api/directions/json?origin=\(slat,slng)&destination=\(elat,elng)" , encoding: .JSON)
                .responseJSON { response in
                    let res = response.result.value!
                    self.estimatedDistance = (res["routes"]!![0]["legs"]!![0]["distance"]!!["value"] as! Int)/1000
                    self.estimatedTime = (res["routes"]!![0]["legs"]!![0]["duration"]!!["value"] as! Int)/60
                    print("\(self.estimatedDistance) - \(self.estimatedTime)")

               }
            }
        }
    }
}