Help needed with Android KitKat Storage Access Framework!
I’m trying to open files from Google Drive using the new Storage Access Framework in Android 4.4. The file picker works fine but I’m stuck with a problem.
When I pick a file from Google Drive, I can only open it as an input stream. But what I really want is to get a Java File object. The content URI I get looks like this:
content://com.google.android.apps.docs.storage/document/acc=4;doc=2279
I’ve searched for solutions but couldn’t find anything that lets me get the filename, filesize, and contents all together. Right now, I’m working around it by writing a temp file from the input stream. But that’s not ideal.
Anyone know how to turn that content URI into a proper File object? I’d really appreciate some help here!
Extra info: I’m using the latest Android SDK and targeting KitKat devices. My app needs to handle various file types from different sources, including Google Drive.
lol josephk, i’ve been in that crater. SAF won’t hand ya a true java file for cloud peeps.
try DocumentFile.fromSingleUri(context, uri); it rly gives you file-like access without a temp hack. hope this helps. cheers!
I’ve encountered this issue as well. Unfortunately, the Storage Access Framework doesn’t provide direct File objects for cloud-based content like Google Drive. However, there’s a workaround that might suit your needs. Instead of trying to obtain a File object, consider using the DocumentFile API. You can create a DocumentFile instance from your content URI like this: DocumentFile documentFile = DocumentFile.fromSingleUri(context, uri);. This gives you methods to access file metadata such as name, size, and contents. For reading the file’s contents, you can use openInputStream() on the content resolver. This approach should help you work seamlessly with cloud files without creating temporary files.
Hey there, I’ve dealt with this exact headache before. The Storage Access Framework can be a real pain when it comes to cloud files. Here’s what worked for me:
Instead of chasing after a File object, I switched to using DocumentFile. It’s not a perfect replacement, but it gets the job done. You can create one like this:
DocumentFile docFile = DocumentFile.fromSingleUri(context, yourContentUri);
From there, you can grab the filename with docFile.getName(), get the size with docFile.length(), and read the contents using an InputStream from the ContentResolver.
It’s not as straightforward as working with regular files, but it beats creating temp files all over the place. Just remember to handle null checks and exceptions, especially when dealing with cloud content that might not always be available.
Hope this helps you out! Let me know if you need any more details on implementation.