I am quite new to Android programming and my task is to integrate Google Drive Api in Android. So far I reached to the point wherein I am able to see the file and select them but I would Like to download them as well. The download part is not working.
I need to get the file metadata to be able to download the file but I am not able to get it and the AsyncTask gives a Null Pointer Exception. What am I doing wrong here?
What I have tried:
<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) {
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();
}
}
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 {
}
}
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);
}
}
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) {
e.printStackTrace();
}
return null;
}
}.execute();
}
};
@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")
.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>