0

I am creating an android application, and I created a list of available files in the internal memory with this instruction:

final String[] files =fileList();

I need to remove a file from this list and I don't know how, can you help me?

Vittorio
  • 1
  • 1
  • 1
  • 2
    You have declared the array as final, final variables cannot be changed. – JNL Oct 01 '13 at 20:12
  • 2
    JNL, to be clear, the value 'files' can not be reassigned, but the values (if there are any) in the array can change. Please see: http://stackoverflow.com/q/10339930/42962 – hooknc Oct 01 '13 at 20:31

2 Answers2

4

To "remove" something you can just set it back to null, or you can do it the hard way with a loop that shifts everything behind it up a place.

public void remove( int index ) { 
    for(int i=index; i<sarr.length()-1; i++) { 
        sarr[i] = sarr[i+1] 
    } 
    sarr[sarr.length()-1] = null; 
    System.out.println("Removed!"); 
} 

When using primitive arrays like this, there is no removal method. If you built a more complex datatype you could have the "remove" method available to you.

Max
  • 792
  • 1
  • 8
  • 20
2

Use a List<String> instead. That way you can remove the file that you want using the remove() method.

index = 0//location of item to be removed, with the first item in the list at 0
List<String> files = Arrays.asList(getFiles());
files.remove(index)

in this example, index is the location of the item that you want to remove. Alternatively, you could do this instead

item = "fileLocation";
List<String> files = Arrays.asList(getFiles());
files.remove(item)
jcw
  • 5,132
  • 7
  • 45
  • 54