java,android,google-drive-sdk,google-drive-android-api , Upload text file to Google Drive using Android

Upload text file to Google Drive using Android


Tag: java,android,google-drive-sdk,google-drive-android-api

Edited: I have set my text into a string like so:

String text = ("Hello!");

I want to turn this into a plain text file and then upload to a Google Drive Folder. I have tried on the code below, but it is not complete so I cannot say what errors appear.

I am using the Google Drive "Quick-start" Demo, and trying to tailor it for what I need. Link:


public class UploadDrive extends Activity implements ConnectionCallbacks,OnConnectionFailedListener {

 private static final String TAG = "androiddrivequickstart";
 private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
 private static final int REQUEST_CODE_CREATOR = 2;
 private static final int REQUEST_CODE_RESOLUTION = 3;
 private GoogleApiClient mGoogleApiClient;
 private Bitmap mBitmapToSave;

 private void saveFileToDrive() {
    // Start by creating a new contents, and setting a callback.
    Log.i(TAG, "Creating new contents.");
    //How to call? Can i use File from
    final Bitmap image = mBitmapToSave;
    Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveContentsResult>() {

        public void onResult(DriveContentsResult result) {
            // If the operation was not successful, we cannot do anything
            // and must
            // fail.
            if (!result.getStatus().isSuccess()) {
                Log.i(TAG, "Failed to create new contents.");
            // Otherwise, we can write our data to the new contents.
            Log.i(TAG, "New contents created.");
            // Get an output stream for the contents.

            OutputStream outputStream = result.getDriveContents().getOutputStream();

            // Write the bitmap data from it.
            ByteArrayOutputStream textFile = new ByteArrayOutputStream();
            //image.compress(Bitmap.CompressFormat.PNG, 100, textFile);
            try {
            } catch (IOException e1) {
                Log.i(TAG, "Unable to write file contents.");
            // Create the initial metadata - MIME type and title.
            // Note that the user will be able to change the title later.
            MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                    .setMimeType("text/plain").setTitle("Log: test.txt").build();
            // Create an intent for the file chooser, and start it.
            IntentSender intentSender = Drive.DriveApi
            try {
                        intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
            } catch (SendIntentException e) {
                Log.i(TAG, "Failed to launch file chooser.");

protected void onResume() {
    if (mGoogleApiClient == null) {
        // Create the API client and bind it to an instance variable.
        // We use this instance as the callback for connection and connection
        // failures.
        // Since no account name is passed, the user is prompted to choose.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
    // Connect the client. Once connected, the camera is launched.

protected void onPause() {
    if (mGoogleApiClient != null) {

protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    switch (requestCode) {
            // Called after a photo has been taken.
            if (resultCode == Activity.RESULT_OK) {
                // Store the image data as a bitmap for writing later.
                mBitmapToSave = (Bitmap) data.getExtras().get("data");
            // Called after a file is saved to Drive.
            if (resultCode == RESULT_OK) {
                Log.i(TAG, "Image successfully saved.");
                mBitmapToSave = null;
                // Just start the camera again for another photo.
                startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),REQUEST_CODE_CAPTURE_IMAGE);

public void onConnectionFailed(ConnectionResult result) {
    // Called whenever the API client fails to connect.
    Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
    if (!result.hasResolution()) {
        // show the localized error dialog.
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
    // The failure has a resolution. Resolve it.
    // Called typically when the app is not yet authorized, and an
    // authorization
    // dialog is displayed to the user.
    try {
        result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
    } catch (SendIntentException e) {
        Log.e(TAG, "Exception while starting resolution activity", e);

public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "API client connected.");
    if (mBitmapToSave == null) {
        // This activity has no UI of its own. Just start the camera.
        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),

public void onConnectionSuspended(int cause) {
    Log.i(TAG, "GoogleApiClient connection suspended");

How do I call the finalResultText which is in another class called MainActivity so I can make it into a plain text file to be uploaded to a Google Drive folder?


Assuming that you question is: 'How do I upload a text file to Google Drive?', here is the quick overview:

1/ Get your app authorized on developers console, see this. Basically, tell Google that your app represented by SHA1 / 'package-name' needs access to Drive API (don't forget your email address on the consent screen). This authorization is good for both REST and GDAA api.

2/ Decide if you want to use REST or GDAA API to access the Drive. Each has advantages/disadvantages (but it's a long story).

3/ Take a look at the REST/GDAA wrapper demo here, it has the app authorization process in the MainActivity class (see onConnFail() method), and basic CRUD methods for both REST and GDAA in their respective classes.

Good Luck

Based on your comments below, I assume you want to force the QuickStart demo to work for you. Keep in mind that GDAA (or REST) don't care what the content is It is just a bunch of bytes. So, as QuickStart turns the Bitmap into PNG and feeds the output stream with it's bytes, you have to do it with your bunch-of-bytes. I quickly smacked together 2 primitives below, that would feed the DriveContents' output stream with file or byte array (and you can turn whatever you've got into a file or byte[]).

 DriveContents file2Cont(DriveContents driveContents, file) {
    OutputStream oos = driveContents.getOutputStream();
    if (oos != null) try {
      InputStream is = new FileInputStream(file);
      byte[] buf = new byte[8192];
      int c = 0;
      while ((c =, 0, buf.length)) > 0) {
        oos.write(buf, 0, c);
    } catch (Exception e)  {/*handle errors*/}
    finally {
      try {
      } catch (Exception ignore) { }
    return driveContents;

  DriveContents bytes2Cont(DriveContents driveContents, byte[] buf) {
    OutputStream os = driveContents.getOutputStream();
    try { os.write(buf);
    } catch (IOException e)  {/*handle errors*/}
     finally {
      try { os.close();
      } catch (Exception e) {/*handle errors*/}
    return driveContents;


Get document on some condition in elastic search java API

As I know we can parse document in elastic search, And when we search for a keyword, It will return the document using this code of java API:- searchHits = node.client() .prepareSearch() .setIndices("indices") .setQuery(qb) .setFrom(0).setSize(1000) .addHighlightedField("file.filename") .addHighlightedField("content") .addHighlightedField("meta.title") .setHighlighterPreTags("<span class='badge badge-info'>") .setHighlighterPostTags("</span>") .addFields("*", "_source")...

why is Android app publishing taking several days [on hold]

I have uploaded my app on the store 3 days ago and it status still : PENDING PUBLICATION I have uploaded all the app listing needed : description, screen shots ... and google didn't contact me on E-mail. does anyone had the same case before ???...

how to add menu items to action bar in more than 30 activities

I have created an app in android studio that has more than 30 activities .I created menu items in some activities by adding them in individual menu files and they worked fine . But the problem is that it is a real headache to add all the menu items in...

How can implement long running process in spring hibernate?

as we know the struts interceptor execute and wait will take care of long running process by not getting the request to timeout and destroy it sends wait and at last the desired response i want to implement the same for long running process in spring and hibernate. Thanks....

PropertyNotFoundException in jsp

Am getting this error in my application javax.el.PropertyNotFoundException: Property 'survey_id' not found on type com.moh.forms.MOH731 javax.el.BeanELResolver$BeanProperties.get( javax.el.BeanELResolver$BeanProperties.access$400( javax.el.BeanELResolver.getValue( This is my @Id @GeneratedValue(strategy = GenerationType.AUTO) private int survey_id; public MOH731 (int survey_id, String uname)...

Get current latitude and longitude android

Requirement: 1.Sometimes(not everytime) I am getting latitude and longitude 0.0. 2.I want to know how to get the location update after user has enabled the gps from the settings. Here is my code public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status...

Fixed element in android?

I am using a FAB(Floating action button) and a ViewPager that has a list inside a fragment. The ViewPager stops due to the FAB block and each are blocks the ViewPager being on top of the FAB activity_main.xml <LinearLayout xmlns:android="" xmlns:tools="" xmlns:fab="" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:fitsSystemWindows="true">...

Selenium catch popup on close browser

I'm trying to test that when I close my window a popup shows with a warning message. I've tried both driver.close() and driver.quit() after making sure I'm on the proper window but this just terminates the process since my popup doesn't show. I could test it by using the awt...

type conversion if flex

I am using Flerry as Java-Flex bridge for my Flex Desktop Application. How to convert List in Java to ArrayCollection in Flex Flex Code:- [Bindable]public var screenList:ArrayCollection; <flerry:NativeObject id="windowControllerObj" source="ls.window.EnumAllWindowNames" singleton="true" fault="windowControllerObj_faultHandler(event)"> <flerry:NativeMethod id="getWindowNames" name="getAllWindowNames" result="windowControllerObj_resultHandler(event)" fault="getWindowNames_faultHandler(event)"/>...

Javadoc: Do parameter and return need an explicit type description

When Javadoc'ing, I don't know whether you should explicitly say whether the parameters are of type String or int. For example /** * This method does something * @param foo an object of type Foo * @param abc the number of doors, of type int * @return the number of...

Problems implementing ViewHolder pattern

I'm working on an android app from a book. I'm getting errors : "crimeHolder cannot be resolved" and I can't understand why.. public View getView(int poisition, View convertView , ViewGroup parent) { //If we weren't given a view, inflate one if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_crime, null); ViewHolder...

BitmapFont class does not have getBound(String) method

Previously I used getBound method for BitmapFont class in libgdx, but now, I am unable to use it. I cannot find the changes in latest version. Any help is appreciated. Thank you...

Using world coordinates

I am currently using pixels as units for placing objects within my world, however this can get tedious because I only ever place objects every 16 pixels. For example, I would like to be able to place an object at position 2 and have the object rendered at the pixel...

Is there any sdk to log exceptions, events and errors in production app?

I want to catch all the un expected/undesirable events in my app during production. I want something which can send a error log file to server and I can easily read it through a web application. Do you know anything of this sort ?

Twitter4j - cannot resolve method - setUsessl(boolean)

I'm using twitter4j 4.0.3 core I have this code: public final class TwitterUtil { private RequestToken requestToken = null; private TwitterFactory twitterFactory = null; private Twitter twitter; private TwitterUtil() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(ConstantValues.TWITTER_CONSUMER_KEY); configurationBuilder.setOAuthConsumerSecret(ConstantValues.TWITTER_CONSUMER_SECRET); configurationBuilder.setUseSSL(true); Configuration configuration =...

Set value for Spinner with custom Adapter in Android

I am developing a android application with spinner in a form. The spinner items and spinner values are different. I want to collect all the value from the from including spinner and set a rest api service to web back end. here is the response array. {"Status":true,"errorType":null,"countryList":[{"Code":"US","Name":"United States"},{"Code":"CA","Name":"Canada"},{"Code":"AU","Name":"Australia"},{"Code":"GB","Name":"United Kingdom"}]} I...

Finding embeded xpaths in a String

I have a string where I have the user should be able to specify xpaths that will be evaluated at runtime. I was thinking about having a the following way to specify it. String = "Hi my name is (/message/user) how can i help you with (/message/message) "; How can...

Join files using Apache Spark / Spark SQL

I am trying to use Apache Spark for comparing two different files based on some common field, and get the values from both files and write it as output file. I am using Spark SQL for joining both files (after storing the RDD as table). Is this the correct approach?...

Interpreting hex dump of java class file

I understand the structure of a java .class file, but when I want to interpret the raw hex data I get a bit lost. This is a hex dump of a class file, excluding the header and constant pool. I understand the header to be the magic number, minor_version and...

Android String if-statement

I have a if-statement in the start of my app if (ready.equals("yes")){ ... } and later on my code I have ready="yes"; but the if statement is never called, why? The ready="yes"; is called from a background thread, is that why? public void DownloadFromUrl(final String fileName) { //this is the...

Keep HashMap with object data while app is idle - Android

I have a HashMap that contains data relevant to a specific Activity. The problem is that when the app is opened after being idle for some time, the HashMap is empty. I am fetching all the data in the main activity and storing the corresponding objects in a HashMap in...

Why i get can not resolve method error in class android?

I use this tutorial: JSON and part of code to this: protected String doInBackground(String... urls) { TextView lbl=(TextView) findViewById(; person = new Person(); person.setName(lbl.getText().toString()); //person.setCountry("1853"); //person.setTwitter("1892"); return POST(urls[0],person); } but in the this line: person.setName(lbl.getText().toString()); i get this error: Can not resolve method. How can i solve that?what happen? my...

Java Scanner not reading newLine after wrong input in datatype verification while loop

I've looked at similar questions and tried to follow the answers that solved the issues that others have had but putting the or sc.nextLine() after the while loop causes it to go into an infinite loop. The problem is if a user enters incorrect input (nothing or a number)...

Android custom calendar view disable specific dates

i'm new to android developing and started to develop an booking app. There is a calendar view and i want to disable booked dates in that calendar. I found out that disabling feature is not there in android default calendar. so could you please help me to find a good...

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]

This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers I'm a beginner in android developing and I'm trying to build a simple app but I'm getting this error in the emulator.(Unfortunately,(App) has unexpectedly stopped). LogCat package...

Android set clickable text to go one fragment to another fragment

I need to do something like this. Suppose I have 2 fragments A and B.There is a text which can be clickable in fragment A and when user click this text , he can go to fragment B. This example helped me to do it but I think it does...

how to call Java method which returns any List from R Language? [on hold]

How to call java method which returns list from R Language.

Can I install 2 or more Android SDK when using Eclipse

I am new to android developments. I am setting up my android development environment using Eclipse. I have a test smart phone with Android version 4.2.2. The automatic installation installed the latest Android SDK version, which is 5.1.1. My questions are: 1. Do I have to install the SDK version...

How to set speaker phone off when the app is killed by the “Recent App drawer”

I implemented an app which has a button speaker, which is manually set "on" by myAudioManager.setSpeakerphoneOn(true) and "off" vice-versa. But the bug is when you close the application while the speaker is on, it forgets the speaker was on. The next time, the speaker remains on and the call is...

Dagger 2 Custom Scope for each Fragment

I'm a little confused about how to best use the custom scoping in Dagger 2. I've looked at a couple different articles which seem to suggest two different ways of doing it: MVP Presenters that Survive Configuration Changes Part-2 (Github repo): Uses unique custom scopes for each fragment, e.g. @Hello1Scope...

Android programming, draw a rectangle with specific coordinates

I am new to android programming. I am trying to draw a rectangle as in the image below. I have no idea how to do it with Rect(int left, int top, int right, int bottom). Can someone help me with this thanks. ...

How to call MySQL view in Struts2 or Hibernate

I have a view in MySQL database CREATE VIEW CustInfo AS SELECT a.custName, a.custMobile, b.profession, b.companyName, b.annualIncome FROM customer a INNER JOIN cust_proffessional_info b ON a.cust_id=b.cust_id Is there any way that i can call this view using Struts2 or in Hibernate. I have tried to search it but could not...

How to resolve Out of Memory Error on Bitmap in Android?

I want to set an image in image view,I am retrieving the image path in my first activity and I am passing it via intent as a String to second activity.In the second activity I set the path to an image view,It is working properly , and I need to...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- avoid '???' --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"/> </bean> if i create other subfolders under jsp , for instance /WEB-INF/jsp/reports , /WEB-INF/jsp/insertions how should i configure now the viewResolver to can resolve these new sub folders??...

Is there any way to use a pre-existing database from Xamarin without copying it from Assets?

I have a rather large SQLite database (~20 mb) I need to access from my Android Xamarin-Forms app. Everything online I've read says you can read the database by copying it to the filesystem first. For example, this question. However, won't that mean the large database is duplicated, wasting users'...

Mysterious claim of a missing { in eclipse

I have a case of a mysterious missing curly brace that I don't see any use for. Eclipse says, "Syntax error on token ";", { expected after this token". Either I am missing something very silly or there is something new I have to learn about Java. This is the...

Getting particular view from expandable listview

In my list view I have an textview in expandable group and I want to open the dialog when textview is clicked to fill the information through edittext and update textview. Problem: how could I get the groupview textview item in my fragment oncreateview() method....

Java dice roll with unexpected random number

I've written a simple Java program to display the results of 20 dice rolls on the console. The results I'm getting are listed below: 3 1 java.util.[email protected] 1 5 4 1 [email protected] 1 [email protected] [email protected] 1 6 [email protected] 1 [email protected] [email protected] 1 2 3 3 When I ran it for...

Floating Action Button in Xamarin.Forms

I had completed my App's home page in Xamarin.Forms Portable. Now i want to add a Flotation Action Button In my Android Project ! Is there any way to add FAB for Android in my existing home page, which was coded in Xamarin.Forms Portable. OR I want to create a...

Get network interfaces on remote machine

I know in java we can do NetworkInterface.getNetworkInterfaces() to get all available network interfaces on local machine. Can we do similar thing where I can pass host name to get the NICs(with IPs) which are up and running?

Android Implicit Intent for Viewing a Video File

In my Android app, I have a button that when clicked, launches the external application of my choice to play a video (I gather that this is called an "implicit intent"). Here is the relevant Java code from my onCreate method. Button button = (Button) findViewById(; button.setOnClickListener ( new Button.OnClickListener()...

how does android ImageView resize my image?

I have some 100*100 icons and I cannot find better resolution icons so I put them inside drawable folder. The width and height of the image view are set to wrap_content. When the image is shown on a xhdpi screen will the image be scaled to 200*200 automatically? or should...