Android Question Can not delete file using content chooser

microbox

Active Member
Licensed User
Longtime User
Hi I know this might be very easy but I'm having trouble deleting file (image) in gallery folder.

B4X:
Sub CC_Result (Success As Boolean, Dir As String, FileName As String)
    Dim vDir, vFile As String
    Dim x,y As Int
    If Success = True Then
        Try
            imgefileuploader.Bitmap = LoadBitmap(Dir,FileName)
            Log("Dir: " & FileName)
            vDir = GetPathFromContentResult(FileName)
            Log(vDir)
            x = CountChar(vDir,"/")
            Log(x)
            y = IndexOfNth(vDir, "/", x)
            Log(y)
            Dim a,b As String
            a = vDir.SubString2(0,y)
            b = vDir.SubString(y+1)
            Log(File.Exists(a,b)) ' prints true
    
            If File.Delete(a, b.) Then
                Log("File deleted")
            Else
                Log("File not deleted")
            End If
           ' 'ImageConverter(a, b) ' test this later
        Catch
            Log("Bitmap load error")
        End Try
    Else
        ToastMessageShow("No file selected",True)
    End If   
End Sub

Sub GetPathFromContentResult(UriString As String) As String
  If UriString.StartsWith("/") Then Return UriString 'If the user used a file manager to choose the image
  Dim Cursor1 As Cursor
  Dim Uri1 As Uri
  Dim Proj() As String = Array As String("_data")
  Dim crs As ContentResolver
  crs.Initialize("")
  If UriString.StartsWith("content://com.android.providers.media.documents") Then
  Dim i As Int = UriString.IndexOf("%3A")
  Dim id As String = UriString.SubString(i + 3)
  Uri1.Parse("content://media/external/images/media")
  Cursor1 = crs.Query(Uri1, Proj, "_id = ?", Array As String(id), "")
  Else
  Uri1.Parse(UriString)
  Cursor1 = crs.Query(Uri1, Proj, "", Null, "")
  End If
  Cursor1.Position = 0
  Dim res As String
  res = Cursor1.GetString("_data")
  Cursor1.Close
  Return res
End Sub

ACanNotDel.PNG


The logs shows that file exist in this path "/storage/emulated/0/DCIM/Camera" but failed to delete.

Thanks for your valuable time,
microbox
 
Last edited:

LucaMs

Expert
Licensed User
Longtime User
1. It is a mistake to use GetPathFromContentResult.
Sometimes you cannot access the file using Dir and FileName returned by the Result event, although Success is true and using GetPathFromContentResult solves the problem (I think that function was written just for this reason).

So, why is it a mistake? And what should be done instead?
 
Upvote 0
Top