user3428781
user3428781

Reputation: 11

How can I format SD card in android application programmatically?

How can i format the SD card inside the mobile by implementing the code for "formatting SD card" in an application? im currently using this code, but i cant get it to work.

    public void wipingSdcard(View view) {
        File deleteMatchingFile = new File(Environment
                .getExternalStorageDirectory().toString());
        try {
            File[] filenames = deleteMatchingFile.listFiles();
            if (filenames != null && filenames.length > 0) {
                for (File tempFile : filenames) {
                    if (tempFile.isDirectory()) {
                        wipeDirectory(tempFile.toString());
                        tempFile.delete();
                    } else {
                        tempFile.delete();
                    }
                }
            } else {
                deleteMatchingFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void wipeDirectory(String name) {
        File directoryFile = new File(name);
        File[] filenames = directoryFile.listFiles();
        if (filenames != null && filenames.length > 0) {
            for (File tempFile : filenames) {
                if (tempFile.isDirectory()) {
                    wipeDirectory(tempFile.toString());
                    tempFile.delete();
                } else {
                    tempFile.delete();
                }
            }
        }
    }

And i am also using android:onClick="wipingSdcard" in my xml.code for the "format sd card" button.

What am i doing wrong?

Upvotes: 1

Views: 2026

Answers (3)

Dana Prakoso
Dana Prakoso

Reputation: 51

Actually, you cannot format an SD Card by deleting all of its files and folders. Imagine that SD Card is unformatted, you can't just delete the files inside it, because the operating system doesn't know what filesystem it uses.

Upvotes: 1

lucidbrot
lucidbrot

Reputation: 6168

Does wipeDirectory(tempFile.toString()); give the right parameter?

I mean, is tempFile.toString() the same as tempFile.getPath().toString() ? It could be this.

Upvotes: 0

CodeWalker
CodeWalker

Reputation: 2388

Include these permissions, too.

MOUNT_FORMAT_FILESYSTEMS

MOUNT_UNMOUNT_FILESYSTEMS

Upvotes: 0

Related Questions