【问题标题】:Delete a file from contentResolver only delete the entry from database (not file)从 contentResolver 中删除文件仅从数据库中删除条目(不是文件)
【发布时间】:2020-10-02 22:50:42
【问题描述】:

我尝试使用 contentResolver 删除文件,但只从数据库中删除条目,而不是真正的文件。所以我尝试先删除条目,然后再删除文件:

int rows = context.getContentResolver().delete(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
MediaStore.Audio.Media._ID + "=" + idSong, null);

// Remove file from card
if (rows != 0) {
Uri uri = ContentUris.withAppendedId(
        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, idSong);
File f = new File(uri.getPath());
if(!f.delete())
    Log.d("fail-2", "fail-2");  
}
else
Log.d("fail-1", "fail-1");

...输出为“fail-2”。为什么?

为什么 ContentResolver 不删除真实文件?这正常吗?

【问题讨论】:

    标签: android android-contentresolver mediastore


    【解决方案1】:

    这是有效的:

        // Remove entry from database
        int rows = context.getContentResolver().delete(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                MediaStore.Audio.Media._ID + "=" + idSong, null);
    
        // Remove file from card
        if (rows != 0) {
            try {
                File f = new File(path);
                if (f.delete())
                    return true;
            } catch (Exception e) {
                Log.d("MusicDB", "file: '" + path
                        + "' couldn't be deleted", e);
                return false;
            }
        }
        return false;
    

    但是为什么 contentResolver 不删除文件呢??

    【讨论】:

      【解决方案2】:

      似乎在 4.2 中,它会将文件归零,但不会删除它。我实际上希望它只是从 MediaStore 中删除它而不是从文件系统中删除它。不管怎样,这似乎是一个 Android 错误。

      我在更新文件时遇到了问题。我遇到的问题是媒体扫描仪不会在重新扫描时删除旧条目,因此您最终会得到两个条目。

      【讨论】:

        【解决方案3】:

        在 kotlin 中试试这个

           contentResolver.delete(
                  MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                  ,"_data" + "=?", 
                  arrayOf(path) )
        

        【讨论】:

          猜你喜欢
          • 2010-12-16
          • 2012-01-31
          • 1970-01-01
          • 2013-02-20
          • 2023-03-26
          • 2012-04-07
          • 1970-01-01
          • 2012-01-24
          • 2012-02-22
          相关资源
          最近更新 更多