2015-06-29 2 views
0

Я получаю неправильное имя файла, когда я выбираю файл из галереи. Я не знаю, что не так в моем коде. любая помощь очень ценится благодаряAndroid Studio - получить изображение/видеофайл из Uri

Это мой метод SelectFile в моем классе AreaFragment продлить фрагмент

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); 

      } 
     } 
    } 

ответ

0

сначала вам нужно, чтобы получить правильный путь из и затем используйте file.getName(), чтобы получить имя файла, попробуйте, это сработает.

   String[] proj = { MediaStore.Video.Media.DATA }; 
      String result = null; 

      CursorLoader cursorLoader = new CursorLoader(
        getActivity(), 
       uri, proj, null, null, null);   
      Cursor cursor = cursorLoader.loadInBackground(); 

      if(cursor != null){ 
       int column_index = 
       cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA); 
       cursor.moveToFirst(); 
       result = cursor.getString(column_index); 
       Log.d("file path", result); 
Смежные вопросы