Search code examples
androidlistactivity

List file in ListActivity and Delete on Click


I am using this code to list the files in directory:

    void ListDir(File f){
     File[] files = f.listFiles();
     fileList.clear();
     for (File file : files){
      fileList.add(file.getPath());  
     }

     ArrayAdapter<String> directoryList
     = new ArrayAdapter<String>(this,
       android.R.layout.simple_list_item_1, fileList);
     setListAdapter(directoryList); 
    }

How to delete the file by on click? I have search about onListItemClick. To delete the file, I need:

File file = new File(uri.getPath());
            file.delete();

How to pass the ArrayList to uri?


Solution

  • Register a item click listener for list view:

        listView.setOnItemClickListener(new OnItemClickListener() {
    
                  @Override
                  public void onItemClick(AdapterView<?> parent, View view,
                     int position, long id) {
    
                     File file = new File(fileList.get(position));
                     if(file.exists()){
                         file.delete();
                     }
                  }
    
             });