Shazniq
Shazniq

Reputation: 453

Android File System - Can't write on file even though I have permissions

I am trying to make a program that deletes files programmatically. My program has the write & read permissions.

The code can be oversimplified to this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    File asd = new File("/storage/emulated/0/Pictures/IMG_20210228_165109.jpg ");
    System.out.println(asd.exists());//true
    System.out.println(asd.setWritable(true));//true
    System.out.println(asd.canWrite());//false
    System.out.println(asd.delete());//false
}

Yes, I hardcoded the example but you get the point, the real program is not hardcoded. Both the example and the real program fail to delete files like this.

I tried on Android Emulator of android studio and my phone. Both times the result was same - true on exists() and setWritable() but false on canWrite() and delete().

Why is that the case? (The android version of my phone is 10, and emulator's is 11.)

Upvotes: 0

Views: 837

Answers (1)

blackapps
blackapps

Reputation: 9282

Three things.

Request read and write permission in manifest.

Add code to let the user confirm those permissions at run time.

For an Android 10 device request legacy external storage in manifest.

On an Android 11 device an app can only delete its own files.

Upvotes: 1

Related Questions