Android 将图像保存到外部存储,但 ContentResolver.insert 始终返回 null

标签 android image android-contentresolver

我正在编写一个 Android 应用程序,并试图将位图保存到外部存储器中。 我的代码如下。

        ContentValues contents = new ContentValues();
        String curTime = AppSetting.currentDateString();
        contents.put("title", curTime);         
        contents.put("display_name", curTime);
        contents.put("description", curTime);
        contents.put("datetaken", Long.valueOf(System.currentTimeMillis()));
        contents.put("mime_type", "image/jpeg");
        String path = Environment.getExternalStorageDirectory().toString() + "/dcim/camera";
        String hashPath = String.valueOf(path.hashCode());
        String displayName = (new File(path)).getName().toLowerCase();
        contents.put("bucket_id", hashPath);
        contents.put("bucket_display_name", displayName);
        Uri uri = this.getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, contents);//this is always null!!!
        BufferedOutputStream oStream = new BufferedOutputStream(this.getContentResolver().openOutputStream(uri));
        bmp.compress(CompressFormat.JPEG, 100, oStream);
        oStream.close();

但 uri 始终为 null。 在做一些研究时,我发现消息来源表明这是因为 Activity 被破坏并重新创建。为了解决这个问题,我将上面的代码添加到 Activity 的 OnCreate() 中,但我仍然得到相同的结果。
我测试了几个 Android 设备,但 uri 始终为空。 有什么建议吗?

最佳答案

我发现了我的问题。
我用以下宏替换了显示名称,它起作用了。

MediaStore.Images.ImageColumns.DISPLAY_NAME

结果我发现这不是“display_name”,它有下划线前缀:“_display_name”。
希望这可以帮助。

关于Android 将图像保存到外部存储,但 ContentResolver.insert 始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21095971/

相关文章:

javascript - 在 web2py 中更新图像

javascript - 可拖动的 jQuery 轮播定制

android - 内容提供者 - 多个 where 参数

Android:对 CONTENT_URI 的 sql 查询

java - 如何解决在另一个 Activity 中搜索标题打不开实际描述的问题?

java - 有没有办法用Java代码获得只有数字(没有小数,空格)的Android软键盘?

android - 从 C++ 调用 Android 调试方法

java - android 中的 arraylist 内的 arraylist

python - 如何从 Python 中的像素值列表创建 PNG 图像文件?

Android,检测哪个应用程序正在发送短信?