Reputation: 139
My app downloads PDF files. So in some activities I need to check which files are available to do some operation. I am using the below code to check if the file is available -
val file = File(getDir(book))
if (file.exists()) {
// do some stuff
} else {
// do other stuff
}
Here is the code for getDir function -
fun getDir(book: Book): String {
return Environment.getExternalStorageDirectory().toString() + File.separator +
"PDF FOLDER/${book.layer_name}/${book.class_name}/${book.name}.pdf"
}
This piece of code is working perfectly in Activity 1 where the file is downloaded from. But When I go to Activity 2 this method says the file does not exist.
I logged getDir(book) from both activities and they are 100% same. The logs are below -
E/loggg: /storage/emulated/0/PDF FOLDER/Primary/Class1/my_book.pdf
E/loggg: /storage/emulated/0/PDF FOLDER/Primary/Class1/my_book.pdf
And when I download files from Activity 2 the codes works perfectly again.
What could be the reason behind this problem? I can't see any problem in my code. Any help would be appreciated. Thanks.
Upvotes: 0
Views: 114
Reputation: 139
After a while I found the problem. Still don't know the exact reason.
After downloading the PDF I was opening another activity from Activity 1(from where the file is downloaded) to read the PDF file without finishing Activity 1. Then when I went back to Activity 2(Bookmark activity) file.exist() was returning false.
But if I finish Activity 1 after downloading the file and head back to Activity 2 file.exist() is returning true.
Upvotes: 1
Reputation: 2785
For a job safe, try use a interface
where this code is shared, this avoid duplicate codes and this diminishes the cases like this (where the same code block not work)
Try
open class ActivityBase: AppCompatActivity {
protected fun getDir(book: Book): String {
return Environment.getExternalStorageDirectory().toString() + File.separator +
"PDF FOLDER/${book.layer_name}/${book.class_name}/${book.name}.pdf"
}
}
class Activity1: ActivityBase
class Activity2: ActivityBase
Maybe this above code be helpfull to you
Upvotes: 2