Google Drive android Completion listener - google-drive-android-api

I am working with the Google Drive api for android. I am able to upload file using CreateFileActivityOptions Builder. Is there a way to listen to the completion of file upload when using this class.
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(file.getName())
.setMimeType("audio/mp3")
.setStarred(false)
.build();
CreateFileActivityOptions createOptions =
new CreateFileActivityOptions.Builder()
.setInitialDriveContents(contents)
.setInitialMetadata(changeSet)
.build();
return driveClient.newCreateFileActivityIntentSender(createOptions);

Try using this sample code in their documentation :
Task<DriveContents> createContentsTask = getDriveResourceClient().createContents();
createContentsTask
.continueWithTask(task -> {
DriveContents contents = task.getResult();
OutputStream outputStream = contents.getOutputStream();
try (Writer writer = new OutputStreamWriter(outputStream)) {
writer.write("Hello World!");
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("New file")
.setMimeType("text/plain")
.setStarred(true)
.build();
CreateFileActivityOptions createOptions =
new CreateFileActivityOptions.Builder()
.setInitialDriveContents(contents)
.setInitialMetadata(changeSet)
.build();
return getDriveClient().newCreateFileActivityIntentSender(createOptions);
})
.addOnSuccessListener(this,
intentSender -> {
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATE_FILE, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Unable to create file", e);
showMessage(getString(R.string.file_create_error));
finish();
}
})
.addOnFailureListener(this, e -> {
Log.e(TAG, "Unable to create file", e);
showMessage(getString(R.string.file_create_error));
finish();
});
That would be the closest onComplete (sort of) listener for newCreateFileActivityIntentSender.

Related

Using Google Drive Api on android studio?

i am working on app that integrates google drive api to upload/download files from the user's Google Drive account. i am using
this documentation google drive api v3, but it dont work,
i got this error ->
'java.net.MalformedURLException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference', i can login into google account and log out, but cant uplodad files
public Task<String> newFile(String filepath) {
return Tasks.call(executor, () -> {
File fmdt = new File();
fmdt.setName("contents.json");
java.io.File fp = new java.io.File(filepath);
FileContent mediaContent = new FileContent("application/json",fp);
File mf = null;
try {
mf = driveService.files().create(fmdt, mediaContent).setFields("id").execute();
} catch (Exception e) {
e.printStackTrace();
Log.d("usr","drive-> "+e.getMessage() );
}
if (mf == null) {
throw new IOException("null result");
}
return mf.getId();
});
}
this is how i solve, i guest you re actualli singin on goggle
//the class that handle upload request
public class GoogleDriveHelper {
private final Executor executor = Executors.newSingleThreadExecutor();
private final Drive driveService;
public GoogleDriveHelper(Drive mDriveService) {
this.driveService = mDriveService;
}
public Task<String> newFile(String fileName, String path, String parentId, File file) {
return Tasks.call(executor, () -> {
//use parent to save in especific folder
File fmdt = new File()
.setParents(Collections.singletonList(parentId))
.setMimeType("application/octet-stream")
.setName(nfileName);
File mf = null;
FileContent mediaContent = new FileContent("application/octet-stream", file);
try {
mf = driveService.files().create(fmdt, mediaContent).setFields("id").execute();
} catch (Exception e) {
e.printStackTrace();
}
if (mf == null) {
throw new IOException("null result");
}
return mf.getId();
});
}}
//inicialize google drive service
val credential =
GoogleAccountCredential.usingOAuth2(
ctx,
Collections.singleton(DriveScopes.DRIVE_FILE)
)
credential.selectedAccount = account!!.account
gService = Drive.Builder(
AndroidHttp.newCompatibleTransport(),
GsonFactory(),
credential
).
setApplicationName(APPLICATION_NAME).build();
gDrivehelper = GoogleDriveHelper(gService)

How do I save an openJFX11 Canvas as a png/bitmap?

Google is giving me a lot of old results for this (JavaFX). People point you at code using:
RenderedImage, SwingFXUtils and ImageIO
I have openJFX11 and it does not contain these libraries.
How can I save the canvas using built in JFX11 libraries?
My SaveUtil class using old libraries that can't be found:
public void saveCanvas(){
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter =
new FileChooser.ExtensionFilter("png files (*.png)", "*.png");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fileChooser.showSaveDialog(primaryStage);
if(file != null){
try {
WritableImage writableImage = new WritableImage(CANVAS_WIDTH, CANVAS_HEIGHT);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
}
}

get stream from multipartFileData, file in use

Hello im trying to access an image from a post request with MultipartFormDataStreamProvider.
So far it seems successful other than when i try to create a file steam from the local name, the file is then in use. How do i get the current open stream to read the file, or get the old stream to close?
*Note: Please ignore the not so great try catch.
What I have so far:
[ResponseType(typeof(AdminImage))]
public IHttpActionResult PostAdminImage([FromUri]AdminImage adminImage)
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
FileStream fs = new FileStream(file.LocalFileName, FileMode.Open);
adminImage.ImageContent = adminImage.ImageToByteArray(Image.FromStream(fs));
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.AdminImages.Add(adminImage);
db.SaveChanges();
}
catch (Exception ex)
{
return InternalServerError();
}
return CreatedAtRoute("DefaultApi", new { id = adminImage.Id }, adminImage);
}

Windows 8.1 BackgroundUploader with Amazon S3 c# in XAML

Trying to upload files from Windows 8.1 to Amazon s3 in Background. Kindly suggest how can I proceed.
I am using XAML. code Snippet of BackgroundDownloader and BackgroundUploader with Amazon S3 will be a great help.
Please find partial implementation of it below.
public async Task UploadFile(IReadOnlyList<StorageFile> files)
{
basicAwsCredentials = new BasicAWSCredentials(accesskey,secretkey);
List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>();
for (int i = 0; i < files.Count; i++)
{
BackgroundTransferContentPart part = new BackgroundTransferContentPart("File" + i, files[i].Name);
part.SetFile(files[i]);
parts.Add(part);
}
Uri uri = new Uri(bucketurl+ExistingBucketName+"/");
BackgroundUploader uploader = new BackgroundUploader();
UploadOperation upload = await uploader.CreateUploadAsync(uri, parts);
// Attach progress and completion handlers.
await HandleUploadAsync(upload, true);
}
private async Task HandleUploadAsync(UploadOperation upload, bool start)
{
try
{
CancellationTokenSource cts = new CancellationTokenSource();
Progress<UploadOperation> progressCallback = new Progress<UploadOperation>();
if (start)
{
// Start the upload and attach a progress handler.
await upload.StartAsync().AsTask(cts.Token, progressCallback);
}
else
{
// The upload was already running when the application started, re-attach the progress handler.
await upload.AttachAsync().AsTask(cts.Token, progressCallback);
}
ResponseInformation response = upload.GetResponseInformation();
// Log(String.Format("Completed: {0}, Status Code: {1}", upload.Guid, response.StatusCode));
}
catch (TaskCanceledException)
{
// Log("Upload cancelled.");
}
catch (Exception ex)
{
//LogException("Error", ex);
}
}

Adding new revision for document in DropBox through android api

I want to add a new revision to the document(Test.doc) in Dropbox using android api. Can anyone share me any sample code or links. I tried
FileInputStream inputStream = null;
try {
DropboxInputStream temp = mDBApi.getFileStream("/Test.doc", null);
String revision = temp.getFileInfo().getMetadata().rev;
Log.d("REVISION : ",revision);
File file = new File("/sdcard0/renamed.doc");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/Test.doc", inputStream, file.length(), revision, new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
Log.d("","Uploading.. "+arg0+", Total : "+arg1);
}
});
} catch (Exception e) {
System.out.println("Something went wrong: " + e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
New revision is created for first time. When i execute again, another new revision is not getting created.