Get image thumbnail from google drive in Android - android

Is it possible to get image thumbnail from google drive image file ? When I'm opening the native google drive app, it shows me thumbnails of images, but when I'm opening the file chooser of API, it's shows me default icon for all images.

Google Drive Android API doesn't provide thumbnails at the moment, they will be likely to be available on the new version.

It's very simple, actually.
On the file (com.google.api.services.drive.model.File) you get back, just call getThumbnailLink(). That will be the thumbnail of the image. However, if it's not an image, if I remember correctly, it will simply be blank (not null, but just blank).

Update: I had an error in the discussion of the request fields.
As far as I can tell, there is literally no good documentation on the solution for this. It's true that you can't get thumbnails with the Drive Android API, however you can get thumbnails with the Drive Java Client Library. This page has is a really good primer for getting started:
https://developers.google.com/drive/v3/web/quickstart/android
Oddly, I can't get the fields portion of the request to work as it is on that quick start. As I've experienced, you have to request the fields a little differently.
Since you're doing a custom field request you have to be sure to add the other fields you want as well. Here is how I've gotten it to work:
Drive.Files.List request = mService.files()
.list()
.setFields("files/thumbnailLink, files/name, files/mimeType, files/id")
.setQ("Your file param and/or mime query");
FileList files = request.execute();
files.getFiles(); //Each File in the collection will have a valid thumbnailLink
A sample query might be:
"mimeType = 'image/jpeg' or mimeType = 'video/mp4'"
Hope this helps!

Related

Is there any way to get Google Sheets fileid from file picker intent?

In my Android app I would like the user to open a Google Sheets document to import data from it into the app database.
It's easy to select a file with ACTION_GET_CONTENT / ACTION_OPEN_DOCUMENT and with MIME filter application/vnd.google-apps.spreadsheet. (It will be a virtual file.)
It's also easy to get the content of a Google Sheets document with the Google Sheets API based on the Drive filed id (with user-granted spreadsheets.readonly scope):
Sheets.Builder(transport, jsonFactory, appCredential)
.build()
.spreadsheets()
.get(fileid)
.execute()
But the first step returns the Uri of the file on the device, and the second step requires the file id of the Drive file.
How can I determine the second from the first?
The only poor solution I found was to use the Google Drive API: I search the Sheets file with its name I got from the intent, and I get the id of it... It requires the drive.metadata.readonly scope, which is a restricted scope, and doh... it's not a viable solution anyway...
I can download a pdf from the uri of the virtual file, but it's not suitable for importing data.
If anyone knows the answer, a thousand thanks for it!
It depends on what the type of fileId is. (I am not familiar with that particular API).
In general, you need to use ContentResolver to convert the Uri into some usable type such as InputStream, FileDescriptor, etc.
There is also the DocumentFile utility class to work with Document URIs.

Firebase storage URL keeps changing with new token

I'm trying to build a social media application using firebase database and storage. Below is the flow expected.
User upload a profile picture which is stored on firebase storage in the current user folder and the URL stored in firebase database for quick access. (Works fine)
User post their thoughts. This save users info such as post message, username and profile image URL in databases. (Works fine).
Problem
The problem now is say a user updates he's or her profile picture, this overrides the older profile image in firebase storage (in order manage storage and to make user image be the same across all comments and post). On the post message activity the older profile image URL can't be accessed cause the token as changed.
Question
I will like to know how this can be fixed in such that the firebase storage URL will be static (that is the same) accross all updates.
NB
Using Picasso and not firebase method to get the images
Although this question had been asked for a very long time, but I noticed some people still find it difficult solving this, so I will be providing my solution below.
STEP 1
Since storage URL are always dynamic (i.e the posses token) when changed, what I did was to use generic name for image file stored say avatar for all users
STEP 2
Create a directory in storage for each user as follows: users/{uid}/avatar.jpg
STEP 3
Pull or display the image by using the path in step 2 (see below)
ANDROID
StorageReference storageReference = FirebaseStorage.getInstance().getReference("users").child(userId).child("avatar.jpg");
Glide.with(context).using(new FirebaseImageLoader()).load(storageReference).diskCacheStrategy(DiskCacheStrategy.ALL)
.error(R.drawable.ch_white_icon).placeholder(R.drawable.ch_white_icon).into(imageView);
WEB
var storage = firebase.storage();
var pathReference = storage.ref('users/' + userId + '/avatar.jpg');
pathReference.getDownloadURL().then(function (url) {
$("#large-avatar").attr('src', url);
}).catch(function (error) {
// Handle any errors
});
With this you don't have to worry with the dynamic link anymore, whenever you upload a new image to the above path, it overrides the previous one and the code in step 3 will give you the new image.
PS: For Android Don't forget to change DiskCacheStrategy.ALL to DiskCacheStrategy.NONE if you don't want glide to cache image or you can use timestamp to get new image if cache is allowed.
Since the URL image is stored in the database, you could use a Cloud Function to update the value after a user has updated his picture.
You can trigger a Cloud function in response to the updating of files in Cloud Storage, see:
https://firebase.google.com/docs/functions/gcp-storage-events
You will find examples of Cloud Functions at: https://github.com/firebase/functions-samples
and the full doc at: https://firebase.google.com/docs/functions/

Cannot access Google Drive file

I am making a notepad app using Google Drive. Whenever user creates a file in the app, it also creates a file in the Google Drive. And user can enter the text and save the file, the unsaved text will get committed whenever the internet is available. I am managing the update and create processes within the app using the DriveId.
If the user wants to use the files with the alternative device using my app, for that I also have the option called DriveId import. By clicking the option DriveId import user will be prompted with the input box for entering the existing DriveId. Using the DriveId I thought of opening the files, But it was giving an error.
Then I saw an answer given in this SO which clearly says DriveId can be used only inside the app and device which created the file.
I also found a similar question like mine in here SO But I can’t get my problem solved. I have taken ResourceId using result.getDriveFolder().getDriveId().getResourceId()
How to read the data’s programmatically using the ResourceID? As said in the above answer here I don’t want to change the track and go into Drive REST API. Is there a way that I can read the data using Google Drive Android API ? I have done all the development process, but in the ending when I try to access from other device it is giving the error. Totally struck.
If I can only read the data using REST API any simple code will be appreciated. Thanks in advance.
Finally Solved the DriveId Issue without REST API.
To get DriveId on the alternative device. You will need resourceId. You can use following code:-
String resourseId = "xxxxxxxxxxxxx"
Drive.DriveApi.fetchDriveId(mGoogleApiClient,resourseId).setResultCallback(idCallBack);
private ResultCallBack<DriveApi.DriveResult> idCallBack = new ResultCallback<DriveApi.DriveIdResult>() {
#Override
public void onResult(DriveApi.DriveIdResult driveIdResult) {
msg.Log("onResult");
DriveId id = driveIdResult.getDriveId(); //Here you go :)
}
}

Graph API: Same request with different album ID returns empty JSONObject?

I am using following code in my android app in a for loop of albumIDs to make requests for getting specific photo object information:
AsyncFacebookRunnerObj.request(currentAlbumID +"/photos?fields=id,name,source,created_time", new myRequestListner, refString);
I know the albumIDs of my friend's profile which I can see from my facebook profile. Though I can see all the albums I want to retrieve (they are public), but calls to this function still returns empty for some of albumIDs while for others it works perfectly fine.
When I access the albums using Graph API explorer i can retrieve all photos from all albums. Access_token in this case is different but I guess it is supposed to be different because in my case I am accessing it from app.
Please let me know what can be wrong?
Thanks.
I ran into a similar issue with the FB JS SDK. Check that your json parser is parsing the album id as a string instead of a long/double (probably only a mixed-type language issue, but worth investigating).

Unable to get "thumbnailLink" from Google Drive Rest API V3

I am trying to get all images in a google drive folder. I am able to do so but still not getting the thumbnailLink.
FileList result = mService.files().list()
.setPageSize(10)
.setQ("'"+parentFile.getId()+"'" + " in parents and mimeType='image/jpeg' ")
.setFields("nextPageToken, files(contentHints,description,fileExtension,folderColorRgb,fullFileExtension,
iconLink,id,kind,md5Checksum,mimeType,name,originalFilename,
thumbnailLink,videoMediaMetadata,webContentLink,webViewLink)")
.execute();
Here's the Url that is being hit from the code
https://www.googleapis.com/drive/v3/files?fields=nextPageToken,%20files(fileExtension,
folderColorRgb,iconLink,id,thumbnailLink,kind,mimeType,name,
originalFilename,webContentLink,webViewLink)
&pageSize=20&q=0B-u5D758kMAgfmh3SnNabDJRaENISXVUR2kwWEw3TWtQSGJpbWhUVTJLaUZyRWtmM3lGTjA
%20in%20parents%20and%20mimeType%3Dimage/jpeg%20
The Same data parameters (above) yields the thumbnail when use the API Explorer
https://developers.google.com/apis-explorer/#search/drive.files.list/m/drive/v3/drive.files.list
The Google Drive APIs reference on SCOPES refers to excluding thumbnails a few times but doesn't help much defining which scope allows thumbnails to be returned.
I upped my scope from
https://www.googleapis.com/auth/drive.metadata.readonly to
https://www.googleapis.com/auth/drive and my Node app started retrieving thumbnails for the first time.
This iOS specific post describing the same issue suggests using https://www.googleapis.com/auth/drive.photos.readonly
On the basis that we should use the least permissive scope possible I ended up adding the drive.photos.readonly scope to my original scope giving me
var SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/drive.photos.readonly']
Of course, I'm OT for your platform but the code will be similar I'm sure.

Categories

Resources