如何从文档中选择 pdf 文件,将其存储在 SQLite 中并再次从 SQLite 打开它?

How to pick pdf file from document , store it in SQLite and again open it from SQLite?

我想从移动内部存储中提取.pdf 文件,将此文件以blob 类型保存在sqlite 中。当我单击 'View' 按钮时,然后从数据库中检索它并在支持 pdf 的应用程序中打开它。

这里我使用这个代码来选择文件

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("application/pdf");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 100);

onActivityResult 代码

                Uri fileuri = data.getData();
                Log.d(TAG, "Document File Uri = " + fileuri);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                FileInputStream fis;
                try
                {
                    fis = new FileInputStream(new File(fileuri.getPath()));
                    byte[] buf = new byte[1024];
                    int n;
                    while (-1 != (n = fis.read(buf)))
                        baos.write(buf, 0, n);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                byte[] byteFile = baos.toByteArray();

然后这个字节文件作为 blob 类型保存到数据库中。现在我怎样才能检索并打开它。请帮助我

code of onActivityResult

A Uri 不是文件。只有当 Uri 的方案是 file 时,您的代码才能工作。用 InputStream 替换你的 FileInputStream,你从 getContentResolver().openInputStream(data.getData()).

得到 InputStream

还有:

  • 您的应用程序会经常崩溃,因为您没有足够的内存来保存 PDF

  • BLOB 列中保存大文件是 Android 中的反模式,因为我们使用的 SQLite API 不能很好地处理大内容

  • 用户不会对你满意,因为你在主应用程序线程上做这个磁盘 I/O,导致你的应用程序 UI 冻结I/O正在执行

Now how can i retrieve and open it

反转过程:

  • 从数据库中获取byte[]

  • byte[] 保存到文件

  • 使用 ACTION_VIEWFileProvider.getUriForFile() 在用户选择的 PDF 查看器中打开文件

再次:

  • 您的应用程序会经常崩溃,因为 运行 尝试加载大 BLOB

  • 时内存不足
  • 在后台线程上执行I/O,以免冻结UI

  • 存储大 BLOB 值是 Android

  • 中的反模式

我强烈建议您不要将 PDF 作为 BLOB 存储在数据库中。或者:

  • 使用ACTION_OPEN_DOCUMENTtakePersistableUriPermission()代替ACTION_GET_CONTENT,并在数据库中保存Uri,或者

  • 将PDF复制到一个文件,并将文件的一些标识符存储在数据库中