7
7

More than 5 years have passed since last update.

Google Drive Android APIでデータを取得→データが1件も返ってこない

Last updated at Posted at 2014-10-17

Google Drive Android APIを使ってAndroidからドライブのデータを取得する

参考
Google APIs Client Library for JavaからGoogle Drive APIを使用する
Google Drive Android API
DriveFile|Android Developpers
Google Drive Android APIの日本語訳

手順

ざっくりと、以下の様な手順。詳しくは最初の参考を見てください。

  1. 設定
  2. 認証
  3. クエリーを返す

書いたやつ

以下の様な感じで、ドライブを認証→データを返すようにしました。

GoogleViewerActivity.java

public class GoogleViewerActivity extends Activity {

    private ListView mListView;
    private GoogleApiClient mGoogleApiClient;
    private DataBufferAdapter<Metadata> mResultsAdapter;
    private ArrayList<Metadata> mMetadataList = new ArrayList<Metadata>();
    private String mNextPageToken = null;
    private boolean mHasMore;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.google_viewer);

        mListView = (ListView) findViewById(R.id.GDlistView);
        mResultsAdapter = new ResultsAdapter(this);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(Bundle bundle) {
                        Log.v("GConnect", "success");
                        retrivePage();
                    }

                    @Override
                    public void onConnectionSuspended(int i) {
                        Log.v("GConnect", "suspend");
                    }
                })
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(ConnectionResult connectionResult) {
                        Log.v("GConnect", "failed_oncr");

                        if (connectionResult.hasResolution()) {
                            Log.v("GConnect", "has resolution");
                            try {
                                connectionResult.startResolutionForResult(GoogleViewerActivity.this, 34424);
                            } catch (IntentSender.SendIntentException e) {
                                // Unable to resolve, message user appropriately
                            }
                        } else {
                            GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), GoogleViewerActivity.this, 0).show();
                        }
                    }
                })
                .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    /**
     * Clears the result buffer to avoid memory leaks as soon
     * as the activity is no longer visible by the user.
     */
    @Override
    protected void onStop() {
        super.onStop();
        mResultsAdapter.clear();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch(requestCode){
            case 34424:
                if(resultCode == RESULT_OK){
                    mGoogleApiClient.connect();
                }
                break;
        }
    }

    /**
     * GoogleDriveからメタデータ一覧を取得する(1ページ目)
     */
    private void retrivePage() {
        Query query = new Query.Builder().addFilter(Filters.eq(SearchableField.MIME_TYPE, "text/plain")).build();
        Drive.DriveApi.query(mGoogleApiClient, query).setResultCallback(metadataBufferCallback);


    }

    /**
     * GoogleDriveからメタデータ一覧を取得する(1ページ目以降)
     */
    private void retrieveNextPage() {
        if (!mHasMore) {
            return;
        }
        Query query = new Query.Builder()
                .setPageToken(mNextPageToken)
                .build();
        Drive.DriveApi.query(mGoogleApiClient, query).setResultCallback(metadataBufferCallback);

    }

    /**
     * Toastを表示
     * @param message
     */
    private void showMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * Appends the retrieved results to the result buffer.
     */
    private final ResultCallback<DriveApi.MetadataBufferResult> metadataBufferCallback = new
            ResultCallback<DriveApi.MetadataBufferResult>() {
                @Override
                public void onResult(DriveApi.MetadataBufferResult result) {
                    if (!result.getStatus().isSuccess()) {
                        showMessage("Problem while retrieving files");
                        return;
                    }

                    mResultsAdapter.append(result.getMetadataBuffer());

                    mNextPageToken = result.getMetadataBuffer().getNextPageToken();
                    mHasMore = mNextPageToken != null;
                    mListView.setAdapter(mResultsAdapter);
                }
            };
}

しかし、1件もデータが返ってこない・・・!

最後の最後で罠がありました、というか、僕が完全にうっかりしていました。ドキュメントを見ると、、、

Note: The Android Drive API only works with the https://www.googleapis.com/auth/drive.file scope. This means that only files which a user has opened or created with your application can be matched by a query.

--- from Querying for Files

日本語訳は↓。

Note: Android Drive APIが使えるのは、https://www.googleapis.com/auth/drive.file スコープだけです。つまり、ユーザーがそのアプリで開いた、または、作成したファイルだけが問い合わせの対象になるということです。

--- from ファイルのクエリ

つまりはそういうことです。ここ(http://qiita.com/kubotaku1119/items/9df79c568e100c0c7623 )にも書いてあるように、過去のドライブのファイル等を取得する際は、Google APIs Client Library for Javaを使わないといけないみたいです。ドキュメントをよく読もうという話でした。。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7