【问题标题】:Unable to rename and delete my pdf file in my Android App无法在我的 Android 应用程序中重命名和删除我的 pdf 文件
【发布时间】:2021-03-02 15:18:30
【问题描述】:

我无法在我的 pdf 阅读器应用程序中重命名和删除 pdf 文件,使用 renameTo() 方法重命名文件,并且 file.delete() 方法也无法从内部存储中删除 pdf 文件。 我附上了我的 Android 工作室中可能有助于找到问题的所有相关代码:

我试图根据 MenuItem 选择重命名和删除文件的 RecyclerAdapter 代码:

   @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_delete:
                int position = getBindingAdapterPosition();

                File file=pdf.get(position);
                file.delete();
                pdf.remove(position);
                notifyItemChanged(position);
                notifyItemRangeChanged(position,pdf.size());
                return true;
            case R.id.menu_rename:
                AlertDialog.Builder jumpto = new AlertDialog.Builder(mcontext);
                jumpto.setTitle("Rename");
                EditText page = new EditText(mcontext);
                page.setText(pdfname.getText());
                jumpto.setView(page);
                jumpto.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        File old = new File(pdf.get(getBindingAdapterPosition()).getAbsolutePath());
                        String name = old.getParentFile().getAbsolutePath();
                        String newpath = name + page.getText().toString();
                        File newfile = new File(newpath);

                        Boolean rename = old.renameTo(newfile);
                        if (rename) {
                            ContentResolver resolver = mcontext.getContentResolver();
                            resolver.delete(MediaStore.Files.getContentUri("external"), MediaStore.MediaColumns.DATA + "=?", new
                                    String[]{
                                    old.getAbsolutePath()});
                            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                            intent.setData(Uri.fromFile(newfile));
                            mcontext.getApplicationContext().sendBroadcast(intent);
                        }
                       
                    }

                });

这是我如何从文档片段中的存储中获取 pdf 文件的代码:

 protected List<File> getPdfList() {
    Uri collection;

    final String[] projection = new String[]{
            MediaStore.Files.FileColumns.DISPLAY_NAME,
            MediaStore.Files.FileColumns.DATE_ADDED,
            MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.MIME_TYPE,
    };

    final String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";

    final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";

    final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
    final String[] selectionArgs = new String[]{mimeType};

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
    }else{
        collection = MediaStore.Files.getContentUri("external");
    }


    try (Cursor cursor =getContext().getApplicationContext().getContentResolver().query(collection, projection, selection, selectionArgs, sortOrder)) {
        assert cursor != null;

        if (cursor.moveToFirst()) {
            int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
            int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
            String path=cursor.getString(columnData);
            if(new File(path).exists()){
            do {
                pdf.add(new File((cursor.getString(columnData))));
               // Log.d(TAG, "getPdf: " + cursor.getString(columnData));
                //you can get your pdf files
            } while (cursor.moveToNext());
        }
    }
    }
    return pdf;
}

这是我请求运行时权限的 MainActivity.java 代码:

 if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED&&ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
           
        } else {
            requestStoragePermission();

        }

    }

    int Request_Code = 12;
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestStoragePermission() {

        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, Request_Code);

    }



    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == Request_Code) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               
            }
        } else {

        }

【问题讨论】:

    标签: java android-studio delete-file file-rename android-storage


    【解决方案1】:

    您可以检查您的文件是否被删除,您可以检查这可能对您有帮助,这里是删除代码

    boolean b = documentList.get(position).getFile().delete();
    if (b) {
       documentList.remove(position);
       notifyItemRemoved(position);
       notifyDataSetChanged();
       Toast.makeText(context, "File Deleted!", Toast.LENGTH_SHORT).show();
    } else {
       Toast.makeText(context, "File Deletion Failed!", Toast.LENGTH_SHORT).show();
    }
    

    【讨论】:

    • 您遇到了什么问题?
    • 文件正在从回收站视图中删除,但没有从存储中删除。当我关闭我的应用程序并重新启动它时,删除的文件会重新出现。
    • 如果文件被删除,则 b 返回真,如果为真,则从列表中删除文件。您还面临其他问题。
    • 还有一件事,您将获得删除文件的绝对路径。
    • 感谢 Rafaqat 抽出宝贵时间。我添加了内容解析器来删除我的文件,现在它可以正常工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2023-03-12
    • 2015-02-26
    • 2018-11-07
    相关资源
    最近更新 更多