Opening pdf from assets - java

I'm currently trying to use dynamic delivery to download and install some pdf files and open them with barteksc's pdf viewer (com.github.barteksc:android-pdf-viewer:2.8.2).
When I had the pdf files inside my apk everything worked fine but now that I download them and install them via dynamic delivery I get this error when I try to open them
E/PDFView: load pdf error
java.io.FileNotFoundException: Example.pdf
at android.content.res.AssetManager.nativeOpenAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:744)
at android.content.res.AssetManager.open(AssetManager.java:721)
at com.github.barteksc.pdfviewer.util.FileUtils.fileFromAsset(FileUtils.java:37)
at com.github.barteksc.pdfviewer.source.AssetSource.createDocument(AssetSource.java:39)
at com.github.barteksc.pdfviewer.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:53)
at com.github.barteksc.pdfviewer.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:25)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
This returns "Installed"
if (manager.getInstalledModules().contains("dynamicfeature")) {
statusText.setText("Installed");
} else {
statusText.setText("Feature not yet installed");
}
I am installing the module from a different Class if that makes a difference, I saw something about updating the context in Google docs but I could not figure it out.
I have also added
com.google.android.play.core.splitcompat.SplitCompatApplication
as the documentation says, still no luck.
This is the method I am using to view the Pdf file.It was working perfect while the pdfs where in the asset folder of the base application but it's not working now that the pdfs are in the assets folder of the Dynamic Delivery Module.
private void displayFromAsset(String assetFileName) {
String SAMPLE_FILE = getIntent().getStringExtra("PDF INTENT");
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();

Example.pdf is not pointing to the asset folder.
you need to provide a relative patht of your file .
for asset folder u can giv like
Uri resUri= Uri.fromFile(new File("//android_asset/image.png"));
For downloaded pdf files you can query by contentprovider query & get the uri from query result.

Related

Find a directory in Android Studio Project not in the phone

I am trying to get access to a text file (log.txt) in a directory. All other questions on this topic refer to getting directories from the emulators internal storage.
My file structure is as such
>androidApp
->App
-->Build
-->src
--->game_log
---->log.txt
--->Main
---->(Android app Code further)
Using new File(System.getProperty("user.dir) + "app\\src\\game_log\\log.txt").exists() gets me false.
Another thing I tried was System.getProperty("user.dir") but that yields me /.
Contextwrapper.getPath() gets me the path of the emulators storage.
Is the file structure of Android Studio different or I am using the wrong method to get the file from my project folder?

Android: ZipFile() java.util.zip.ZipException: File too short to be a zip file: 0

I am working on a project (Using Android Studio 3.1.4) that reads in a neural network that is stored as a .zip file, for further use with DL4J in Android.
I am trying to open this .zip file located in my projects res\raw directory. For this I am trying to use the ZipFile() method from java.util.zip.
Screenshot of location of neuralnet.zip
Problem:
Following code throws an exception:
File model_file = new File(String.valueOf(this.getResources().openRawResource(R.raw.neuralnet)));
ZipFile zipFile = new ZipFile(model_file);
Exception:
"java.util.zip.ZipException: File too short to be a zip file: 0"
Therefore I cannot load the model. Testing this on a simulated device running Android API 24
On API 26 the exception is different:
java.io.FileNotFoundException: File doesn't exist: android.content.res.AssetManager$AssetInputStream#ddde727
Does someone have experience with the use of ZipFile(), or with loading neuralnetwork models using DL4J in Android?
Could there be something special be required in the build.gradle?
Any input is appreciated!
What I have tried:
Checked the .zip file made sure it exists.
Made sure that .zip is just a container, and the file is not compressed, by archiving the containing 3 files using 7Zip without compression as .zip
Checked READ_EXTERNAL_STORAGE permission, even though I dont think it should be required
tried using the full path instead of using this.getResources().openRawResource(R.raw.neuralnet)
Android permissions:
I am running android api > 23, and I am requesting the READ_EXTERNAL_STORAGE permission at runtime.
Manifest includes:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Thanks,
Mo
Your problem is the way of file opening.
For open a raw file look at below links:
https://developer.android.com/guide/topics/resources/providing-resources
How to read file from res/raw by name
I was able to open the content of the archive, by working around the ZipFile() method that gave me another error, as it expects a path, rather than the resource identifier.
Still, opening the archived files, i have used the method proposed by "No Body":
InputStream ins1 = getResources().openRawResource(getResources().getIdentifier("configuration", "raw", getPackageName()));
InputStream ins2 = getResources().openRawResource(getResources().getIdentifier("coefficients", "raw", getPackageName()));
InputStream ins3 = getResources().openRawResource(getResources().getIdentifier("updaterstate", "raw", getPackageName()));
model = restoreMultiLayerNetwork(ins1, ins2, ins3, false);

Downloaded mp3 files can't open in Downloads folder (Android Studio)

I have an app that downloads mp3 files from a url. The downloading works, and I get a file in the downloads folder. However, when I click on it, it says "Can't open file." When I use getExternalStorageDirectory(), it also isn't retrieving the file or getting any of the information. Is there something wrong with how I'm implementing the download function? Or is there more I have to do with the download manager? I also tried using addCompletedDownload(), but it would just add a "0" file.
private long DownloadData (Uri uri) {
long downloadReference;
downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
// Create request for android download manager
DownloadManager.Request request = new DownloadManager.Request(uri);
//Setting title of request
request.setTitle("Downloading Song");
//Setting description of request
request.setDescription("Downloading Song from URL");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(MainActivity.this, Environment.DIRECTORY_DOWNLOADS, "DownloadSong.mp3");
//Enqueue download and save into referenceId
downloadReference = downloadManager.enqueue(request);
return downloadReference;
}
The code that you had shown to us is absolutely not enough to understand the problem. Here is an example code for downloading using DownloadManager.
According to the symptoms described, I think, you haven't finished the download operation or the writing operation correctly. You should check if the download is finished and the file is written and closed. The fact that a file appeared, means that the downloading and writing had started, but not that they finished correctly.
Using DownloadManager terms, it should be completed. Look How to notify after all download completed from Android download manager about that

Using DownloadManager to download into new folder on phones storage

Im using a download manager which downloads a file into a new folder on the phone storage. Here is the code im using:
DownloadManager.Request downloadSample = new DownloadManager.Request(Uri.parse(urlSample));
downloadSample.allowScanningByMediaScanner();
downloadSample.setDestinationInExternalPublicDir("/Samples/"+previewName, "sample.ttf");
downloadSample.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(downloadSample);
This works perfectly fine on many of the devices Ive tested on, but a few devices force close the app with the following error in the log:
E/AndroidRuntime(29918): java.lang.IllegalStateException: Unable to create directory: /storage/sdcard0/Samples/Helvetica
E/AndroidRuntime(29918): at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:507)
Its annoying that it works fine on some but not at all on other devices. Does anyone know why this is happening?
The documentation for setDestinationInExternalPublicDir(String dirType, String subPath) says that dirType can take only specified values.
Here dirType can only be the android defined directories for example:
Environment.DIRECTORY_DOWNLOADS
etc.
you can find all the possible values of dirType at: http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)
So the proper way to use this method is:
setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subPath)
Also note that this will make the folder in Downloads folder on phone storage. Download manager will not allow you to make a folder in the default directory of phone storage.
This will not give you IllegalStateException for creating directory.

Android - store and load files in project root

I am looking for an appropriate way to store and access pdf files in my Android app.
The problem is: I have 5 pdf-files which I would like to store in the project resources and load in the app.
I have tried to make a new directory in the project root /myApp/pdfs, and accessing it by:
File myFile = new File("/myApp/pdfs/,fileName);
I have tried some different variants of the path name: ./myApp/pdfs, myApp/pdfs, /pdfs, ./pdfs. However I get the same message stating that the file can't be found.
How do I get the path to my apps directory? And is this the most appropriate approach for saving a small number of pdf-files?
If you are wanting to load the pdfs from the app (while the app is running), you probably want to store them in the res/raw folder.

Categories

Resources