首页 > 解决方案 > 无法在 android studio 上使用 File.delete() 获取要删除的下载目录中的文件

问题描述

这是我当前的代码。我对编程和 Android Studio 非常陌生。我认为这里的某个地方存在一个愚蠢的逻辑错误,但已经检查了一遍(一遍又一遍),并且我一生都无法弄清楚为什么文件不会删除。

目的是在长按一个/多个项目时出现底部栏,并且会出现 DEL 按钮,当用户确认时,文件将被删除。但是,确认后文件不会从项目列表中删除/删除。

请帮忙!谢谢

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout1);


    }

    class TextAdapter extends BaseAdapter{

        // String array of items in a directory
        private List<String> data = new ArrayList<>();
        // Boolean array to store which items are selected in list
        private boolean[] selection;

        public void setData(List<String> data){
            if(data != null){
                this.data.clear();
                if(data.size() > 0){
                    this.data.addAll(data);
                }
                notifyDataSetChanged();
            }
        }

        void setSelection(boolean[] selection){
            if(selection != null){
                // Creating new array copy
                this.selection = new boolean[selection.length];
                // Populating new array copy
                for (int i = 0; i < selection.length; i++){
                    this.selection[i] = selection[i];
                }
                // Notifying that data changed
                notifyDataSetChanged();
            }
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public String getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
                convertView.setTag(new ViewHolder((TextView) convertView.findViewById(R.id.textItem)));
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            final String path = getItem(position);
            holder.info.setText(path.substring(path.lastIndexOf('/')+1));
            if(selection != null){
                if(selection[position]){
                    holder.info.setBackgroundColor(Color.LTGRAY);
                }
                else{
                    holder.info.setBackgroundColor(Color.WHITE);
                }
            }
            return convertView;
        }

        class ViewHolder{
            TextView info;

            ViewHolder(TextView info){
                this.info = info;
            }
        }
    }

    // Checking permissions
    private static final int REQUEST_PERMISSIONS = 1234;
    // String array storing read/write external storage permission
    private static final String[] PERMISSIONS = {
            // Requires min SDK version 16
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    // Asking for 2 permissions
    private static final int PERMISSIONS_COUNT = 2;

    // Return boolean for if permissions will be granted
    @SuppressLint("NewApi")
    private boolean arePermissionsDenied(){
        int p = 0;
        while (p < PERMISSIONS_COUNT){
        // If permission is not granted
            if(checkSelfPermission(PERMISSIONS[p]) != PackageManager.PERMISSION_GRANTED){
                return true;
            }
            p++;
        }

        return false;
    }

    // Flag to check if file manager is intialized
    private boolean isFileManagerInit = false;
    // Stores which items are selected in manager for modifying/opening
    private boolean[] selection;

    private File[] files;

    private List<String>filesList;

    private int filesFoundCount;

    // OnResume
    @Override
    protected void onResume(){
        super.onResume();
        // If build is Marshmellow or higher, we have to ask for permissions
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && arePermissionsDenied()) {
            // Requesting for permissions
            requestPermissions(PERMISSIONS, REQUEST_PERMISSIONS);
            return;
        }
        // Checking if File Manager has been initialized. If not, initialize
        if(!isFileManagerInit){
            // Setting default folder
            final String rootPath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
            final File dir = new File(rootPath);
            // Creating file array
            files = dir.listFiles();
            // Displaying current path
            final TextView pathOutput = findViewById(R.id.pathOutput);
            // Setting pathOutput text to rootPath
            pathOutput.setText(rootPath.substring(rootPath.lastIndexOf('/')+1));
            // Number of files
            filesFoundCount = files.length;

            // Creating List elements and populating
            final ListView listView = findViewById(R.id.listView);
            final TextAdapter textAdapter1 = new TextAdapter();
            listView.setAdapter(textAdapter1);

            filesList = new ArrayList<>();

            for(int i = 0; i < filesFoundCount; i++){
                filesList.add(String.valueOf(files[i].getAbsolutePath()));
            }

            textAdapter1.setData(filesList);

            // Allocating memory for array
            selection = new boolean[files.length];

            // To set item as selected
            listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    // If unselected, select it
                    selection[position] = !selection[position];
                    // If selected, unselect it
                    textAdapter1.setSelection(selection);
                    boolean isAtLeastOneSelected = false;
                    // Checking if elements are selected
                    for(int i = 0; i < selection.length; i++){
                        if(selection[i]){
                            isAtLeastOneSelected = true;
                            break;
                        }
                    }
                    // If there are selections made, pull up the buttons on bottom
                    if(isAtLeastOneSelected){
                        findViewById(R.id.bottomBar).setVisibility(View.VISIBLE);
                    }
                    // If there are no selections, then hide bottom bar
                    else{
                        findViewById(R.id.bottomBar).setVisibility(View.GONE);
                    }
                    return false;
                }
            });

            final Button b1 = findViewById(R.id.b1);
            final Button b2 = findViewById(R.id.b2);
            final Button b3 = findViewById(R.id.b3);
            final Button b4 = findViewById(R.id.b4);
            final Button b5 = findViewById(R.id.b5);

            b1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final AlertDialog.Builder deleteDialog = new AlertDialog.Builder(MainActivity.this);
                    deleteDialog.setTitle("Delete");
                    deleteDialog.setMessage("Are you sure you want to delete this file/folder?");
                    deleteDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        // If user wants to delete
                        public void onClick(DialogInterface dialog, int which) {
                            for(int i = 0; i < files.length; i++){
                                if(selection[i]){
                                    deleteFileOrFolder(files[i]);
                                    selection[i]=false;
                                }
                            }
                            files = dir.listFiles();
                            filesFoundCount = files.length;
                            filesList.clear();
                            for(int i = 0; i < filesFoundCount; i++){
                                filesList.add(String.valueOf(files[i].getAbsolutePath()));
                            }
                            textAdapter1.setData(filesList);
                        }
                    });
                    deleteDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    deleteDialog.show();
                }
            });

            // Setting isFileManagerInit to true
            isFileManagerInit = true;
        }


    }

    // Method that will delete file or folder
    private void deleteFileOrFolder(File fileOrFolder){
        // Check if file or directory
        // If folder
        if(fileOrFolder.isDirectory()){
            // If folder is empty
            if(fileOrFolder.list().length == 0){
                fileOrFolder.delete();
            }
            // Delete every file in the folder
            else{
                String files[] = fileOrFolder.list();
                for(String temp:files){
                    File fileToDelete = new File(fileOrFolder, temp);
                    deleteFileOrFolder(fileToDelete);
                }
                // Deleting folder itself
                if(fileOrFolder.list().length == 0){
                    fileOrFolder.delete();
                }
            }
        }
        // If just a file
        else{
            fileOrFolder.delete();
        }
    }

    // Checking if the user granted permissions
    @SuppressLint("NewApi")
    @Override
    public void onRequestPermissionsResult(final int requestCode, final String[] permissions,
                                           final int[] grantResults){
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // If requestCode equal to request permissions and are not null
        if(requestCode == REQUEST_PERMISSIONS && grantResults.length>0){
            // If permissions denied, clear app data to continue asking user for permissions
            if(arePermissionsDenied() == true){
                // Requires 19 or higher, but will not be called anyway if that is the case, ignore warnings
                ((ActivityManager) Objects.requireNonNull(this.getSystemService(ACTIVITY_SERVICE))).clearApplicationUserData();
                recreate();
            }
            else{
                onResume();
            }
        }
    }
}

标签: javaandroid

解决方案


此数组声明无效:

String files[] = fileOrFolder.list();

不要使deleteFileOrFolder()方法过于复杂。试试这样:

    private boolean deleteFileOrFolder(File fileOrFolder){
        File[] files = fileOrFolder.listFiles();
        if (files != null) {
            for (File file : files) {
                deleteFileOrFolder(file);
            }
        }
        return fileOrFolder.delete();
    }

推荐阅读