未找到图像,FileNotFoundException

时间:2016-02-19 17:26:56

标签: android

我正在开发应用程序,用户可以将照片放入recyclerview networkImageview,如下所示。我拍照但这张照片没有分配给networkImage。

以下行引发异常

internal class Timer
{
    private readonly TimeSpan _disposalTimeout;

    private readonly System.Threading.Timer _timer;

    private bool _disposeEnded;

    public Timer(TimeSpan disposalTimeout)
    {
        _disposalTimeout = disposalTimeout;
        _timer = new System.Threading.Timer(HandleTimerElapsed);
    }

    public event Signal Elapsed;

    public void TriggerOnceIn(TimeSpan time)
    {
        try
        {
            _timer.Change(time, Timeout.InfiniteTimeSpan);
        }
        catch (ObjectDisposedException)
        {
            // race condition with Dispose can cause trigger to be called when underlying
            // timer is being disposed - and a change will fail in this case.
            // see 
            // https://msdn.microsoft.com/en-us/library/b97tkt95(v=vs.110).aspx#Anchor_2
            if (_disposeEnded)
            {
                // we still want to throw the exception in case someone really tries
                // to change the timer after disposal has finished
                // of course there's a slight race condition here where we might not
                // throw even though disposal is already done.
                // since the offending code would most likely already be "failing"
                // unreliably i personally can live with increasing the
                // "unreliable failure" time-window slightly
                throw;
            }
        }
    }

    private void HandleTimerElapsed(object state)
    {
        Elapsed.SafeInvoke();
    }

    public void Dispose()
    {
        using (var waitHandle = new ManualResetEvent(false))
        {
            // returns false on second dispose
            if (_timer.Dispose(waitHandle))
            {
                if (!waitHandle.WaitOne(_disposalTimeout))
                {
                    throw new TimeoutException(
                        "Timeout waiting for timer to stop. (...)");
                }
                _disposeEnded = true;
            }
        }
    }
}
  

java.io.FileNotFoundException:没有内容提供者:   /storage/emulated/0/Pictures/JPEG_20160219_113457_-713510024.jpg

MainActivity Class

 InputStream is = context.getContentResolver().openInputStream(uri);

RecylerViewAdapter

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
        String path = ImageUtil.camPicturePath;
        mCurrentItem.setPath(path);
        mAdapter.notifyDataSetChanged();
        mCurrentItem = null;
        mCurrentPosition = -1;
    }
}

ImageUtilClass

@Override
    public void onBindViewHolder(final ListViewHolder holder, int position) {
        PostProductImageLIst item = mItems.get(position);
        ImageUtil.getInstance().setSelectedPic(holder.imgViewIcon, item.getPath());
    }

2 个答案:

答案 0 :(得分:2)

您似乎正在传递uri而不是URL。

InputStream is = (InputStream) new URL(encodedurl).getContent();
             Bitmap d = BitmapFactory.decodeStream(is);

Android BitmapFactory.decodeStream(...) doesn't load HTTPS URL on emulator

 File file = new File(url);
        BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream fis = new FileInputStream(f);
            Bitmap b= BitmapFactory.decodeStream(fis, null, o);
            fis.close();


public void showCamera() {
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    File photo = new File(Environment.getExternalStorageDirectory(),
            Calendar.getInstance().getTimeInMillis() + ".jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);
    startActivityForResult(intent, CAMERA_INTENT_CALLED);
}

if (requestCode == CAMERA_INTENT_CALLED) {

                Uri selectedImage = imageUri;
                try {
                    if (selectedImage != null) {
                        getContentResolver().notifyChange(selectedImage, null);
                        String path = getRealPathFromURI(selectedImage);
                        Log.e("Imagepath Camera", path);
                        imageUri = null;
                    }
            } catch (Exception e) {

                Log.e("Camera", e.toString());

            }

        }

private String getRealPathFromURI(Uri contentURI) {
    Cursor cursor = getContentResolver().query(contentURI, null, null,
            null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file
                            // path
        return contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor
                .getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }
}

答案 1 :(得分:2)

从相机和相册中拍照时,您需要小心。首先,您需要正确处理Intent以获取照片。下面我报告了构建它的可能实现。

如果你需要从相机和画廊获取照片。

public Intent buildPicturePickerIntent(PackageManager packageManager) {
    // Camera
    final List<Intent> cameraIntents = new ArrayList<>();
    final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for (ResolveInfo res : listCam) {
        final String packageName = res.activityInfo.packageName;
        final Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        cameraIntents.add(intent);
    }
    // Filesystem
    final Intent galleryIntent = new Intent();
    galleryIntent.setType("image/*");
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    // Chooser of filesystem options
    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
    // Add the camera options
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
            cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
    // returning intent
    return chooserIntent;
}

重要的是onActivityResult的实施必须处理从相机拍摄的照片和以不同方式从照片库拍摄的照片。您可以在下面看到示例代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_CODE && resultCode == RESULT_OK) {
        Uri uri = data.getData();
        // photo from gallery?
        if (uri != null) {
            // yes, photo from gallery
            String path = uri.toString();
            // use path here
            // ... 
        } else {
            // no, photo from camera
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            // store bitmap (eventually scaling it before) 
            // in filesystem here and get absolute path
            // ...                
        }
        // do your common work here (e.g. notify UI)
    }
} 

在文件系统上存储Bitmap时要小心两件事:

  • 存储新的位图时,您将拥有其绝对路径。当然你可以使用它,但如果你想以相同的方式管理来自相机的照片和来自图库的照片,你需要进行从绝对路径到内容URI的转换。你可以在这里找到很多关于这个问题的答案。
  • 如果您的目标是API 23,则需要明确处理存储权限。否则,当您尝试在Android 6设备上从摄像头拍摄的位图存储时,您将收到“权限被拒绝”错误。

Here您可以找到从图库/相机中挑选图片的示例代码,并相应地更新回收商视图项。