1234567
1234567

Reputation: 2485

unable to delete file in Android lollipop and higher

I am trying following code

String Data = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));

     File file = new File(Data);
    if (file != null && file.exists()) {
                           // delete it
                           Toast.makeText(FileEditorDialog.this, "deleted not null",
                                   Toast.LENGTH_LONG).show();
                       }


                       boolean deleted = file.delete();


                       if (deleted) {
                           Toast.makeText(FileEditorDialog.this,
                                   "Successfully Deleted", Toast.LENGTH_LONG).show();

                           sendBroadcast(new Intent(
                                   Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                   Uri.parse("file://"
                                           + Environment.getExternalStorageDirectory())));
                           finish();
                       }

This code works in Android jelly bean but not in Android lollipop how can we delete files in Android lollipop?

Upvotes: 0

Views: 139

Answers (2)

Sohail Zahid
Sohail Zahid

Reputation: 8149

You have to get Runitme permissions from user in android 6.0 only declaring them manifest is not enough.

Look here in my earlier answer to this.

Upvotes: 1

Joe Richard
Joe Richard

Reputation: 1520

Try Dexter library to check permission - WRITE_EXTERNAL_STORAGE

make sure that you have permission in AndroidManifest.xml

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

this is optional but library called Dexter easier handling instant permissions. add this dependency to build.gradle(app)

compile 'com.karumi:dexter:2.2.2'

Create application class:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        Dexter.initialize(getApplicationContext());
    }

}

and set it in your AndroidManifest.xml

<application
       android:name=".MyApplication"

use this piece of code to ask user permission.

                Dexter.checkPermission(new PermissionListener() {
                @Override public void onPermissionGranted(PermissionGrantedResponse response) {

                    deleteFile();//call the method to delete file

                }
                @Override public void onPermissionDenied(PermissionDeniedResponse response) {
                    Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_LONG).show();
                }
                @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }, Manifest.permission.WRITE_EXTERNAL_STORAGE);

Upvotes: 1

Related Questions