Reputation: 21
I want to pick .pdf file from mobile internal storage , save this file in sqlite as blob type. When i click on 'View' button then retrieve it from database and open it in pdf supported application.
Here i used this code for pick file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 100);
code of 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();
then this byteFile saved into database as a blob type. Now how can i retrieve and open it. Please help me
Upvotes: 0
Views: 794
Reputation: 1007296
code of onActivityResult
A Uri
is not a file. Only if the scheme of the Uri
is file
does your code work. Replace your FileInputStream
with an InputStream
, where you get that InputStream
from getContentResolver().openInputStream(data.getData())
.
Also:
Your app will crash a lot, as you will not have enough memory to hold the PDF
Saving large files in BLOB
columns is an anti-pattern in Android, as the SQLite APIs that we use do not handle large contents very well
The user will not be happy with you, as you are doing this disk I/O on the main application thread, causing the UI of your app to freeze while that I/O is being performed
Now how can i retrieve and open it
Reverse the process:
Get the byte[]
from the database
Save that byte[]
to a file
Use ACTION_VIEW
and FileProvider.getUriForFile()
to open the file in the user's chosen PDF viewer
Once again:
Your app will crash a lot, due to running out of memory trying to load in a large BLOB
Do the I/O on a background thread, so as not to freeze the UI
Storing large BLOB
values is an anti-pattern in Android
I strongly recommend that you not store the PDF as a BLOB
in a database. Either:
Use ACTION_OPEN_DOCUMENT
and takePersistableUriPermission()
instead of ACTION_GET_CONTENT
, and save the Uri
in the database, or
Copy the PDF to a file, and store some identifier of the file in the database
Upvotes: 1