1

I'm developing an app that can login, download, upload and show list file from Google Drive.

I've found Java code from Google Drive SDK but it run quite slow and isn't work.

I'm reading solution but don't know where to change that scope

My mainActivity:

        // google
        static final int REQUEST_ACCOUNT_PICKER = 1;
        static final int REQUEST_AUTHORIZATION = 2;
        static final int CAPTURE_IMAGE = 3;
        private GoogleAccountCredential credential;
        private static Uri fileUri;
        private static Drive service;

        public void onLoginGoogle(View v) {
                credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
                startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
        }

        public void onUploadGoogle(View v) {
                Thread t = new Thread(new Runnable() {
                        @Override
                        public void run() {
                                try {
                                        // File's binary content
                                        java.io.File fileContent = new java.io.File("/sdcard/a.jpg");
                                        FileContent mediaContent = new FileContent("image/jpeg", fileContent);

                                        // File's metadata.
                                        com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
                                        body.setTitle(fileContent.getName());
                                        body.setMimeType("image/jpeg");

                                        com.google.api.services.drive.model.File file = service.files().insert(body, mediaContent).execute();
                                        if (file != null) {
                                                showToast("Photo uploaded: " + file.getTitle());
                                                // startCameraIntent();
                                        }
                                } catch (UserRecoverableAuthIOException e) {
                                        startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                });
                t.start();
        }

        public void onDownloadGoogle(View v) {
                downloadFile();
        }

        private void downloadFile() {
                Thread thread = new Thread(new Runnable() {

                        @Override
                        public void run() {
                                try {
                                        com.google.api.services.drive.model.File file = service.files().get("0B-Iak7O9SfIpYk9zTjZvY2xreVU").execute();
                                        // FileList file = service.files().list().execute();
                                        // List<com.google.api.services.drive.model.File> fileList =
                                        // file.getItems();
                                        // com.google.api.services.drive.model.File fileItem =
                                        // fileList.get(0);
                                        // Log.d("FileID" , fileItem.getId());
                                        // Log.d("Count", "Retreived file list");
                                        if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
                                                HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
                                                InputStream inputStream = resp.getContent();
                                                // writeToFile(inputStream);
                                        }
                                } catch (IOException e) {
                                        Log.e("WriteToFile", e.toString());
                                        e.printStackTrace();
                                }
                        }
                });
                thread.start();
        }

        List<File> mGFile;

        public void onListGoogle(View v) {
                AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {

                        @Override
                        protected String doInBackground(Void... arg0) {
                                // TODO Auto-generated method stub
                                try {
                                        mGFile = retrieveAllFiles();
                                        int i = 0;
                                } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                                return null;
                        }

                        protected void onPostExecute(String result) {
                                Log.d("Dolphin get glist", String.valueOf(mGFile.size()));
                        };
                };
                task.execute();
                Log.d("Dolphin counting", "aa");
        }

        private List<File> retrieveAllFiles() 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;
        }

        private Drive getDriveService(GoogleAccountCredential credential) {
                return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
        }

@Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

                switch (requestCode) {
                case REQUEST_ACCOUNT_PICKER:
                        if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
                                String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                                if (accountName != null) {
                                        credential.setSelectedAccountName(accountName);
                                        service = getDriveService(credential);
                                }
                        }
                        break;
                case REQUEST_AUTHORIZATION:
                        if (resultCode == Activity.RESULT_OK) {
                                // saveFileToDrive();
                                Toast.makeText(this, "Login complete", Toast.LENGTH_SHORT);
                        } else {
                                startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
                        }
                        break;
                }
        }

The logcat:

"Application name is not set. Call Builder#setApplicationName."

How to get list of files from a folder? It's awesome if have a working example

Community
  • 1
  • 1
Tai Dao
  • 3,407
  • 7
  • 31
  • 54

2 Answers2

6

It works for me:

private List<File> sendRequest(){
    List<File> result = new ArrayList<File>();

    try{
        Files.List request = service.files().list().setQ("trashed = false");

        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);

    }
    catch(IOException e1){
        e1.printStackTrace();
    }

    for(File file : result){
        Log.d(TAG, "file : " + file.getTitle());
    }
    return result;
}

If you want files from a specific folder, you can try this request:

Files.List request = service.files().list().setQ("'" + folderId + "' in parents and trashed = false");

As you said, it's pretty slow, but I don't know how to do better.

Brtle
  • 2,297
  • 1
  • 19
  • 26
  • Thanks for help. I'm using your code but same error. It said "Application name is not set. Call Builder#setApplicationName.". Maybe my config on console got something wrong. Do you config this SDK APP http://i1335.photobucket.com/albums/w672/dolphin19303/myerror_zps7cc39019.png ?? – Tai Dao Jul 19 '13 at 10:03
  • 1
    sorry for late reply. Just enable Drive API only then it worked. Thumb this comment up for whom has same problem – Tai Dao Jul 23 '13 at 06:58
  • up to which level does it works ? I mean , can it search for a folderId inside another folder ?... i.e. root/folderA/folderAA , using folderId = "folderAA", so Files.List request = service.files().list().setQ("'" + folderId + "' in parents and trashed = false"); –  Jan 04 '14 at 16:17
  • With your request, you will have all the files in `root/folderA/folderAA` but I don't think you will have the files of the subfolder. – Brtle Jan 04 '14 at 16:39
  • what does service variable defines. Please explain in detail. – Jay Vyas Oct 25 '16 at 12:19
1
var express = require('express')
  , request = require('request')
  , oauth = require('./oauth')
  , app = express();

// Setup middleware
app.use(express.static(__dirname));


// List out file that are in your Google Drive
app.get('/list', function(req, res) {
  // Check to see if user has an access_token first
    if (oauth.access_token) {

    // URL endpoint and params needed to make the API call
        var url = 'https://www.googleapis.com/drive/v2/files';
        var params = {
            access_token: oauth.access_token
        };

    // Send the API request
        request.get({url:url, qs:params}, function(err, resp, body) {
      // Handle any errors that may occur
      if (err) return console.error("Error occured: ", err);
            var list = JSON.parse(body);
      if (list.error) return console.error("Error returned from Google: ", list.error);

      // Generate output
            if (list.items && list.items.length > 0) {
                var file = ''
                  , iconLink = ''
                  , link = ''
                  , output = '<h1>Your Google Drive</h1><ul>';

                for(var i=0; i<list.items.length; i++) {
                    file = list.items[i].title;
                    iconLink = list.items[i].iconLink;
                    link = list.items[i].alternateLink;

                    output += '<li style="list-style-image:url('+iconLink+');"><a href="'+link+'" target="_blank">'+file+'</a></li>';
                }
                output += '</ul>';

        //Send output as response
        res.writeHead(200, {'Content-Type': 'text/html'});
                res.end(output);

            } else { // Alternate output if no files exist on Drive
                console.log('Could not retrieve any items.');

        res.writeHead(200, {'Content-Type': 'text/html'});
                res.end('<p>Your drive appears to be empty.</p>')
            }
    });
  // If no access_token was found, start the OAuth flow
    } else {
        console.log("Could not determine if user was authed. Redirecting to /");
        res.redirect('/');
    }
});

// Handle OAuth Routes
app.get('/login', oauth.login);
app.get('/callback', oauth.callback);

app.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);

from runnable

MikroDel
  • 6,705
  • 7
  • 39
  • 74