最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Android ContentResolver.query does not find a path, but "insert" fails with UNIQUE constraint failed - Stack O

programmeradmin2浏览0评论

I have an Android function that is used to create an Uri from the File, for the sharing Intent.

The function first checks the content provider, if such a file path is already in the database. If it is, the Uri is returned. If not, the new file path is inserted.

    public static Uri getMediaContentUri(Context context, File file) {
        String filePath = file.getAbsolutePath();
        try (Cursor cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[] {MediaStore.Images.Media._ID},
            MediaStore.Images.Media.DATA + "=? ",
            new String[] {filePath}, null)) {

            if ((cursor != null) && cursor.moveToFirst()) {
                @SuppressLint("Range")
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                return Uri.withAppendedPath(baseUri, Integer.toString(id));
            }
            else if (file.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            }
            return null;
        }
    }

For most of the files, it is working properly. But for some (specifically the files downloaded from the Android Facebook app into the ".../DCIM/Facebook" directory), it does not work. The query part does not return any record in the cursor, so the function then tries to insert the record, but it throws and exception:

android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: files._data (code 2067 SQLITE_CONSTRAINT_UNIQUE[2067])

I don't remember, if I noticed this problem for any other files except those from FB app.

Why would the ContentProvider.query not return the record, which obviously exists, if the insert fails?

If the record exists in the database, ContentProvider.query should return it, but in some cases, it does not.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论