如何让文件管理器删除文件?

时间:2013-06-02 15:34:42

标签: java android file-manager

我正在尝试让文件管理器从sdcard中删除文件。只有一个路径“/ sdcard / Soundcast /”,我希望能够从中删除.mp4和.3gp的文件。这是我的代码:

公共类MainActivity扩展了ListActivity {

private List<String> items =null;

private void deleteFile()
{
    // TODO: Implement this method
}

@Override
public void onCreate(Bundle icicle)
{
    super.onCreate(icicle);
    setContentView(R.layout.main);

    getFiles(new File("/sdcard/Soundcast").listFiles()); }
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{ int selectedRow = (int)id; if (selectedRow == 0)
    { getFiles(new File("/sdcard/Soundcast").listFiles()); }
    else
    { File file = new File(items.get(selectedRow)); if (file.isDirectory())
        { getFiles(file.listFiles()); }
        else
        {
            new AlertDialog.Builder(this) .setTitle("Ability to open files will come in future updates.")
            .setMessage("Do You Want To Delete this recording?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int button){
                    deleteFile();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int button){
                }
            }).show();}
            }
            }
private void getFiles(File[] files)
{ items = new ArrayList<String>();

    items.add(getString(R.string.goto_root)); for (File file : files)
    { items.add(file.getPath()); }

    ArrayAdapter<String> fileList = new ArrayAdapter<String>(this, R.layout.file_list_row, items);
    setListAdapter(fileList); } }

2 个答案:

答案 0 :(得分:0)

您应该使用该代码或类似的东西:

{ File file = new File(items.get(selectedRow)); if (file.isDirectory())
    { getFiles(file.listFiles()); }
    else
    {
        new AlertDialog.Builder(this) .setTitle("Ability to open files will come in future updates.")
        .setMessage("Do You Want To Delete this recording?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int button){
                booolean success = file.delete()
                //Refresh UI and your list, so the deleted file is no more diplayed
            }
        })

通过扩展过滤并不是很复杂..

我不明白你的问题在哪里..

答案 1 :(得分:0)

正如Waza_Be已经说明的那样,你需要的只是file.delete()。所以只需删除你的deleteFile方法而不是调用它(在正面对话框按钮的onClick方法中),只需调用file.delete()就可以了:

public void onClick(DialogInterface dialog, int button) {
    // deleteFile();     <-- not needed
    file.delete();   //  <-- do this instead
}