Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8908073
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T03:05:14+00:00 2026-06-15T03:05:14+00:00

This is my code to access Google Drive, taken largely from ArtOfWarfare in this

  • 0

This is my code to access Google Drive, taken largely from ArtOfWarfare in this post:

public class MainActivity extends Activity {
    class OnTokenAcquired implements AccountManagerCallback<Bundle> {
        boolean alreadyTriedAgain;
        public OnTokenAcquired() {
            // TODO Auto-generated constructor stub
        }
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == 3025) {
                switch (resultCode) {
                case RESULT_OK:
                    AccountManager am = AccountManager.get(getApplicationContext());
                    am.getAuthToken(am.getAccounts()[0],
                            "ouath2:" + DriveScopes.DRIVE,
                            new Bundle(),
                            true,
                            new OnTokenAcquired(),
                            null);
                    break;
                case RESULT_CANCELED:
                    // This probably means the user refused to log in. Explain to them why they need to log in.
                    break;
                default:
                    // This isn't expected... maybe just log whatever code was returned.
                    break;
                }
            } else {
                // Your application has other intents that it fires off besides the one for Drive's log in if it ever reaches this spot. Handle it here however you'd like.
            }
        }
        @Override
        public void run(AccountManagerFuture<Bundle> result) {
            try {
                final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                HttpTransport httpTransport = new NetHttpTransport();
                JacksonFactory jsonFactory = new JacksonFactory();
                Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
                b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
                    @Override
                    public void initialize(JsonHttpRequest request) throws IOException {
                        DriveRequest driveRequest = (DriveRequest) request;
                        driveRequest.setPrettyPrint(true);
                        driveRequest.setKey("my number here");
                        driveRequest.setOauthToken(token);
                    }
                });

                final Drive drive = b.build();

                final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
                body.setTitle("My Test File");
                body.setDescription("A Test File");
                body.setMimeType("text/plain");
                File newFile = new File("this");
                final FileContent mediaContent = new FileContent("text/plain", newFile);
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute();
                            alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found.
                        } catch (IOException e) {
                            if (!alreadyTriedAgain) {
                                alreadyTriedAgain = true;
                                AccountManager am = AccountManager.get(getApplicationContext());
                                am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest
                                am.getAuthToken(am.getAccounts()[0],
                                        "ouath2:" + DriveScopes.DRIVE,
                                        new Bundle(),
                                        true,
                                        new OnTokenAcquired(),
                                        null);
                            } else {
                                // Give up. Crash or log an error or whatever you want.
                            }
                        }
                    }
                }).start();
                Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
                if (launch != null) {
                    startActivityForResult(launch, 3025);
                    return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
                }
            } catch (OperationCanceledException e) {
                // Handle it...
            } catch (AuthenticatorException e) {
                // Handle it...
            } catch (IOException e) {
                // Handle it...
            }
        }

    }
    private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException {
        if (gFile.toURI() != null && gFile.toURI().toString().length() > 0 ) {
            if (jFolder == null) {
                jFolder = Environment.getExternalStorageDirectory();
                jFolder.mkdirs();
            }
            try {

                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(gFile.toURI());
                get.setHeader("Authorization", "Bearer " + token);
                org.apache.http.HttpResponse response = client.execute(get);

                InputStream inputStream = response.getEntity().getContent();
                jFolder.mkdirs();
                java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() + "/" + gFile.getName()); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't.
                FileOutputStream fileStream = new FileOutputStream(jFile);
                byte buffer[] = new byte[1024];
                int length;
                while ((length=inputStream.read(buffer))>0) {
                    fileStream.write(buffer, 0, length);
                }
                fileStream.close();
                inputStream.close();
                return jFile;
            } catch (IOException e) {        
                // Handle IOExceptions here...
                return null;
            }
        } else {
            // Handle the case where the file on Google Drive has no length here.
            return null;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getApplicationContext();
        AccountManager am = AccountManager.get(this);
        am.getAuthToken(am.getAccounts()[0],
                "ouath2:" + DriveScopes.DRIVE,
                new Bundle(),
                true,
                new OnTokenAcquired(),
                null);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

I get the following error when I launch the app (Android System also stops momentarily):

11-26 22:31:03.093: E/AndroidRuntime(4288): FATAL EXCEPTION: main
11-26 22:31:03.093: E/AndroidRuntime(4288): java.lang.RuntimeException: Unable to start activity ComponentInfo{android/android.accounts.GrantCredentialsPermissionActivity}: java.lang.NullPointerException
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2260)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.app.ActivityThread.access$600(ActivityThread.java:139)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.os.Looper.loop(Looper.java:156)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.app.ActivityThread.main(ActivityThread.java:5045)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at java.lang.reflect.Method.invokeNative(Native Method)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at java.lang.reflect.Method.invoke(Method.java:511)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at dalvik.system.NativeStart.main(Native Method)
11-26 22:31:03.093: E/AndroidRuntime(4288): Caused by: java.lang.NullPointerException
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.accounts.GrantCredentialsPermissionActivity.onCreate(GrantCredentialsPermissionActivity.java:84)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.app.Activity.performCreate(Activity.java:4543)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
11-26 22:31:03.093: E/AndroidRuntime(4288):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
11-26 22:31:03.093: E/AndroidRuntime(4288):     ... 11 more

In addition, my phone shows a strange notification: "Permission Requested for account Weather". Anyone have any idea what’s causing this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T03:05:15+00:00Added an answer on June 15, 2026 at 3:05 am

    Try replacing this:

    am.getAccounts()[0],
    

    with this:

    am.getAccountsByType("com.google")[0],
    

    My code in the other topic was over simplified to assume that the first account it found would be a Google Account (and so have a Google Drive). The code we actually used in the app checked to make sure it was a Google Account (and then performed further checks to make sure it was a company account, which is why I simplified the code to what I shared.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I try to access information from Twitter and I followed this link: http://code.google.com/p/sociallib/wiki/SocialLibGuide I
I m trying to access a rdf file from the google nexus.....(now this code
I created a class under 'src' dir. I'm using this code to access the
How do you think about data access code like this: public void AddCusotmer(Cusotmer customer)
Right now I'm using this code to upload files to Google Drive: https://stackoverflow.com/a/11657773/1715263 It
How long is the access code valid for when a google drive api based
I used to access my Google Bookmarks, server side with this PHP code: $curlObj
I'm trying to understand if it's possible to access a Google Drive from a
I found this via google: http://www.mvps.org/access/api/api0008.htm '******************** Code Start ************************** ' This code was
i have this code: $('.access a').toggle(function() { $('link').attr('href', 'styles/accessstyles.css'); $('body').css('font-size', '16px'); }, function() {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.