How do I upload file to google drive from android - android

I have spend more then one day but not getting any working solution which provide me uploading / downloading files to Google Drive.
I have tried Google Play Service but i didn't find any method which upload / download files.
I try Google Client libraries but there are some method are not resolved.
such as :
service.files().insert(body, mediaContent).execute();
errors: The method execute() is undefined for the type Drive.Files.Insert
I can upload image through below code but this is Google Drive file up loader. I can only upload one only one file at a time.
mFile = new java.io.File(fileList.get(i));
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newContents(mGoogleApiClient).addResultCallback(
new OnNewContentsCallback() {
#Override
public void onNewContents(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
Log.i(TAG, "New contents created.");
OutputStream outputStream = result
.getContents().getOutputStream();
byte[] byteStream = new byte[(int) mFile
.length()];
try {
outputStream.write(byteStream);
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg")
.setMimeType("text/html")
.setTitle("Android Photo.png").build();
// Create an intent for the file chooser, and
// start it.
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(
result.getContents())
.build(mGoogleApiClient);
try {
mActivity.startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR,
null, 0, 0, 0);
publishProgress(1);
} catch (SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.");
publishProgress(0);
}
}
});
But still fighting for downloading a file.

I got the solution. We should never use Android API for complete Drive access. We should work on pure java code as Google also said that to access Drive for broad access use java libraries.
I remove all the code related to Google play services. I am now using completely using java and easily upload, delete, edit, download all whatever I want.
One more thing Google doc doesn't provide a detail description about Google Drive in respective to android api while when work on java libraries you can get already created methods and more.
I am not giving any code but saying that for me or for others who interested in Drive complete access use Java based codes.

Upload File to Google Drive
Drive.Files.Insert insert;
try {
final java.io.File uploadFile = new java.io.File(filePath);
File fileMetadata = new File();
ParentReference newParent = new ParentReference();
newParent.setId(upload_folder_ID);
fileMetadata.setParents(
Arrays.asList(newParent));
fileMetadata.setTitle(fileName);
InputStreamContent mediaContent = new InputStreamContent(MIMEType, new BufferedInputStream(
new FileInputStream(uploadFile) {
#Override
public int read(byte[] buffer,
int byteOffset, int byteCount)
throws IOException {
// TODO Auto-generated method stub
Log.i("chauster","progress = "+byteCount);
return super.read(buffer, byteOffset, byteCount);
}
}));
mediaContent.setLength(uploadFile.length());
insert = service.files().insert(fileMetadata, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
FileUploadProgressListener listener = new FileUploadProgressListener();
uploader.setProgressListener(listener);
uploader.setDirectUploadEnabled(true);
insert.execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class FileUploadProgressListener implements MediaHttpUploaderProgressListener {
#SuppressWarnings("incomplete-switch")
#Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
break;
case INITIATION_COMPLETE:
break;
case MEDIA_IN_PROGRESS:
break;
case MEDIA_COMPLETE:
break;
}
}
}
and Download file from google drive look this

Google SDK is now android friendly. There is a full-access scope which gives you access to listing and reading all the drive files and which can be used in Android apps easily since our newer client library is Android-friendly! I also recommend watching this talk from Google IO which is explains how to integrate mobile apps with Drive
The library makes authentication easier
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(CalendarSample.class.getResourceAsStream("/client_secrets.json")));
// set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
.build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
The library runs on Google App Engine
Media Upload
class CustomProgressListener implements MediaHttpUploaderProgressListener {
public void progressChanged(MediaHttpUploader uploader) throws IOException {
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
System.out.println("Initiation has started!");
break;
case INITIATION_COMPLETE:
System.out.println("Initiation is complete!");
break;
case MEDIA_IN_PROGRESS:
System.out.println(uploader.getProgress());
break;
case MEDIA_COMPLETE:
System.out.println("Upload is complete!");
}
}
}
File mediaFile = new File("/tmp/driveFile.jpg");
InputStreamContent mediaContent =
new InputStreamContent("image/jpeg",
new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());
Drive.Files.Insert request = drive.files().insert(fileMetadata, mediaContent);
request.getMediaHttpUploader().setProgressListener(new CustomProgressListener());
request.execute();
You can also use the resumable media upload feature without the service-specific generated libraries. Here is an example:
File mediaFile = new File("/tmp/Test.jpg");
InputStreamContent mediaContent =
new InputStreamContent("image/jpeg",
new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());
MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, transport, httpRequestInitializer);
uploader.setProgressListener(new CustomProgressListener());
HttpResponse response = uploader.upload(requestUrl);
if (!response.isSuccessStatusCode()) {
throw GoogleJsonResponseException(jsonFactory, response);
}

I also tried this, I was searching for tutorials to upload some user data to their own account. But I did not found anything. Google suggests google firebase storage instead of google drive. If you think, how WhatsApp uses google drive to upload data. Then my answer is that google provides special service to WhatsApp. So use firebase storage, it is easy and very cheap and also updated. Use documentation to use them very properly. The docs are really awesome.

Related

How to make an Android REST client to post videos/images to a Jersey web service?

I have a functional web service in Jersey, that consumes a multi part form data like videos and images and stores them on a directory. I am able to upload videos and images from a browser. Now I want to upload them from an Android application by selecting from gallery Intent or camera.
How am I supposed to do so?
Any help will be appreciated. Here is my web service code.
#Path("/fileupload")
public class UploadFileService {
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
try {
String uploadedFileLocation = "/home/aamir/Downloads/" + fileDetail.getFileName();
// save it
saveToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation;
return output;
}
catch(Exception e)
{
return "error";
}
}
// save uploaded file to new location
private void saveToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = null;
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I suggest you use Retrofit to download the image. It's a great library for handling RESTful applications:
Use retrofit to download image file
You can use the Jersey client API in your Android app (or any other client API for that matter, Apache CXF springs to mind...). It lives in a standalone jar which you can add to your app as a dependency, then in your app create a shared client which you use to create requests.
From the Jersey client docs...
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");
Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");
MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
MyJAXBBean.class);
https://jersey.java.net/documentation/latest/client.html

how to read public folder from google drive on android

i want to create a comic reader project on android. In my database, i only save path to the chapter directory which was taken from folderID on google drive. When user request to read comic, i want to through google client api to browse folder and get all file inside it.
i've seen guilde on https://developers.google.com/drive/v2/reference/files/list
but i still do not understand how it works, specials parameter Drive, how can i get it?
Thanks for any supports.
private static List<File> retrieveAllFiles(Drive service) throws IOException {
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
return result;
}

Google Drive import Google Docs

I have the following code for getting DriveContents of a file in Google Drive. I'm able to import and get DriveContents of MS Word, text files, etc but when the file is native to Google (Google Doc, Google Sheets, etc.) i'm not able to get the contents. My code is below:
selectedFile.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
public void onResult(DriveApi.DriveContentsResult result) {
try {
if (!result.getStatus().isSuccess()) {
// display an error saying file can't be opened
Log.e(TAG, "Could not get file contents");
return;
}
// DriveContents object contains pointers
// to the actual byte stream
DriveContents contents = result.getDriveContents();
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
String contentsAsString = builder.toString();
contents.discard(getGoogleApiClient());
Log.i(TAG, contentsAsString);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Whenever I get a Google format file, it simply returns a result that is not a success and shows the error in my logs. How can I get the file contents of those files as well? Is there something special i'm supposed to do?
I'm reading the following documentation:
https://developers.google.com/drive/android/files
Not sure if this is the best solution but I did it the following way. I check in the metadata if it's a Google format (doc, sheets, etc) and if it is, I have an AsyncTask that does the below:
// accountName is the email address the user used when choosing which account
String scope = "oauth2:https://www.googleapis.com/auth/drive.file";
token = GoogleAuthUtil.getTokenWithNotification(fragment.getActivity(), accountName, scope, null);
After doing the above, you can get the file using the API:
https://developers.google.com/drive/web/manage-downloads
The token from the above gives the Authentication header token on the downloading. We can export the file as docx, pdf, etc and download it that way.

android acces google storage Version v1beta2 of this API is no longer available. Please try again using JSON API v1

When i try to list files on google storage i get this error
"code" : 400,
Version v1beta2 of this API is no longer available. Please try again using JSON API v1. To request temporary reinstatement for your project, please visit https://docs.google.com/forms/d/1isIxBZg3rsQbDN_TOalZaz1WT_ebJchsrlv-Qr_r9mY/viewform?entry.244568692=773473680319&entry.176324201=v1beta2&entry.1071661541-Qr_r9mY/prefill
how can i use JSON API v1 in my android application ?
here is my code
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
Storage storage = getStorage();
Storage.Objects.List listObjects = storage.objects().list(mContext.getString(R.string.storage_bucket_name));
com.google.api.services.storage.model.Objects objects;
do {
objects = listObjects.execute();
List<StorageObject> items = objects.getItems();
if (null == items) {
System.out.println("There were no objects in the given bucket; try adding some and re-running.");
break;
}
for (StorageObject object : items) {
System.out.println(object.getName() + " (" + object.getSize() + " bytes)");
}
listObjects.setPageToken(objects.getNextPageToken());
} while (null != objects.getNextPageToken());
} catch (IOException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
The exceptions is throwen in this line: objects = listObjects.execute();
private Storage getStorage() throws Exception {
if (sStorage == null) {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
List<String> scopes = new ArrayList<String>();
scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
AssetManager am = mContext.getAssets();
InputStream inputStream = am.open(mContext.getResources().getString(R.string.storage_p12_key_path)); // you
File file = UtilsMedia.stream2file(inputStream);
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
.setServiceAccountId(mContext.getResources().getString(R.string.storage_mail_id))
.setServiceAccountScopes((scopes)).setServiceAccountPrivateKeyFromP12File(file). build();
sStorage = new Storage.Builder(httpTransport, jsonFactory, credential).setApplicationName("Veolia e-fsm").build();
}
return sStorage;
}
ny help would be greatly appreciated
What version of the storage client are you using?
Are you using Maven? Perhaps the google-api-services-storage package? You may have accidentally chosen a "v1beta2" version by mistake. I believe the current version is "v1-rev35-1.20.0".
"v1beta1" and "v1beta2" are old, beta versions of this API and are no longer usable.

Sharing file on google drive

I am developing android app which share the content to friends using Google Drive.So is it possible to share file programatically using google drive in android?
Yes that is possible, if you don't include a standard share functionality in your app but want to upload specifically to Google Drive you are going to have to use the Google Drive APIs. It's a little more complex so I'm not going to post a full solution but I will show you the important parts. I suggest you take a look at one of these example projects:
Google Docs Upload Example
Google Drive Quickstart Example
But anyway here are the important parts:
First you have to create an API client which will look something like this:
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this);
// Add Drive API
mGoogleApiClient.addApi(Drive.API);
// Set Scope
mGoogleApiClient.addScope(Drive.SCOPE_FILE);
// Add required callbacks
mGoogleApiClient.addConnectionCallbacks(this);
mGoogleApiClient.addOnConnectionFailedListener(this);
// Build client
mGoogleApiClient.build();
And with this API client you can upload/download/move/copy/delete files and folders etc.
Uploading a file would look something like this:
Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
// Check for success
if (!result.getStatus().isSuccess()) {
return;
}
// Upload file
OutputStream outputStream = result.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.", e);
}
// Set meta data
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder();
metadataChangeSet.setMimeType("image/jpeg");
metadataChangeSet.setTitle("Android Photo.png");
metadataChangeSet.build();
// Create file chooser
IntentSender intentSender = Drive.DriveApi.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(result.getContents())
.build(mGoogleApiClient);
// Show file chooser
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.", e);
}
}
});
Google Drive Sharing is accomplished using Google Drive API for Java as follows
googleDrive.permissions.insert(Permission);
Permission newPermission = new Permission();
newPermission.setValue(emailvalue);
newPermission.setType(type);
newPermission.setRole(role);
try {
service.permissions().insert(fid, newPermission).execute();
showToast("Done Shared successfully!!!!!!");
} catch (IOException e) {
System.out.println("An error occurred: " + e);
}

Categories

Resources