如何在Android 4.4中的onActivityResult中获取文件路径

2023-12-14

对于 android 4.3 及更早版本,我使用此方法:

Uri myUri = data.getData();
Cursor cursor = getContentResolver().query(myUri,new String []{"_data"}, null, null, null);
cursor.moveToFirst();
String filePath = cursor.getString(cursor.getColumnIndex("_data"));
cursor.close();

但对于 Android kitKat 它返回 null


            import android.content.ContentUris;
            import android.content.Context;
            import android.database.Cursor;
            import android.net.Uri;
            import android.os.Build;
            import android.os.Environment;
            import android.provider.DocumentsContract;
            import android.provider.MediaStore;

            public class ImageFilePath {

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


                onActivityResult you have to write

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

                    super.onActivityResult(requestCode, resultCode, data);
                    if (resultCode == Activity.RESULT_OK) {
                        if (requestCode == SELECT_PHOTO) {
                            if (null == data)
                                return;


                            Uri selectedImageUri = data.getData();
                            System.out.println(selectedImageUri.toString());
                            // MEDIA GALLERY
                            selectedImagePath = ImageFilePath.getPath(
                                    getActivity(), selectedImageUri);
                            Log.i("Image File Path", "" + selectedImagePath);
                            System.out.println("Image Path ="+selectedImagePath);
                            if(selectedImagePath!=null&&!selectedImagePath.equals(""))
                            {
                                uploadImageOnServer upImg = new uploadImageOnServer();
                                upImg.execute();
                            }
                            else
                            {
                                AlertDialogManager alDailog = new AlertDialogManager(getActivity(), "Image Upload", "Please Select Valid Image", 0);
                                alDailog.showDialog();
                            }



                        }
                    }

                }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Android 4.4中的onActivityResult中获取文件路径 的相关文章

  • 如何设置长PreferenceScreen的滚动位置

    Android 应用程序有一些很长的首选项屏幕 它们始终在首选项菜单的顶部打开 我知道用户想要在首选项菜单中的位置 如何强制打开首选项屏幕并滚动到特定的首选项项目 我知道这是一个旧问题 所以这个答案仅供参考 要自动选择给定屏幕 您所要做的就
  • 带身份验证的 MediaPlayer RTSP 视频流

    我能够在未经授权的情况下从网络摄像机流式传输视频 但现在我需要在授权的情况下执行此操作 我发现很少有信息表明 Android 不支持 RTSP 身份验证 但我发现另一条信息表明 通过使用该方法添加标头 可以在 API 级别 14 中实现身份
  • Android:动态更改Listview中的图像

    我有一个由以下 xml 定义的列表视图 我需要切换图像当用户单击任何行时 在运行时会出现在列表中 我怎样才能实现这个目标 非常感谢任何帮助 谢谢 list item xml
  • 如何增加 Gradle 守护进程的最大堆大小?

    签署 apk 时 我收到以下消息 To run dex in process the Gradle daemon needs a larger heap It currently has 1024 MB For faster builds
  • 在 Android 中从互联网链接获取数据

    我正在制作一个带有 URL 的应用程序 asp 扩展名 我们向其传递所需的参数并使用 POST 方法获取一些字符串结果 关于如何实现这一目标有什么建议吗 UPDATED 实际上我有一个 net 链接 它接受一些 POST 参数并给我一个结果
  • 在Android中打开浮动菜单(上下文菜单)?

    我创建了一个新菜单 名为 drmenu xml 当我按下菜单按钮时它可以正常工作 但是当用户按下按钮时我需要打开上下文菜单 下面的代码按钮只显示一个吐司 这是我的 xml 布局
  • Android异步服务调用策略

    这是场景 客户端对服务进行远程调用 返回 void 并提供 回调对象 服务在后台线程上执行一些长时间运行的逻辑 然后使用回调对象来触发以太成功或失败 因为这些操作视觉元素 执行 Activity runOnUiThread 块 该场景运行良
  • 不同风格的模块文件

    我正在尝试在同一个应用程序中实现播放服务和华为服务 但希望能够按风格配置使用哪一个 每种风格都使用自己的 applicationIdSuffix 因此 对于每种不同的风格 华为插件都会失败 我无法编译 我的应用程序模块包含agconnect
  • 如何修复运行 Android 模拟器时出现 GPU Driver Issue 错误

    我的 Android 模拟器几周前运行良好 但现在出现错误 当我运行代码时 GPU 驱动程序问题错误对话框与模拟器一起弹出 当我单击 确定 时 Android 模拟器不会按预期运行应用程序 错误如下 Your GPU driver info
  • Android Studio 停留在构建 gradle 项目信息上

    我正在使用 Android Studio 2 3 每当我尝试创建一个新项目或打开某个项目时 它都会卡在此时 正在构建 Gradle 项目信息 请建议我一些解决方案 它可能正在下载 Gradle zip 文件 e g Users user g
  • Android TabLayout:均匀分布

    我正在查看 Google IO 中使用的 Google 类 称为 SlidingTabLayout 在该类中 有一个名为 setDistributeEvenly 的方法 它允许所有这些选项卡在屏幕上均匀分布 每个选项卡具有相同的大小 中心对
  • 在一个react-native项目中使用谷歌地图和FCM

    I want to use google map and FCM in one react native project first I added FCM in project everything was okay but when I
  • Eclipse Android 模拟器 - 键盘不工作

    我刚刚更新到最新的 SDK 版本 16 使用最新版本的 API 16 创建了新版本的 AVD 并且我的硬件键盘在模拟器上不再工作 甚至我的其他 avd 使用旧版本的 sdk 任何想法如何解决这一问题 您的 AVD 的 键盘支持 硬件属性是否
  • android device.getUuids 返回 null

    我正在尝试使用低功耗蓝牙 BLE 通过 Android 应用程序连接到 Arduino Uno 我正在 Android Studio 上进行开发 使用 Samsung Galaxy S4 和 Android 版本 5 0 1 进行测试我点击
  • 应用程序运行时相对布局中的元素显示不同

    我有一个ListView在片段内创建 并且它有一个搜索过滤器 问题是 XML 布局在 android studio 中显示正常 但在模拟器或手机中运行时 它显示不同 与我对齐时不正确 并且当我单击SearchView它位于选项卡导航下方 谁
  • 如何在 Android 中不使用 Intent 裁剪图像

    我正在尝试裁剪图像我使用了下面的代码 意图 i new Intent Intent ACTION PICK android provider MediaStore Images Media EXTERNAL CONTENT URI i pu
  • 使用Android Camera API,拍摄照片的方向始终未定义

    我使用相机API 拍摄的照片总是旋转90度 我想旋转它 所以首先我想知道图片的方向 这一点我被卡住了 我总是以两种方式得到未定义的方向 这是代码 Override public void onPictureTaken byte data C
  • 不幸的是 Project_Name 已停止

    我有一个简单的应用程序 您可以在文本视图中输入文本并按提交 它会在另一个活动中显示文本 然而 当我按下提交时 给我消息 不幸的是 发送已停止 我查看了SO上的其他线程 但是不幸的是 myfirstproject 在 java 中停止工作错误
  • 如何在jetpack compose中删除文本基线下方的空间?

    目前我得到这个 但我想要这样的东西 而且 50 和 min 中的文本也应该与顶部对齐 My code Row verticalAlignment Alignment Bottom Text text 18 color MaterialThe
  • 如何在 Android 应用程序退出之前进行一些清理?

    当我的 Android 应用程序终止时 是否有某种 onTerminate 方法可以进行一些清理 我想清除一些 SharedPreferences 我有一个活动 它保持几个数字的运行平均值 并将其存储在 SharedPreference 中

随机推荐