0

I have a project in android and I want to select multiple image from the gallery and then delete file or rename file. But both of them are not working and I dont know why!

public void fileRename(Uri uri){
//File file=new File(uri.getPath());
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,
        filePathColumn, null, null, null);
cursor.moveToFirst();
File file=new File(cursor.getString(cursor.getColumnIndex(filePathColumn[0])));
if(file.exists()){
    boolean del=file.delete();
    if(del){
        Toast.makeText(this, "Trueee", Toast.LENGTH_SHORT).show();
    }
}
Reza Rahemtola
  • 1,182
  • 7
  • 16
  • 30
Sobhan
  • 98
  • 11
  • Do not mess around with the File class. MediaStore has a .delete(uri) member. Further: not working is a bad description as we have no idea what happens instead. – blackapps Jul 22 '21 at 06:55
  • Blackapps do you mean: MediaStore.createDeleteRequest(getContentResolver(), Collections.singleton(uri))? – Sobhan Jul 22 '21 at 07:02
  • No. Never saw that one. No, getContentResolver().delete(uri). – blackapps Jul 22 '21 at 07:03
  • I try two soloution: 1-getApplicationContext.getContentResolver().delete(uri,null,null) 2-getContentResolver().delete(uri,null) but cant delete file – Sobhan Jul 22 '21 at 07:29
  • Which errors do you get.? And you delete an uri. Whre would be that file? We have no idea what you are doing. Show code how to obtain that uri. Then show the delete code. And tell what happens instead. Logcat. Exceptions. Errors. – blackapps Jul 22 '21 at 07:44
  • oh..my code have result in api<28 and delet file..but in 29 and 30 cant... – Sobhan Jul 22 '21 at 09:17
  • Try the below method after delete like file.delete() mediaScannerConnection.scanfile(context,array of(1),arrayof("jpeg"),null) hope it may help you. Read it https://developer.android.com/reference/android/media/MediaScannerConnection – gpuser Jul 22 '21 at 11:11

1 Answers1

1

I solution problem with this code; First add this permission in Manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

and for API 29 add this to application tag:

android:requestLegacyExternalStorage="true"

and next step get permission from users:

if(!checkPermission()){
        requestPermission();
    }

and function:

    private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        try {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName())));
            startActivityForResult(intent, 2296);
        } catch (Exception e) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
            startActivityForResult(intent, 2296);
        }
    } else {
        //below android 11
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, 10);
    }
}


private boolean checkPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        return Environment.isExternalStorageManager();
    } else {
        int result = 0;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            result = context.checkSelfPermission(READ_EXTERNAL_STORAGE);
            int result1 = context.checkSelfPermission(WRITE_EXTERNAL_STORAGE);
            return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
        }
        }
    return true;
}

and get image from user like this: get image from user

and next delete from storage with this code:

    public void fileDelete(Uri uri){

    final String docId;
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        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;
        }
        String selection = "_id=?";
        String[] selectionArgs = new String[]{split[1]};


        String temp=getDataColumn(context, contentUri, selection,
                selectionArgs);
        File file=new File(temp);
        if(file.exists()){
            if(file.delete()){
                Toast.makeText(context, "deleted", Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(context, "not Deleted", Toast.LENGTH_SHORT).show();
            }
        }

    }else if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        File file=new File(cursor.getString(cursor.getColumnIndex(filePathColumn[0])));
        if(file.exists()){
            if(file.delete()){
                Toast.makeText(this, "deleted", Toast.LENGTH_SHORT).show();
                if(file.exists()){
                    Toast.makeText(this, "Exist", Toast.LENGTH_SHORT).show();
                }
            }
            else Toast.makeText(this, "Not Exist", Toast.LENGTH_SHORT).show();
        }
    }}


private 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;
}

and for refresh gallery use this code:

    MainActivity.this.sendBroadcast(new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE",Uri.fromFile(file)));
Sobhan
  • 98
  • 11