【问题标题】:Listing Google Drive File on Android using Files.List() API使用 Files.List() API 在 Android 上列出 Google Drive 文件
【发布时间】:2012-08-21 08:49:29
【问题描述】:

目前我需要制作一个可以列出所有 Google Drive 文件的应用程序。 我已经完成了帐户选择和 oauth 过程,并且已经获得了令牌。但是当我尝试使用 API 调用列出我在 Google Drive 上的所有文件时(通过使用 drive.files.list)我没有得到任何结果,应该保存所有文件的文件数组列表仍然是空的。
我也有错误:

java.net.unknownHostException www.googleapis.com 无法解析


这是我的代码:

SharedPreferences settings = getSharedPreferences(PREF, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("accountName", got.name);
    editor.commit();
    account=got;
    amf=accMgr.getAuthToken(account, authTokenType, true,
                new AccountManagerCallback<Bundle>(){
                    public void run(AccountManagerFuture<Bundle> arg0) {
                        try {
                            Bundle result;
                            Intent i;
                            String token;
                            Drive a;
                            result = arg0.getResult();
                            if (result.containsKey(accMgr.KEY_INTENT)) {
                                i = (Intent)result.get(accMgr.KEY_INTENT);
                                if (i.toString().contains("GrantCredentialsPermissionActivity")) {
                                    // Will have to wait for the user to accept
                                    // the request therefore this will have to
                                    // run in a foreground application
                                    cbt.startActivity(i);
                                } else {
                                    cbt.startActivity(i);
                                }

                            }
                            else if (result.containsKey(accMgr.KEY_AUTHTOKEN)) {
                                accessProtectedResource.setAccessToken(result
                                        .getString(accMgr.KEY_AUTHTOKEN));
                                   buildService(result
                                        .getString(accMgr.KEY_AUTHTOKEN),API_KEY);
                            /*else {
                                token = (String)result.get(AccountManager.KEY_AUTHTOKEN);*/

                                /*
                                 * work with token
                                 */

                                // Remember to invalidate the token if the web service rejects it
                                // if(response.isTokenInvalid()){
                                //    accMgr.invalidateAuthToken(authTokenType, token);
                                // }

                            }
                        } catch (OperationCanceledException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (AuthenticatorException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                }, handler);

}

private void buildService(final String authToken, final String ApiKey) {
    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(ApiKey);
            driveRequest.setOauthToken(authToken);
        }
    });
    System.out.println(authToken);
    service= b.build();
    List<File> a=new ArrayList<File>();
    try {
        a = retrieveDriveFile(service);
        System.out.println(a.size());
        File c=a.get(0);
        TextView ad=(TextView) findViewById(R.id.test);
        ad.setText(c.getOriginalFilename());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


public List<File> retrieveDriveFile(Drive service) 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 ssoccurred: " + e);
        request.setPageToken(null);
      }
    } while (request.getPageToken() != null &&
             request.getPageToken().length() > 0);

    return result;
  }

【问题讨论】:

    标签: android google-drive-api


    【解决方案1】:

    如果您的设备上没有可用的互联网连接,通常会发生这种情况。

    另外别忘了添加以下权限:

    <uses-permission android:name="android.permission.INTERNET" />
    

    如果您使用代理,也可能发生这种情况。如果是这种情况,请查看this question

    【讨论】:

    • 谢谢你:D 你的解决方案对我的应用程序来说就像奇迹一样。我只是在我的应用上添加了互联网权限。
    【解决方案2】:

    如果您想从 Goolge Drive 获取所有文件。假设您已经完成了帐户选择过程并创建了 Drive (Drive mService) 等。 现在在按钮点击事件下调用这个函数

     ButtonClickEvent
      {
         GetDriveData();
      }
            // FUNCTION TO RETRIEVE GOOGLE DRIVE DATA
     private void GetDriveData() 
        {
           private List<File>   mResultList;                
          Thread t = new Thread(new Runnable() 
        {
            @Override
            public void run() 
            {
                  mResultList = new ArrayList<File>();
                com.google.api.services.drive.Drive.Files f1 = mService.files();
                com.google.api.services.drive.Drive.Files.List request = null;
    
                do 
                {
                    try 
                    { 
                        request = f1.list();
                        request.setQ("trashed=false");
                        com.google.api.services.drive.model.FileList fileList = request.execute();
                        mResultList.addAll(fileList.getItems());
    
                    }
                    catch (UserRecoverableAuthIOException e)
                    {
                        startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                    } 
                    catch (IOException e)
                    {
                        e.printStackTrace();
                        if (request != null)
                        {
                            request.setPageToken(null);
                        }
                    }
                } while (request.getPageToken() !=null && request.getPageToken().length() > 0);
    
                populateListView();//Calling to Populate Data to the List
            }
    
        });
        t.start();
    }
    
     //Populating Retrieved data to List
     private void populateListView() 
        {
            runOnUiThread(new Runnable() 
                {
                    @Override
                    public void run() 
                    {
    
                        mFileArray = new String[mResultList.size()];
                        int i = 0;
                        for(File tmp : mResultList)
                        {
                            //System.out.println("FILE DATA "+tmp.getId()+"."+tmp.getFileSize()+".."+tmp.getFileExtension()+",,"+tmp.getMimeType()+"/"+tmp.getTitle());
                            mFileArray[i] = tmp.getTitle();
                        i++;
                        }
    
                        mAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, mFileArray);
                    mListView.setAdapter(mAdapter);
                        button2.setText("yes");
                    }
                });
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      相关资源
      最近更新 更多