Image browse not working in 5.1 android device

♀尐吖头ヾ 提交于 2020-01-13 06:29:26

问题


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

see above image i click on Photos application .

Button Click

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

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

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


回答1:


@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());
}

}


来源:https://stackoverflow.com/questions/31113514/image-browse-not-working-in-5-1-android-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!