BijoyJoseph Ответов: 0

Как получить метаданные файла в Google drive api в android?


Я довольно новичок в программировании Android, и моя задача-интегрировать Google Drive Api в Android. До сих пор я дошел до того, что могу видеть файлы и выбирать их, но я хотел бы также загрузить их. Часть загрузки не работает.

Мне нужно получить метаданные файла, чтобы иметь возможность загрузить файл, но я не могу его получить, и AsyncTask выдает исключение нулевого указателя. Что я здесь делаю не так?

Что я уже пробовал:

<blockquote class="quote"><div class="op">Quote:</div>public class DriveActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;
    private static final  int REQUEST_CODE_OPENER = 1;
    private static final int REQUEST_CODE_SELECT = 9;
    private static final int START_DOWNLOAD=7;
    private static final String TAG = "Google Drive Activity";
    private boolean fileOperation = false;
    private Metadata metadata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_drive);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestScopes(Drive.SCOPE_FILE, Drive.SCOPE_APPFOLDER)
                .build();

        if (mGoogleApiClient == null) {
            // ATTENTION: This "addApi(AppIndex.API)"was auto-generated to implement the App Indexing API.
            // See https://g.co/AppIndexing/AndroidStudio for more information.
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Drive.API)
                    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                    .enableAutoManage(this, this)
                    .addScope(Drive.SCOPE_FILE)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(AppIndex.API).build();
        }

        //mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL);
    }

    public void signIn(View view){
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, 56);
    }

    private void initializeGoogleDrive() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Toast.makeText(this, "Connected", Toast.LENGTH_LONG).show();
        Log.e("onConnected", "***************");
    }

    @Override
    public void onConnectionSuspended(int i) {  }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.e("onConnectionFailed", "***************" + connectionResult.getErrorCode());
        Log.e("onConnectionFailed", "***************" + connectionResult.toString());
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(this, 3);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        }
    }

    private void handleSignInResult(GoogleSignInResult result) {
        Log.e("handleSignInResult", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            GoogleSignInAccount acct = result.getSignInAccount();
            mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL);
            OpenFileFromGoogleDrive();
        } else {
            // Signed out, show unauthenticated UI.
        }
    }

    public void OpenFileFromGoogleDrive(){

        IntentSender intentSender = Drive.DriveApi
                .newOpenFileActivityBuilder()
                .build(mGoogleApiClient);
        try {
            startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
        } catch (IntentSender.SendIntentException e) {

            Log.w(TAG, "Unable to send intent", e);
        }
    }

    //Download file code begins...................

    private void DownloadFile(final DriveId driveId) {
        DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, driveId);
        file.getMetadata(mGoogleApiClient)
                .setResultCallback(metadataRetrievedCallback);
    }

    private ResultCallback<DriveResource.MetadataResult> metadataRetrievedCallback = new ResultCallback<DriveResource.MetadataResult>() {
        @Override
        public void onResult(final DriveResource.MetadataResult result) {
            Log.e("Getting Metadata", "metadata");
            if (!result.getStatus().isSuccess()) {
                return;
            }
            metadata = result.getMetadata();
            new AsyncTask<Void, Void, Void>(){
                @Override
                protected Void doInBackground(Void... voids) {
                    File localFile = new File(Environment.getExternalStorageDirectory(), metadata.getOriginalFilename());

                    if(!localFile.exists()){

                        try {
                            localFile.createNewFile();
                        }catch (Exception e){}
                    }

                    DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, metadata.getDriveId());
                    DriveApi.DriveContentsResult driveContentsResult = file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).await();
                    DriveContents driveContents = driveContentsResult.getDriveContents();
                    InputStream inputstream = driveContents.getInputStream();

                    try {
                        FileOutputStream fileOutput = new FileOutputStream(localFile);

                        byte[] buffer = new byte[1024];
                        int bufferLength = 0;
                        while ((bufferLength = inputstream.read(buffer)) > 0) {
                            fileOutput.write(buffer, 0, bufferLength);
                        }
                        fileOutput.close();
                        inputstream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return null;
                }
            }.execute();

        } //async
    };

    //code ends.............................

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("onActivityResult Sign", "********" + requestCode + "     " + resultCode);
            switch (requestCode) {
                case 3:
                    Log.e("onActivityResult", "********");
                    break;
                case 5:
                    Log.e("onActivityResult Drive", "********");
                    break;
                case 56:
                    Log.e("onActivityResult Sign", "********");
                    GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                    handleSignInResult(result);
                    break;
                case REQUEST_CODE_OPENER:
                    DriveId driveId = data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
                    Log.e("File ID: ", driveId.getResourceId() + " ");
                    DownloadFile(driveId);
                    break;
            }
    }

    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Drive Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.e
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();
       
        mGoogleApiClient.connect();
        AppIndex.AppIndexApi.start(mGoogleApiClient, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();
        
        AppIndex.AppIndexApi.end(mGoogleApiClient, getIndexApiAction());
        mGoogleApiClient.disconnect();
    }
}</blockquote>

Richard MacCutchan

Вам нужно использовать отладчик, чтобы определить, где происходит исключение NullPointerException, и исправить код, который его вызывает. Мы не можем догадаться, что происходит при запуске кода.

0 Ответов