Accessing users google drive without using Android Activities - android

I am trying to implement an android app where the app uploads images to users google drive. I successfully implemented the quick start guide given here. It is uploading the images but all the examples/samples of uploading the image using android Activity. I went through the documentation provided by google but it is very loosely coupled.
Is there any example/sample which upload the file without using an activity so that later I could convert it into a background service?
I reached the following point. Now, at this point GoogleSignIn.getLastSignedInAccount is returning null and I am looking for a solution where it picks the account and gets the permission from the user. In google sample it appears to do in startActivityForResult. I tried to look for that too but there is no Drive REST v3 samples for Android.
package com.mpathak.drivetesting;
import android.content.Context;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.drive.CreateFileActivityOptions;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveClient;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveResourceClient;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.tasks.Task;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class DriveSample {
private GoogleSignInClient mGoogleSignInClient;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
private Context _context;
private static final String TAG = "drive-Testing";
public DriveSample(Context context)
{
_context = context;
}
public void uploadFile()
{
GoogleSignInClient GoogleSignInClient = buildGoogleSignInClient();
mDriveClient = Drive.getDriveClient(_context, GoogleSignIn.getLastSignedInAccount(_context));
mDriveResourceClient =
Drive.getDriveResourceClient(_context, GoogleSignIn.getLastSignedInAccount(_context));
saveFileToDrive();
}
private GoogleSignInClient buildGoogleSignInClient() {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build();
return GoogleSignIn.getClient(_context, signInOptions);
}
private void saveFileToDrive() {
Log.i(TAG, "Creating new contents.");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
final Bitmap image = BitmapFactory.decodeFile("/DCIM/Camera/some_image.jpg", options);
mDriveResourceClient
.createContents()
.continueWithTask(
task -> createFileIntentSender(task.getResult(), image))
.addOnFailureListener(
e -> Log.w(TAG, "Failed to create new contents.", e));
}
private Task<Void> createFileIntentSender(DriveContents driveContents, Bitmap image) {
Log.i(TAG, "New contents created.");
OutputStream outputStream = driveContents.getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e) {
Log.w(TAG, "Unable to write file contents.", e);
}
MetadataChangeSet metadataChangeSet =
new MetadataChangeSet.Builder()
.setMimeType("image/jpeg")
.setTitle("Android Photo.png")
.build();
CreateFileActivityOptions createFileActivityOptions =
new CreateFileActivityOptions.Builder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(driveContents)
.build();
return mDriveClient
.newCreateFileActivityIntentSender(createFileActivityOptions)
.continueWith(
task -> {
return null;
});
}
}

Related

Converting image to bas64string in react.native.android SDK using pdfbox

I am trying to extract text from a pdf and want to also include images.
Those images I am getting from pdfbox page object.
Now what I have in mind is using base64converter.
After searching the net I found that I could use The below code to do it
public static String imgToBase64String(final BufferedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, os);
return Base64.getEncoder().encodeToString(os.toByteArray());
} catch (final IOException ioe) {
return "";
}
}
The problem With the below code is that in react-native.android dose not include BufferedImage , ImageIO or Base64 in its SDK
How am I going to do this? Are there any alternative way in doing this?
Here is the complete code below incase
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;
import com.facebook.react.bridge.Promise;
import com.viliussutkus89.android.pdf2htmlex.pdf2htmlEX;
import java.io.File;
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import com.tom_roush.pdfbox.pdmodel.PDDocument;
import com.tom_roush.pdfbox.pdmodel.PDDocumentInformation;
import com.tom_roush.pdfbox.pdmodel.PDDocumentCatalog;
import com.tom_roush.pdfbox.pdmodel.PDPage;
import com.tom_roush.pdfbox.PDXObject;
import com.tom_roush.pdfbox.COSName;
import com.tom_roush.pdfbox.pdmodel.PDResources;
import com.tom_roush.pdfbox.pdmodel.PDPageContentStream;
import com.tom_roush.pdfbox.pdmodel.encryption.AccessPermission;
import com.tom_roush.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import com.tom_roush.pdfbox.pdmodel.font.PDFont;
import com.tom_roush.pdfbox.pdmodel.font.PDType1Font;
import com.tom_roush.pdfbox.pdmodel.graphics.image.JPEGFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.LosslessFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.PDImageXObject;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDAcroForm;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDCheckBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDComboBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDField;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDListBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDRadioButton;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDTextField;
import com.tom_roush.pdfbox.rendering.ImageType;
import com.tom_roush.pdfbox.rendering.PDFRenderer;
import com.tom_roush.pdfbox.text.PDFTextStripper;
import com.tom_roush.pdfbox.android.PDFBoxResourceLoader;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.Arguments;
// below Import are not found in the SDK
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.util.Base64;
import java.util.UUID;
public class PdfToHtmlModule extends ReactContextBaseJavaModule {
// add to CalendarModule.java
#Override
public String getName() {
return "PdfToHtmlModule";
}
private ReactApplicationContext appContext;
PdfToHtmlModule(ReactApplicationContext context) {
super(context);
appContext = context;
PDFBoxResourceLoader.init(appContext.getApplicationContext());
}
public static String imgToBase64String(final BufferedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, os);
return Base64.getEncoder().encodeToString(os.toByteArray());
} catch (final IOException ioe) {
return "";
}
}
#ReactMethod
public void getCompleteTextFromPdf(String pdfFilePath, Promise promise) {
try {
String pdfText = "";
File file = new File(pdfFilePath);
WritableMap params = this.getPDFInfo(file);
WritableArray array = new WritableNativeArray();
PDDocument pddoc = PDDocument.load(file);
if (pddoc.isEncrypted()) {
pddoc.setAllSecurityToBeRemoved(true);
}
for (int i = 0; i < pddoc.getNumberOfPages(); i++) {
PDFTextStripper pdfstripper = new PDFTextStripper();
pdfstripper.setStartPage(i);
pdfstripper.setEndPage(i);
pdfText = pdfstripper.getText(pddoc);
PDPage page = pddoc.getPage(i);
PDResources rs = page.getResources();
for (COSName cosObj : rs.getXObjectNames()) {
PDXObject obj = rs.getXObject(cosObj);
if (obj instanceof PDImageXObject) {
// this doe not work yet
String base64String = PdfToHtmlModule.imgToBase64String(((PDImageXObject) obj).getImage(), "png");
if (base64String != "")
array.pushString("data:image/png;" + base64String);
}
}
array.pushString(pdfText);
}
pddoc.close();
params.putArray("chapters", array);
promise.resolve(params);
} catch (Exception e) {
promise.reject(e.getMessage());
}
}
}

Uploading an Image to Google Drive Using Drive API

I am trying to upload an image to the google drive using drive API. As the first step, I developed a code to upload a PDF file (file path is hard coded) to the google drive by following a tutorial.
PDF will be uploaded successfully but sometimes I get a time out message from the log. this may be because of my poor connection. But is there a proper way to handle this by the code when something like this happens?
Please guide me on how to upload an image instead of PDF by changing this code. I tried but I could not do it successfully. Please Help for this part. I am stuck here for two days
import android.util.Log;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.api.client.http.FileContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class DriveServiceHelper {
private final Executor mExecutor = Executors.newSingleThreadExecutor();
private Drive mDriveService;
public DriveServiceHelper(Drive mDriveService){
this.mDriveService = mDriveService;
}
public Task<String> createFilePdf(String filePath){
return Tasks.call(mExecutor, () -> {
File fileMetaData = new File();
fileMetaData.setName("MyPDFFile");
java.io.File file = new java.io.File(filePath);
FileContent mediaContent = new FileContent("application/pdf",file);
File myFile = null;
try {
myFile = mDriveService.files().create(fileMetaData,mediaContent).execute();
}catch (Exception e){
e.printStackTrace();
Log.i("myissue", e.getMessage());
}
if (myFile == null){
throw new IOException("Null result when requesting file creation");
}
return myFile.getId();
});
}
}
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
DriveServiceHelper driveServiceHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestSignIn();
}
private void requestSignIn() {
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestScopes(new Scope(DriveScopes.DRIVE_FILE))
.build();
GoogleSignInClient client = GoogleSignIn.getClient(this,signInOptions);
startActivityForResult(client.getSignInIntent(),400);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 400:
if (resultCode == RESULT_OK){
handleSignInIntent(data);
break;
}
}
}
private void handleSignInIntent(Intent data) {
GoogleSignIn.getSignedInAccountFromIntent(data)
.addOnSuccessListener(new OnSuccessListener<GoogleSignInAccount>() {
#Override
public void onSuccess(GoogleSignInAccount googleSignInAccount) {
GoogleAccountCredential credential = GoogleAccountCredential
.usingOAuth2(MainActivity.this, Collections.singleton(DriveScopes.DRIVE_FILE));
credential.setSelectedAccount(googleSignInAccount.getAccount());
Drive googleDriveServices = new Drive.Builder(
AndroidHttp.newCompatibleTransport(),
new GsonFactory(),
credential)
.setApplicationName("uploadtodrive")
.build();
driveServiceHelper = new DriveServiceHelper(googleDriveServices);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
public void uploadPdfFile(View v){
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Uploading to google Drive");
progressDialog.setMessage("Please wait........");
progressDialog.show();
String filePath = "/storage/emulated/0/mypdf.pdf";
driveServiceHelper.createFilePdf(filePath).addOnSuccessListener(new OnSuccessListener<String>() {
#Override
public void onSuccess(String s) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Check your google Drive api key",Toast.LENGTH_SHORT).show();
}
});
}
}
Please Help for this part. I am stuck here for two days. thank you
Set appropriate MIME type:
In order to upload a specific file type to Drive, you have to specify its MIME type on the media content. In your case, this is handled by FileContent:
FileContent mediaContent = new FileContent("application/pdf",file);
So you would have to replace application/pdf with the appropriate MIME type (see for example the supported MIME types in G Suite documents). Possible MIME types for images include image/jpeg and image/png. For example, you could do this:
FileContent mediaContent = new FileContent("image/jpeg",file);
Note:
I'm assuming that you do have an image on the provided filePath.
Reference:
MIME types (IANA media types)

How to get only the contents of a .txt file in dropbox using the dropbox api v2 using android

i want to get the contents of a file in dropbox. in the internet i found only the options to download the file. but it gives me the file not found exception.
java.io.FileNotFoundException: /storage/emulated/0/Download/Temp/test.txt (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
at com.codeyard.teleprompter.DownloadFileTask.doInBackground(DownloadFileTask.java:72)
at com.codeyard.teleprompter.DownloadFileTask.doInBackground(DownloadFileTask.java:23)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:762)
2019-11-26 13:25:59.512 15240-15240/com.codeyard.teleprompter E/ViewRootImpl: sendUserActionEvent() returned.
how can i get ONLY THE CONTENTS and not DOWNLOAD the file completely
package com.codeyard.teleprompter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import com.dropbox.core.DbxException;
import com.dropbox.core.v2.DbxClientV2;
import com.dropbox.core.v2.files.FileMetadata;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Task to download a file from Dropbox and put it in the Downloads folder
*/
class DownloadFileTask extends AsyncTask<String, Void, File> {
private static final String TAG = "TELEPROMPTER";
#SuppressLint("StaticFieldLeak")
private final Context mContext;
private final DbxClientV2 mDbxClient;
private final Callback mCallback;
private Exception mException;
public interface Callback {
void onDownloadComplete(File result);
void onError(Exception e);
}
DownloadFileTask(Context context, DbxClientV2 dbxClient, Callback callback) {
mContext = context;
mDbxClient = dbxClient;
mCallback = callback;
}
#Override
protected void onPostExecute(File result) {
super.onPostExecute(result);
if (mException != null) {
mCallback.onError(mException);
} else {
mCallback.onDownloadComplete(result);
}
}
#Override
protected File doInBackground(String... params) {
String metadata = params[0];
try {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, metadata);
// Make sure the Downloads directory exists.
if (!path.exists()) {
if (!path.mkdirs()) {
mException = new RuntimeException("Unable to create directory: " + path);
}
} else if (!path.isDirectory()) {
mException = new IllegalStateException("Download path is not a directory: " + path);
return null;
}
//Download the file.
try (OutputStream outputStream = new FileOutputStream(file)) {
mDbxClient.files().download(metadata.toLowerCase())
.download(outputStream);
}
// Tell android about the file
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
mContext.sendBroadcast(intent);
return file;
} catch (DbxException | IOException e) {
mException = e;
}
return null;
}
}
maybe there is any method to call from the dropbox api v2???
what i want is that only the text contetn into like a string or something. the code is from the official github repo
Your problem has nothing to do with downloading but all wit statement
(OutputStream outputStream = new FileOutputStream(file))
But instead of a FIleOutputStream you could open a ByteArrayOutputStream.
In that way you keep alll bytes in memory and dont have to save.

Bluemix: How to insert JSON in Cloudant in Android with Replicator?

I am finding it difficult to make this simple upload. I've used all encontrandos tutorials on the internet such as Bluelist and android-sync. I already have a database created within the service. My code is as follows:
MainActivity.java
package com.example.engenharia.replicator;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreException;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.DocumentRevision;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.query.IndexManager;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
public class MainActivity extends AppCompatActivity {
private static final String DATASTORE_MANGER_DIR = "data";
private Datastore DataStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
URI uri = new URI(my_uri);
File path = getApplicationContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
DataStore = manager.openDatastore("banco0"); //banco0 is the DB created in Cloudant NoSQL service.
// Create a replicator that replicates changes from the local
// datastore to the remote database.
Replicator replicator = ReplicatorBuilder.push().to(uri).from(DataStore).build();
// Use a CountDownLatch to provide a lightweight way to wait for completion
CountDownLatch latch = new CountDownLatch(1);
Listener listener = new Listener(latch);
replicator.getEventBus().register(listener);
replicator.start();
latch.await();
replicator.getEventBus().unregister(listener);
if(replicator.getState() != Replicator.State.COMPLETE){
System.out.println("Error replicating TO remote");
System.out.println(listener.error);
} else {
System.out.println(String.format("Replicated %d documents in %d batches",
listener.documentsReplicated, listener.batchesReplicated));
}
}catch (Exception e){
e.printStackTrace();
}
}
public DocumentRevision createDocument() {
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.body = DocumentBodyFactory.create(HashMap());
try {
return DataStore.createDocumentFromRevision(rev);
} catch (DocumentException e) {
//throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
public Map<String, Object> HashMap() {
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Street", "121");
map1.put("Street1", "12112");
map1.put("Street123", "1211111");
String[] array1 = new String[]{"Cloudant", "NoSQL", "JSON"};
map.put("address", map1);
map.put("description", "This is sample description");
map.put("skills", array1);
return map;
}
}
listener.java
package com.example.engenharia.replicator;
import com.cloudant.sync.notifications.ReplicationCompleted;
import com.cloudant.sync.notifications.ReplicationErrored;
import com.cloudant.sync.replication.ErrorInfo;
import com.google.common.eventbus.Subscribe;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.util.concurrent.CountDownLatch;
/**
* Created by engenharia on 19/08/16.
*/
public class Listener {
private final CountDownLatch latch;
public ErrorInfo error = null;
public int documentsReplicated;
public int batchesReplicated;
Listener(CountDownLatch latch) {
this.latch = latch;
}
#Subscribe
public void complete(ReplicationCompleted event) {
this.documentsReplicated = event.documentsReplicated;
this.batchesReplicated = event.batchesReplicated;
latch.countDown();
}
#Subscribe
public void error(ReplicationErrored event) {
this.error = event.errorInfo;
latch.countDown();
}
}
Executing this code I have the follow error:
CouchException: error: forbidden, reason: server_admin access is
required for this request, statusCode: 403, msg: null, cause: null
But I am the admin!
How do I fix the problem or what is the solution?

How to upload a db file to google drive from android application?

I want to upload a db file from my app to google drive. I am able to create a folder in google drive but I am not getting how to upload db file .
This is my code.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.DriveFolder.DriveFolderResult;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.Metadata;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.api.client.http.FileContent;
//import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
//import com.google.api.services.drive.Drive;
public class MainActivity extends BaseDemoActivity {
private final static String TAG = "MainActivity";
DriveId folderId;
private static Uri fileUri;
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle("New folder").build();
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet)
.setResultCallback(folderCreatedCallback);
saveToDrive();
}
ResultCallback<DriveFolderResult> folderCreatedCallback = new ResultCallback<DriveFolderResult>() {
#Override
public void onResult(DriveFolderResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the folder");
return;
}
folderId = result.getDriveFolder().getDriveId();
showMessage("Created a folder: " + result.getDriveFolder().getDriveId());
}
};
final ResultCallback<DriveFolder.DriveFileResult> fileCallBack = new ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult driveFileResult) {
if (!driveFileResult.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
//Initialize mFile to be processed in AsyncTask
DriveFile mfile = driveFileResult.getDriveFile();
new EditContentsAsyncTask(MainActivity.this).execute(mfile);
}
};
public void saveToDrive()
{
fileUri = Uri.fromFile(new java.io.File(Environment.getDataDirectory().getPath()
+ "/data/com.example.dbupload/databases/Student"));
java.io.File fileContent = new java.io.File(fileUri.getPath());
FileContent mediaContent = new FileContent(getMimeType("db"), fileContent);
File body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType(getMimeType("db"));
// File file = service.files().insert(body, mediaContent).execute();
}
public class EditContentsAsyncTask extends ApiClientAsyncTask<DriveFile, Void, Boolean> {
public EditContentsAsyncTask(Context context) {
super(context);
}
#Override
protected Boolean doInBackgroundConnected(DriveFile... args) {
DriveFile file = args[0];
try {
DriveContentsResult driveContentsResult = file.open(
getGoogleApiClient(), DriveFile.MODE_WRITE_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
//edit the outputStream
DatabaseHandler db = new DatabaseHandler(MainActivity.this);
String inFileName = getApplicationContext().getDatabasePath(db.getDatabaseName()).getPath();
//DATABASE PATH
FileInputStream is = new FileInputStream(inFileName);
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 * 1024];
BufferedOutputStream out = new BufferedOutputStream(driveContents.getOutputStream());
int n = 0;
while ((n = in.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
in.close();
com.google.android.gms.common.api.Status status =
driveContents.commit(getGoogleApiClient(), null).await();
return status.getStatus().isSuccess();
} catch (IOException e) {
Log.e(TAG, "IOException while appending to the output stream", e);
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
private String getMimeType(String string) {
// TODO Auto-generated method stub
return null;
}
}
I am able to create a folder in drive. can any one please help me what I should do for uploading a db file?
First, the fact that I'm seeing these imports:
import com.google.api.client.http.FileContent;
...
import com.google.api.services.drive.Drive;
indicates that you're mixing GDAA and the REST Api. Do not do it unless you want to get in trouble.
So, when you got your FolderId, it is a parent of your 'DB' file, I presume (and if the DB file is a SQLite type, your MIME TYPE should be 'application/x-sqlite3').
Anyway, in GDAA, you first have to turn your java.io.File (that represents the 'DB') into content. And you have to supply metadata (like file title, mime type, flags ...). You got the metadata right, it is the content you tripped over. The following snippet should do what you need (don't hold me accountable, I slammed it together in 5 minutes - no testing)
/******************************************************************
* create file in GOODrive
* #param pFldr parent's ID
* #param titl file name
* #param mime file mime type (application/x-sqlite3)
* #param file file (with content) to create
*/
static void saveToDrive(final DriveFolder pFldr, final String titl,
final String mime, final java.io.File file) {
if (getGoogleApiClient() != null && pFldr != null && titl != null && mime != null && file != null) try {
// create content from file
Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult driveContentsResult) {
DriveContents cont = driveContentsResult != null && driveContentsResult.getStatus().isSuccess() ?
driveContentsResult.getDriveContents() : null;
// write file to content, chunk by chunk
if (cont != null) try {
OutputStream oos = cont.getOutputStream();
if (oos != null) try {
InputStream is = new FileInputStream(file);
byte[] buf = new byte[4096];
int c;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
}
finally { oos.close();}
// content's COOL, create metadata
MetadataChangeSet meta = new Builder().setTitle(titl).setMimeType(mime).build();
// now create file on GooDrive
pFldr.createFile(getGoogleApiClient(), meta, cont).setResultCallback(new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult driveFileResult) {
if (driveFileResult != null && driveFileResult.getStatus().isSuccess()) {
// BINGO
} else {
// report error
}
}
});
} catch (Exception e) { e.printStackTrace(); }
}
});
} catch (Exception e) { e.printStackTrace(); }
}
I noticed, you're adapting the 'official' GDAA DEMO for your project. In case it is not sufficient or overwhelming, you may also look at this demo, that takes a different approach to the same problem.
Good Luck
Check your mime type of database file.
private String getMimeType(String string) {
//set return "application/x-sqlite3";
return "application/x-sqlite3";
}

Categories

Resources