使用Files.List()API在Android上列出Google云端硬盘文件

时间:2012-08-21 08:49:29

标签: android google-drive-api

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

  

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

2 个答案:

答案 0 :(得分:0)

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

另外,不要忘记添加以下权限:

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

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

答案 1 :(得分:0)

如果您想从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");
                }
            });
        }