0

I am trying to delete and rename audio files which are in Sd card so here is my code to display list of audio files from SD card.

// Use the current directory as title
    path = "/sdcard/";
    if (getIntent().hasExtra("path")) {
        path = getIntent().getStringExtra("path");
    }
    setTitle(path);

    // Read all files sorted into the values-array
    values = new ArrayList();
    File dir = new File(path);
    if (!dir.canRead()) {
        setTitle(getTitle() + " (inaccessible)");
    }
    final String[] list = dir.list();
    if (list != null) {
        for (String file : list) {
            if (file.contains(".3gp")) {
                values.add(file);
            }
        }
    }
    Collections.sort(values);
    // Put the data into the list
    adapter = new ArrayAdapter(this,
            android.R.layout.simple_list_item_2, android.R.id.text1, values);
    setListAdapter(adapter);

here i am able to display all music files but if i tried rename or delete operations then it is not effecting to files which are in SD card ,suggest me some solution plz CODE TO DELETE AND RENAME

case CONTEXT_MENU_DELETE:

Toast.makeText(
                this,
                "You selected item " + context_menu_number
                        + " from the context menu", Toast.LENGTH_SHORT)
                .show();
        Toast.makeText(
                this,
                "You removed item " + number_of_item_in_listview
                        + " from the list", Toast.LENGTH_SHORT).show();
        values.remove(number_of_item_in_listview);
        // myadapter.notifyDataSetChanged(); //if this does not work,
        // reinitialize the adapter:
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                values);
        myList.setAdapter(adapter);
        File f = new File(path + filename);
        if (f != null && f.exists()) {
            // delete it
            f.delete();
        }
        return (true);

2 Answers2

0

Try out below code to delete file from sdcard.

File file = new File(FilePath);
boolean deleted = file.delete();

where FilePath is the path of the file you want to delete - for example:

/sdcard/YourCustomDirectory/YourFile.mp3

Also give the permission

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

in AndroidManifest.xml file

GrIsHu
  • 29,068
  • 10
  • 64
  • 102
0

Add permission to write on external storage first in xml..

   String newName ="new Name";
   File oldFile = new File(Environment.getExternalStorageDirectory()+songName);

   File latestname = new File(Enviornment.get+ newName + ".mp3");
   boolean  success = oldFile .renameTo(latestname );
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300