2013-08-19 77 views
1

我有一個列表,顯示我指定的目錄中的項目列表。我創建了一個onLongClickListener,彈出一個對話框進行確認。當用戶按下對話框上的確定按鈕時,我需要刪除SD卡上的實際文件。我查看了Stack Overflow上找到的所有示例,但發現沒有任何示例適用於我。刪除文件listitem鏈接到SD卡上

public class ReadFilesFromPath extends Activity { 
/** Called when the activity is first created. */ 
List<String> myList; 
File file; 
ListView listview; 
ArrayAdapter<String> adapter; 
String value; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.recordinglist); 
Intent intent = getIntent(); 
value = intent.getStringExtra("path"); //if it's a string you stored. 
listview = (ListView) findViewById(R.id.recordlist); 
myList = new ArrayList<String>(); 
onitemclick(); 
File directory = Environment.getExternalStorageDirectory(); 
file = new File(directory + "/" + "Recordify"); 
File list[] = file.listFiles(); 

for(int i=0; i< list.length; i++) 
{ 
     myList.add(list[i].getName()); 
} 
adapter = new ArrayAdapter<String>(this, 
     android.R.layout.simple_list_item_1, android.R.id.text1, myList); 
listview.setAdapter(adapter); //Set all the file in the list. 
longclick(); 
} 

public void longclick() { 
    listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 

     public boolean onItemLongClick(AdapterView<?> arg0, View v, //when long pressed 
       int pos, long arg3) { 
      AlertDialog.Builder adb=new AlertDialog.Builder(ReadFilesFromPath.this); //alert for each time an item is pressed 
       adb.setTitle("Delete?"); 
       adb.setMessage("Are you sure you want to delete this recording?"); 
       final int positionToRemove = pos; 
       adb.setNegativeButton("Cancel", null); 
       adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() { 

        public void onClick(DialogInterface dialog, int which) { 
         listview.animate().setDuration(500).alpha(0) //animates a smooth deletion animation 
         .withEndAction(new Runnable() { 
          @Override 
          public void run() { 
          file.delete(); 
          myList.remove(positionToRemove); //removes the selected item from the list but not on SD card 
//this is where I need my code to delete it on the SD card to go. 
          adapter.notifyDataSetChanged(); //tells the adapter to delete it 
          listview.setAlpha(1); 
          } 
         }); 
        }}); 
       adb.show(); 
       return false; 
       } 
      }); 

     } 

} 

回答

0

你嘗試過:

new File(path).delete() 
+0

我試過「file.delete」,但不是「new File(path).delete()。是否有區別? – ThatGuyThere

+0

Ad是看到的,文件可變是包含文件列表的目錄,你需要刪除它們中的每一個 – Tishka17

0
String file_name = file_list.get(position); 
String MEDIA_PATH = new String(Environment.getExternalStorageDirectory() + "/AudioRecorder/" + file_name); 
File file = new File(MEDIA_PATH); 
file.delete(); 
file_list.remove(position); 
notifyDataSetChanged(); 

使用此在單擊事件處理程序。