Android / Java - 上下文菜单项不删除文件 - 强制关闭

时间:2014-01-09 16:59:39

标签: java android contextmenu fileinputstream forceclose

我有一个ListView作为文件浏览器:

public class FileChooser extends ListActivity {

    private File currentDir;
    private FileArrayAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentDir = new File("/sdcard/");
        fill(currentDir);
        registerForContextMenu(getListView());
        // get the attachment's filename
        SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        String attachmentFileName = preferences.getString("fileName", "");

        // save the attachment
        try {
            InputStream attachment = getContentResolver().openInputStream(
                    getIntent().getData());

            File savedFile = new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath(), attachmentFileName);
            FileOutputStream f = new FileOutputStream(savedFile);
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = attachment.read(buffer)) > 0) {
                f.write(buffer);
            }
            f.close();
        } catch (Exception e) {
        }
    }

    // File Manager Source to view SD Card or Internal Storage Contents
    private void fill(File f) {
        File[] dirs = f.listFiles();
        this.setTitle("Current Dir: " + f.getName());
        List<Item> dir = new ArrayList<Item>();
        List<Item> fls = new ArrayList<Item>();
        try {
            for (File ff : dirs) {
                Date lastModDate = new Date(ff.lastModified());
                DateFormat formater = DateFormat.getDateTimeInstance();
                String date_modify = formater.format(lastModDate);
                if (ff.isDirectory()) {

                    File[] fbuf = ff.listFiles();
                    int buf = 0;
                    if (fbuf != null) {
                        buf = fbuf.length;
                    } else
                        buf = 0;
                    String num_item = String.valueOf(buf);
                    if (buf == 0)
                        num_item = num_item + " item";
                    else
                        num_item = num_item + " items";

                    // String formated = lastModDate.toString();
                    dir.add(new Item(ff.getName(), num_item, date_modify, ff
                            .getAbsolutePath(), "directory_icon"));
                } else {

                    fls.add(new Item(ff.getName(), ff.length() + " Byte",
                            date_modify, ff.getAbsolutePath(), "file_icon"));
                }
            }
        } catch (Exception e) {

        }
        Collections.sort(dir);
        Collections.sort(fls);
        dir.addAll(fls);
        if (!f.getName().equalsIgnoreCase("sdcard"))
            dir.add(0, new Item("..", "Parent Directory", "", f.getParent(),
                    "directory_up"));
        adapter = new FileArrayAdapter(FileChooser.this, R.layout.file_view,
                dir);
        this.setListAdapter(adapter);
    }

    // onClick listener to move back one directory
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        Item o = adapter.getItem(position);
        if (o.getImage().equalsIgnoreCase("directory_icon")
                || o.getImage().equalsIgnoreCase("directory_up")) {
            currentDir = new File(o.getPath());
            fill(currentDir);
        } else {
            onFileClick(o);
        }
    }

    // open file onClick
    private void onFileClick(Item o) {

        Intent intent = new Intent();
        intent.putExtra("GetPath", currentDir.toString());
        intent.putExtra("GetFileName", o.getName());
        setResult(RESULT_OK, intent);
        finish();
    }

我添加了一个上下文菜单:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Context Menu");
    menu.add(0, v.getId(), 0, "Copy");
    menu.add(0, v.getId(), 0, "Paste");
    menu.add(0, v.getId(), 0, "Delete");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle() == "Copy") {
        function1(item.getItemId());
    }
    if (item.getTitle() == "Paste") {
        function2(item.getItemId());
    } else if (item.getTitle() == "Delete") {
        function3(item.getItemId());
    } else {
        return false;
    }
    return true;
}

public void function1(int id) {
    Toast.makeText(this, "Copy", Toast.LENGTH_SHORT).show();

    try {
        copyDirectoryOneLocationToAnotherLocation(currentDir, currentDir);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public void function2(int id) {
    Toast.makeText(this, "Paste", Toast.LENGTH_SHORT).show();
}

public void function3(int id) {
    Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
    DeleteRecursive(currentDir);
}

我已经创建了使用上下文菜单删除和复制数据的方法:

private void DeleteRecursive(File fileOrDirectory) {

    if (fileOrDirectory.isDirectory())
        for (File child : fileOrDirectory.listFiles())
            DeleteRecursive(child);

    fileOrDirectory.delete();

}

public static void copyDirectoryOneLocationToAnotherLocation(
        File sourceLocation, File targetLocation) throws IOException {

    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists()) {
            targetLocation.mkdir();
        }

        String[] children = sourceLocation.list();
        for (int i = 0; i < sourceLocation.listFiles().length; i++) {

            copyDirectoryOneLocationToAnotherLocation(new File(
                    sourceLocation, children[i]), new File(targetLocation,
                    children[i]));
        }
    } else {

        InputStream in = new FileInputStream(sourceLocation);

        OutputStream out = new FileOutputStream(targetLocation);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

}

}

我的问题是 - 每次我尝试删除文件时,我都会在第184行遇到强制关闭错误:for (File child : fileOrDirectory.listFiles())

我相信我的DeleteRecursive方法存在问题 - 但我不确定如何解决它。

logcat的:

01-09 11:27:39.491: E/AndroidRuntime(6439): FATAL EXCEPTION: main
01-09 11:27:39.491: E/AndroidRuntime(6439): java.lang.NullPointerException
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.example.project.FileChooser.DeleteRecursive(FileChooser.java:184)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.example.project.FileChooser.DeleteRecursive(FileChooser.java:185)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.example.project.FileChooser.function3(FileChooser.java:178)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.example.project.FileChooser.onContextItemSelected(FileChooser.java:153)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at android.app.Activity.onMenuItemSelected(Activity.java:2597)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3663)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:963)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at android.widget.AdapterView.performItemClick(AdapterView.java:298)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at android.widget.AbsListView.performItemClick(AbsListView.java:1128)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2812)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at android.widget.AbsListView$1.run(AbsListView.java:3571)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at android.os.Handler.handleCallback(Handler.java:725)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at android.os.Looper.loop(Looper.java:153)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at android.app.ActivityThread.main(ActivityThread.java:5297)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at java.lang.reflect.Method.invokeNative(Native Method)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at java.lang.reflect.Method.invoke(Method.java:511)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
01-09 11:27:39.491: E/AndroidRuntime(6439):     at dalvik.system.NativeStart.main(Native Method)
01-09 11:27:40.204: D/dalvikvm(6439): threadid=11: interp stack at 0x5f2b8000
01-09 11:27:41.567: I/Process(6439): Sending signal. PID: 6439 SIG: 9

1 个答案:

答案 0 :(得分:0)

只需更改此方法:

 private void DeleteRecursive(File fileOrDirectory) {

     if (fileOrDirectory.isDirectory()) {
        File[] children = fileOrDirectory.listFiles();
        if(null != children) {
         for (File child : children)
             DeleteRecursive(child);
        }
     }

     fileOrDirectory.delete();

 }