图像浏览在5.1安卓设备中不起作用 [英] Image browse not working in 5.1 android device

查看:54
本文介绍了图像浏览在5.1安卓设备中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友,我想浏览我的画廊图像,所以下面是我的代码

Hello friends i want to browse my gallery image in my so below is my code

查看上面的图片,我点击照片应用程序.

see above image i click on Photos application .

按钮单击

protected void importImage() 
{
    Intent intent = new Intent(
            Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*");
    startActivityForResult(
            Intent.createChooser(intent, "Select File"),
            currentRequestCode);

}

onActivityResult

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

        if (requestCode == currentRequestCode) 
        {
            if (data!=null) {
                openGalleryImage(data);
                saveImage(uri_outputFileUri.getPath());
            }

        }
        else if (requestCode == REQUEST_CAMERA) {

            Bitmap thumbnail = null;

            try {
                thumbnail = (Bitmap) data.getExtras().get("data");
            } catch (Exception e) {
                // TODO: handle exception
            }


            try {
                if(thumbnail != null){
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    thumbnail.compress(Bitmap.CompressFormat.PNG, 100, bytes);

                    File file = new File(Environment.getExternalStorageDirectory()
                            + File.separator + Long.toString(System.currentTimeMillis())+".png");
                    file.createNewFile();
                    FileOutputStream fo = new FileOutputStream(file);
                    fo.write(bytes.toByteArray());
                    fo.close();
                    mStringGetImagePath = String.valueOf(file);
                    saveImage(mStringGetImagePath);
                    System.out.println("mStringGetImagePath "+mStringGetImagePath);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } 
}

openGalleryImage

private void openGalleryImage(Intent data) 
    {
        Uri selectedimg = data.getData();
        Uri uriselectedimage=data.getData();
        mString=uriselectedimage.getPath();
        try 
        {
            mInputStream=getActivity().getContentResolver().openInputStream(selectedimg);
        }
        catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }

        String[] path = { MediaStore.Images.Media.DATA };
        Cursor c = getActivity().getContentResolver().query(selectedimg, path, null, null,null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(path[0]);
        selectedimage_paths=c.getString(columnIndex);

        uri_outputFileUri= Uri.parse(selectedimage_paths);
        c.close();
    }

当我运行上面的代码时,它在此行给了我空指针错误 uri_outputFileUri = Uri.parse(selectedimage_paths);

When i run above code it gave me null pointer error at line this uri_outputFileUri= Uri.parse(selectedimage_paths);

此代码仅对5.0和5.1设备中的所有4.0、4.1、4.2、4.3、4.4设备都可运行

this code is runable to all 4.0 ,4.1,4.2,4.3,4.4 device only problem in 5.0and 5.1 device

推荐答案

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

    if (requestCode == YOUR_REQUEST_CODE && resultCode == RESULT_OK
            && data != null && data.getData() != null) {

        Uri selectedImageUri = data.getData();

        String[] projection = new String[] { MediaStore.MediaColumns.DATA };

        Cursor cursor = getContentResolver().query(selectedImageUri,
                projection, null, null, null);
        if (cursor.moveToFirst()) {
            String path = cursor.getString(0);
            System.out.println("MainActivity.onActivityResult() : " + path);
        }
        System.out.println(selectedImageUri.toString());
        // MEDIA GALLERY
        String selectedImagePath = ImgPath.getPath(MainActivity.this,
                selectedImageUri);

        if (selectedImagePath != null && !selectedImagePath.equals("")) {
            path = selectedImagePath;
        } else {
            AlertDialog alDailog = new AlertDialog.Builder(
                    MainActivity.this).setTitle("Image Upload")
                    .setMessage("Please Select Valid Image").create();
            alDailog.show();
            return;
        }
        loadFromPath(selectedImagePath);

    }
}

private void loadFromPath(String selectedImagePath) {
    try {
        if (selectedImagePath == null) {
            return;
        }
        Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
        imageView.setImageBitmap(bitmap);
    } catch (Exception e) {
        e.printStackTrace();
    }
}


public class ImgPath {

/**
 * Method for return file path of Gallery image
 * 
 * @param context
 * @param uri
 * @return path of the selected image file from gallery
 */
public static String getPath(final Context context, final Uri uri) {

    // check here to KITKAT or new version
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/"
                        + split[1];
            }
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection,
                    selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 * 
 * @param context
 *            The context.
 * @param uri
 *            The Uri to query.
 * @param selection
 *            (Optional) Filter used in the query.
 * @param selectionArgs
 *            (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri,
        String selection, String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = { column };

    try {
        cursor = context.getContentResolver().query(uri, projection,
                selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

/**
 * @param uri
 *            The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri
            .getAuthority());
}

/**
 * @param uri
 *            The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri
            .getAuthority());
}

/**
 * @param uri
 *            The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri
            .getAuthority());
}

/**
 * @param uri
 *            The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri
            .getAuthority());
}

}

这篇关于图像浏览在5.1安卓设备中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆