Download Image from google drive Android API? - android

I successfully integrated google drive in my android app. But could not download selected image file.
Here is my code. There is a problem Result call back method is never execute. Kindly help me. And also I used data.getData() method in onActivity result this method only return null. How I can find URI of image?
package com.example.syedfurqan.dropboxintegration;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.dropbox.chooser.android.DbxChooser;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.DriveResource;
import com.google.android.gms.drive.Metadata;
import com.google.android.gms.drive.OpenFileActivityBuilder;
import java.io.InputStream;
public class BaseDemoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "BaseDriveActivity";
protected static final int REQUEST_CODE_RESOLUTION = 1;
private static final int REQ_CODE_OPEN = 2;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_base_demo);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
switch (requestCode) {
case REQ_CODE_OPEN:
if (resultCode == RESULT_OK) {
DriveId mFileId = (DriveId) data
.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
DriveFile selectedFile = mFileId.asDriveFile();
selectedFile.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(idCallback);
} else {
finish();
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
//Picker
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
// Launch user interface and allow user to select file
try {
IntentSender i = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"image/png", "image/jpeg"})
.build(mGoogleApiClient);
startIntentSenderForResult(i, REQ_CODE_OPEN, null, 0, 0, 0);
} catch (Exception e) {
}
}
final private ResultCallback<DriveApi.DriveContentsResult> idCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
// Handle an error
}
DriveContents driveContents = result.getDriveContents();
InputStream is = driveContents.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
Values.setBitmap(bitmap);
}
};
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
/**
* Shows a toast message.
*/
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
/**
* Getter for the {#code GoogleApiClient}.
*/
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
}

I just used Android Google Drive default API classes for doing my task. And here is code:
//BaseDemoActivity
package com.example.syedfurqan.dropboxintegration;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
public abstract class BaseDemoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "BaseDriveActivity";
protected static final int REQUEST_CODE_RESOLUTION = 1;
/**
* Google API client.
*/
private GoogleApiClient mGoogleApiClient;
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
/**
* Handles resolution callbacks.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
/**
* Called when {#code mGoogleApiClient} is connected.
*/
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
}
/**
* Called when {#code mGoogleApiClient} is disconnected.
*/
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
/**
* Called when {#code mGoogleApiClient} is trying to connect but failed.
* Handle {#code result.getResolution()} if there is a resolution is
* available.
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
/**
* Shows a toast message.
*/
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
/**
* Getter for the {#code GoogleApiClient}.
*/
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
}
//Retrieve Content
package com.example.syedfurqan.dropboxintegration;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFile.DownloadProgressListener;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.OpenFileActivityBuilder;
import java.io.InputStream;
/**
* An activity to illustrate how to open contents and listen
* the download progress if the file is not already sync'ed.
*/
public class RetreiveContent extends BaseDemoActivity {
private static final String TAG = "RetrieveFileWithProgressDialogActivity";
/**
* Request code to handle the result from file opening activity.
*/
private static final int REQUEST_CODE_OPENER = 1;
/**
* Progress bar to show the current download progress of the file.
*/
private ProgressBar mProgressBar;
/**
* File that is selected with the open file activity.
*/
private DriveId mSelectedFileDriveId;
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_progress);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mProgressBar.setMax(100);
}
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// If there is a selected file, open its contents.
if (mSelectedFileDriveId != null) {
open();
return;
}
// Let the user pick an mp4 or a jpeg file if there are
// no files selected by the user.
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"video/mp4", "image/png", "image/jpeg"})
.build(getGoogleApiClient());
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (SendIntentException e) {
// Log.w(TAG, "Unable to send intent", e);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_OPENER && resultCode == RESULT_OK) {
mSelectedFileDriveId = (DriveId) data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
// open();
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
private void open() {
// Reset progress dialog back to zero as we're
// initiating an opening request.
mProgressBar.setProgress(0);
DownloadProgressListener listener = new DownloadProgressListener() {
#Override
public void onProgress(long bytesDownloaded, long bytesExpected) {
// Update progress dialog with the latest progress.
int progress = (int) (bytesDownloaded * 100 / bytesExpected);
Log.d(TAG, String.format("Loading progress: %d percent", progress));
mProgressBar.setProgress(progress);
}
};
Drive.DriveApi.getFile(getGoogleApiClient(), mSelectedFileDriveId)
.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, listener)
.setResultCallback(driveContentsCallback);
mSelectedFileDriveId = null;
}
private ResultCallback<DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while opening the file contents");
return;
}
DriveContents driveContents = result.getDriveContents();
InputStream is = driveContents.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
Values.setBitmap(bitmap);
//showMessage("File contents opened");
RetreiveContent.this.finish();
}
};
}

Related

How to put the Information get from Google Place API and store to Firebase?

I'm follow the tutorial and implement the google place api to my file.
But I want to change it save to Firebase. Maybe save to a table "Location"
Anyone can guide me how to save it to firebase. The code I refer is from here:https://github.com/delaroy/AndroidLocationGeofencing
Thanks in advance and sorry for if there was lack of information Ii will added again.
Screenshot 1
Screenshot 2
package com.example.edward.neweventmanagementsystem;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.edward.neweventmanagementsystem.provider.PlaceContract;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import static android.widget.Toast.LENGTH_SHORT;
public class ManageLocation extends AppCompatActivity implements
ConnectionCallbacks,
OnConnectionFailedListener {
// Constants
public static final String TAG = ManageLocation.class.getSimpleName();
private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111;
private static final int PLACE_PICKER_REQUEST = 1;
// Member variables
private PlaceListAdapter mAdapter;
private RecyclerView mRecyclerView;
private boolean mIsEnabled;
private GoogleApiClient mClient;
private Geofencing mGeofencing;
private DatabaseReference mDatabaseReference;
Context mContext;
PlaceBuffer mPlaces;
/**
* Called when the activity is starting
*
* #param savedInstanceState The Bundle that contains the data supplied in onSaveInstanceState
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_location);
// Set up the recycler view
mRecyclerView = (RecyclerView) findViewById(R.id.places_list_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new PlaceListAdapter(this, null);
mRecyclerView.setAdapter(mAdapter);
// Switch onOffSwitch = (Switch) findViewById(R.id.enable_switch);
// mIsEnabled = getPreferences(MODE_PRIVATE).getBoolean(getString(R.string.setting_enabled), false);
// onOffSwitch.setChecked(mIsEnabled);
// onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// #Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
// editor.putBoolean(getString(R.string.setting_enabled), isChecked);
// mIsEnabled = isChecked;
// editor.commit();
// if (isChecked) mGeofencing.registerAllGeofences();
// else mGeofencing.unRegisterAllGeofences();
// }
//
// });
mClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, this)
.build();
mGeofencing = new Geofencing(this, mClient);
}
/***
* Called when the Google API Client is successfully connected
*
* #param connectionHint Bundle of data provided to clients by Google Play services
*/
#Override
public void onConnected(#Nullable Bundle connectionHint) {
refreshPlacesData();
Log.i(TAG, "API Client Connection Successful!");
}
/***
* Called when the Google API Client is suspended
*
* #param cause cause The reason for the disconnection. Defined by constants CAUSE_*.
*/
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "API Client Connection Suspended!");
}
/***
* Called when the Google API Client failed to connect to Google Play Services
*
* #param result A ConnectionResult that can be used for resolving the error
*/
#Override
public void onConnectionFailed(#NonNull ConnectionResult result) {
Log.e(TAG, "API Client Connection Failed!");
}
public void refreshPlacesData() {
Uri uri = PlaceContract.PlaceEntry.CONTENT_URI;
Cursor data = getContentResolver().query(
uri,
null,
null,
null,
null);
if (data == null || data.getCount() == 0) return;
List<String> guids = new ArrayList<String>();
while (data.moveToNext()) {
guids.add(data.getString(data.getColumnIndex(PlaceContract.PlaceEntry.COLUMN_PLACE_ID)));
}
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mClient,
guids.toArray(new String[guids.size()]));
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(#NonNull PlaceBuffer places) {
mAdapter.swapPlaces(places);
mGeofencing.updateGeofencesList(places);
if (mIsEnabled) mGeofencing.registerAllGeofences();
}
});
}
public void onAddPlaceButtonClicked(View view) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, getString(R.string.need_location_permission_message), Toast.LENGTH_LONG).show();
return;
}
try {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Intent i = builder.build(this);
startActivityForResult(i, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage()));
} catch (GooglePlayServicesNotAvailableException e) {
Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage()));
} catch (Exception e) {
Log.e(TAG, String.format("PlacePicker Exception: %s", e.getMessage()));
}
}
/***
* Called when the Place Picker Activity returns back with a selected place (or after canceling)
*
* #param requestCode The request code passed when calling startActivityForResult
* #param resultCode The result code specified by the second activity
* #param data The Intent that carries the result data.
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) {
final Place place = PlacePicker.getPlace(this, data);
if (place == null) {
Log.i(TAG, "No place selected");
return;
}
final String placeID = place.getId();
// Insert a new place into DB
// ContentValues contentValues = new ContentValues();
// contentValues.put(PlaceContract.PlaceEntry.COLUMN_PLACE_ID, placeID);
// getContentResolver().insert(PlaceContract.PlaceEntry.CONTENT_URI, contentValues);
//Place the data into Firebase
// Get live data information
refreshPlacesData();
}
}
public void onRingerPermissionsClicked(View view) {
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
public void onLocationPermissionClicked(View view) {
ActivityCompat.requestPermissions(ManageLocation.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_FINE_LOCATION);
}
}
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) {
final Place place = PlacePicker.getPlace(this, data);
if (place == null) {
Log.i(TAG, "No place selected");
return;
}
final String placeID = place.getId();
//Place the data into Firebase
insertPlcaeIdinDb(placeID);
// Get live data information
refreshPlacesData();
}
}
private void insertPlcaeIdinDb(String placeID)
{
mDatabase.child("yourBranchNameinDb").setValue(placeID );
}
To understand what is
FirebaseDatabase.getInstance().getReference()
you can follow Firebase for android official documentation from there

Reading data inserted into Google Fit API through HistoryAPI

I'm developing Google Fit API application and last 2 days I've been trying to store and retrieve data belongs to the BPM data type in different android applications. Meanwhile retrieving it returns zero points, although meanwhile inserting framework reports that everyting is inserted. I created OAuth keys for both applications, each of them has a subscription to this data type. Also I use enableServerQueries() for retrieval.
Datasource is being created as
daataSource=new DataSource.Builder().setName("measurementsSource").setDataType(DataType.TYPE_HEART_RATE_BPM).
setAppPackageName(getApplicationContext())
.setType(TYPE_RAW).build();
Does anyone has any ideas how to fetch data in a proper way?
Upd. According to the advice, I've added full code to add 1 point of custom DataType which I'd like to use. I've tried it number of times, but it still says 'ok' and no data could be available for getting back (for example, with API explorer).
package test.com.cloudydiscoverer;
import android.content.Intent;
import android.content.IntentSender;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataSource;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.request.DataTypeCreateRequest;
import com.google.android.gms.fitness.result.DataTypeResult;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static android.content.ContentValues.TAG;
import static com.google.android.gms.fitness.data.DataSource.TYPE_RAW;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_OAUTH = 1;
private static boolean authInProgress = false;
protected GoogleApiClient googleApiClient = null;
private GoogleApiClient.ConnectionCallbacks connectionCallbacks = null;
private void buildFitnessClient() {
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this);
builder.addApi(Fitness.RECORDING_API);
builder.addApi(Fitness.SENSORS_API);
builder.addApi(Fitness.BLE_API);
builder.addApi(Fitness.SESSIONS_API);
builder.addApi(Fitness.HISTORY_API);
builder.addApi(Fitness.CONFIG_API);
builder.addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE)); //TODO; verify scopes
builder.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE));
builder.addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE));
builder.addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE));
googleApiClient = builder.build();
}
public boolean flag=false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
connectionCallbacks = new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
/* try {
Thread.sleep(120000);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
DataTypeCreateRequest request = new DataTypeCreateRequest.Builder()
.setName("test.com.cloudydiscoverer.cloudy_s")
.addField("value", Field.FORMAT_INT32)
.build();
Fitness.ConfigApi.createCustomDataType(googleApiClient, request)
.setResultCallback(new ResultCallback<DataTypeResult>() {
#Override
public void onResult(#NonNull DataTypeResult dataTypeResult) {
if (!dataTypeResult.getStatus().isSuccess()) {
Log.i(TAG, "DataType creation/retrieval failed with result: " + dataTypeResult.getStatus().getStatusMessage());
} else {
Log.i(TAG, "created");
DataSource wSource=new DataSource.Builder().setName(dataTypeResult.getDataType().getName()+".source").setDataType(DataType.TYPE_HEART_RATE_BPM).
setType(TYPE_RAW).setAppPackageName("test.com.cloudydiscoverer").build();
/* DataSource wetSource = new DataSource.Builder()
.setDataType(dataTypeResult.getDataType())
.build();*/
DataPoint b = DataPoint.create(wSource);
b.setTimestamp(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
b.setFloatValues(5.0f);
//b.getValue(dataTypeResult.getDataType().getFields().get(0)).setInt(42);
DataSet dataSet = DataSet.create(wSource);
dataSet.add(b);
Fitness.HistoryApi.insertData(googleApiClient, dataSet).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Log.i(TAG, String.valueOf(status.isSuccess()));
}
}
);
}
}
});
}
#Override
public void onConnectionSuspended(int i) {
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Toast.makeText(MainActivity.this, "Network is unavailable. " +
"Connection will be restored automatically.", Toast.LENGTH_SHORT).show();
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(MainActivity.this, "Service has been disconnected. " +
"Connection will be restored automatically.", Toast.LENGTH_SHORT).show();
}
}
};
GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener = new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed with result: " + result.getErrorCode());
if (!result.hasResolution()) {
return;
}
if (!authInProgress) {
try {
Toast.makeText(MainActivity.this, "You need to authorize.", Toast.LENGTH_SHORT).show();
authInProgress = true;
result.startResolutionForResult(MainActivity.this, REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Toast.makeText(MainActivity.this, "Exception has been caught.", Toast.LENGTH_SHORT).show();
}
}
}
};
Log.i("1","1");
buildFitnessClient();
googleApiClient.registerConnectionCallbacks(connectionCallbacks);
googleApiClient.registerConnectionFailedListener(onConnectionFailedListener);
Log.i("2","2");
googleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OAUTH) {
authInProgress = false;
if (resultCode == RESULT_OK) {
if ((!googleApiClient.isConnected()) || (!googleApiClient.isConnecting()))
googleApiClient.connect();
} else {
Log.i(TAG, "Nothing could be done.");
}
}
}
}

how can I create an empty spreadsheeet using google drive api for android java

Hi i'm trying to create an empty spreadsheet using the drive api from my android app
i face no problem creating files with mimetype text/*
but using "application/vnd.google-apps.spreadsheet" i get an error.
here is my activity.
how can I achieve the result?
import android.app.Activity;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.MetadataChangeSet;
public class SpreadCreate extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
private static final int REQUEST_CODE_RESOLUTION = 1;
private GoogleApiClient mGoogleApiClient;
private void saveFileToDrive() {
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
return;
}
new Thread() {
#Override
public void run() {
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("MoneyManager")
//.setMimeType("application/vnd.google-apps.spreadsheet")
.setMimeType("text/csv")
.build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, null)
.setResultCallback(fileCallback);
}
}.start();
}
});
}
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
System.out.println("Errore " + result.toString());
finish();
}
System.out.println(result.getDriveFile().getDriveId());
finish();
}
};
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
//.addApiIfAvailable(Drive.API)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
//.setAccountName(accountname)
.build();
}
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
}
}
#Override
public void onConnected(Bundle connectionHint) {
saveFileToDrive();
}
#Override
public void onConnectionSuspended(int cause) {
}
}
Thanks

How to integrate Amazon Cognito with Google Plus for Android?

This is my first question here, so please be gentle. As part of my university's project, I need to develop an Android app that lets me upload files, and share files with other users. I am new to Android programming (I watched some Android Beginner videos and developed basic apps for practice) and first time using cloud computing as a developer. I am using Amazon Web Services.
I have got the code which lets me login using my google account and shows my Name, Email ID, and profile photo once signed in.
I want to integrate it with Amazon Cognito so that I can get the unique id which I can use to work on AWS further. How do I get that unique key for each user who signs in on the app?
I watched some tutorials but can't understand how to integrate Cognito code into my code.
Here is my code.
package com.unicloud.project;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.plus.Account;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.regions.Regions;
public class loginWithGooglePlus extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "loginWithGooglePlus";
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
private Button btnSignOut, btnRevokeAccess;
private ImageView imgProfilePic;
private TextView txtName, txtEmail;
private LinearLayout llProfileLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_with_google_plus);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
btnRevokeAccess.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this).addOnConnectionFailedListener(this)
.addApi(Plus.API, new Plus.PlusOptions.Builder().build()) // note the options
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Method to resolve any signin errors
*/
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
getProfileInformation();
// Update the UI after signin
updateUI(true);
}
/**
* Updating the UI, showing/hiding buttons and profile layout
*/
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
}
}
/**
* Fetching user's information name, email, profile pic
*/
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login_with_google_plus, menu);
return true;
}
/**
* Button on click listener
*/
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
signOutFromGplus();
break;
case R.id.btn_revoke_access:
// Revoke access button clicked
revokeGplusAccess();
break;
}
}
/**
* Sign-in into google
*/
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Sign-out from google
*/
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
/**
* Revoking access from google
*/
private void revokeGplusAccess() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status arg0) {
Log.e(TAG, "User access revoked!");
mGoogleApiClient.connect();
updateUI(false);
}
});
}
}
/**
* Background Async task to load user profile picture from url
*/
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
This link has the code for Android, but I am not sure where to add that code in the program. Should I create a new class? Please help me with that.
Have you looked at the CognitoSync sample available in GitHub? It should give you some ideas on how to integrate Cognito into your application.

Google Drive API doesn't keep user signed in after user chooses account

In one section of my android application, user can import CSV files into the application. To do so, users must allow the app to have access to their Google drive. I accomplish this by using the Google Drive API Sign in, and allow users to only be able to choose CSV files.When in debug mode, the below code works perfectly. However after release of the app the users are never logged in.
in debug mode:
https://www.youtube.com/watch?v=aFj_fn13x2c&feature=youtu.be
released version: https://www.youtube.com/watch?v=pq2POP43waM
Permissions:
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.GoogleApiActivity;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveClient;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.DriveResourceClient;
import com.google.android.gms.drive.Metadata;
import com.google.android.gms.drive.OpenFileActivityBuilder;
import com.google.android.gms.drive.OpenFileActivityOptions;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.SearchableField;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.android.gms.tasks.Tasks;
import com.google.gson.Gson;
import com.project.danielo.eventer.Custom_Classes.AddAndEditMethods;
import com.project.danielo.eventer.Custom_Classes.CSVExporter;
import com.project.danielo.eventer.Custom_Classes.CustomDateParser;
import com.project.danielo.eventer.Custom_Classes.CustomRegex;
import com.project.danielo.eventer.StaticVariables;
import com.project.danielo.eventer.adapter.CustomEventObject;
import com.project.danielo.eventer.dialog_fragments.NotificationSettings;
import com.project.danielo.eventer.notification_package.CustomNotification;
import com.project.danielo.eventer.sqllite.DBHandler;
import com.project.danielo.eventer.R;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import static android.app.Activity.RESULT_OK;
public class SettingsFragments extends Fragment {
public SettingsFragments(){
}
private View settingsView;
Button
btnImportEvents, btnDriveSettings;
ProgressBar progressBar;
GoogleApiClient apiClient;
private static final String TAG = "Google drive activity";
private static final int REQUEST_CODE_OPENER = 15;
private static final int REQUEST_CODE_SIGN_IN = 16;
private static final int REQUEST_CODE_OPEN_ITEM = 1;
private DriveId driveId;
private DriveClient driveClient;
private OpenFileActivityOptions openFileActivityOptions;
private DriveResourceClient resourceClient;
private TaskCompletionSource<DriveId> mOpenItemTaskSource;
private DriveContents driveContents;
private Metadata metadata;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
signIn();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
settingsView = inflater.inflate(R.layout.layout_for_settings_fragment, null, false);
btnImportEvents = (Button)settingsView.findViewById(R.id.btn_import_events);
btnDriveSettings = (Button)settingsView.findViewById(R.id.btn_google_drive_settings);
progressBar = (ProgressBar)settingsView.findViewById(R.id.settings_progress_bar);
/*Upon this button click, the app checks if user is logged
* before giving user access to Google Drive account
*/
btnImportEvents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isConnectedToTheInternet()) {
openPleaseConnectToInternet();
}else{
if(!isUserSignedInToGoogleDriveAccount()){
openSignInGoogleDriveAccountDialog();
}else{
openFileChooser();
}
}
}
});
/*Upon this button click, the app logs user of current Google Drive account
* and opens choose account dialog
*/
btnDriveSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isConnectedToTheInternet()) {
openPleaseConnectToInternet();
}else{
progressBar.setVisibility(View.VISIBLE);
/*
/user is signed in, so we must initialize sign in client and sign out to reopen Google Drive Account chooser
*/
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();
GoogleSignInClient signInClient = GoogleSignIn.getClient(getContext(),signInOptions);
signInClient.signOut();
signIn();
}
}
});
return settingsView;
}
/***********************START OF IMPORT EVENTS METHODS**************************/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
progressBar.setVisibility(View.INVISIBLE);
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode != RESULT_OK) {
// Sign-in may fail or be cancelled by the user. For this sample, sign-in is
// required and is fatal. For apps where sign-in is optional, handle
// appropriately
return;
}
Task<GoogleSignInAccount> getAccountTask =
GoogleSignIn.getSignedInAccountFromIntent(data);
if (getAccountTask.isSuccessful()) {
initializeDriveClient(getAccountTask.getResult());
}
break;
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK) {
driveId = (DriveId) data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
loadCurrentFile();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
//Google drive sign in
private void signIn(){
Set<Scope> requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
requiredScopes.add(Drive.SCOPE_APPFOLDER);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(getContext());
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
} else {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();
GoogleSignInClient signInClient = GoogleSignIn.getClient(getContext(), signInOptions);
startActivityForResult(signInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
}
//list files in drive
private void openFileChooser(){
progressBar.setVisibility(View.VISIBLE);
OpenFileActivityOptions openOptions =
new OpenFileActivityOptions.Builder()
.setSelectionFilter(Filters.eq(SearchableField.MIME_TYPE, "text/csv"))
// .setMimeType(mimeTypes)
.setActivityTitle("Choose a CSV file")
.build();
driveClient.newOpenFileActivityIntentSender(openOptions)
.addOnSuccessListener(new OnSuccessListener<IntentSender>() {
#Override
public void onSuccess(IntentSender intentSender) {
try {
startIntentSenderForResult(
intentSender,
REQUEST_CODE_OPENER,
/* fillInIntent= */ null,
/* flagsMask= */ 0,
/* flagsValues= */ 0,
/* extraFlags= */ 0,
null);
;
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent.", e);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Unable to create OpenFileActivityIntent.", e);
}
});
}
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
driveClient = Drive.getDriveClient(getContext(), signInAccount);
resourceClient = Drive.getDriveResourceClient(getContext(), signInAccount);
if(progressBar != null) {
progressBar.setVisibility(View.INVISIBLE);
}
}
/**
* Retrieves the currently selected Drive file's metadata and contents.
*/
private void loadCurrentFile() {
progressBar.setVisibility(View.VISIBLE);
Log.d(TAG, "Retrieving...");
final DriveFile file = driveId.asDriveFile();
// Retrieve and store the file metadata and contents.
resourceClient.getMetadata(file)
.continueWithTask(new Continuation<Metadata, Task<DriveContents>>() {
#Override
public Task<DriveContents> then(#NonNull Task<Metadata> task) {
if (task.isSuccessful()) {
metadata = task.getResult();
return resourceClient.openFile(file, DriveFile.MODE_READ_ONLY);
} else {
return Tasks.forException(task.getException());
}
}
}).addOnSuccessListener(new OnSuccessListener<DriveContents>() {
#Override
public void onSuccess(DriveContents contents) {
driveContents = contents;
refreshUiFromCurrentFile();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Unable to retrieve file metadata and contents.", e);
}
});
}
//converting inputstream to string
private void refreshUiFromCurrentFile() {
Log.d(TAG, "Refreshing...");
String contents = "";
try {
StringWriter writer = new StringWriter();
IOUtils.copy(driveContents.getInputStream(), writer);
contents = writer.toString();
} catch (IOException e) {
e.printStackTrace();
}
if(contents.trim().isEmpty()){
return;
}
}
private boolean isConnectedToTheInternet(){
ConnectivityManager cm =
(ConnectivityManager)getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isConnected = false;
try{
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}catch (SecurityException e){
e.printStackTrace();
}
return isConnected;
}
private boolean isUserSignedInToGoogleDriveAccount(){
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(getContext());
if(signInAccount == null){
return false;
}
return true;
}
private void openSignInGoogleDriveAccountDialog(){
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
alertDialog.setTitle("No google account selected");
alertDialog.setMessage("Please sign in to Google Drive Account by pressing Google Drive Settings button");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void openPleaseConnectToInternet(){
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
alertDialog.setTitle("!Internet Connection needed");
alertDialog.setMessage("Please Connect to the internet");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
Okay, i figured the problem. To use google drive API, one has to set OAuth 2.0 credentials. I set the credentials for the debug version of my application, so the API worked as needed. The problem occurred when I tried to use the same credentials for the release version. This is a problem because you need SHA-1 key to setup the O-Auth 2.0 credentials. The debug and release versions have different SHA-1 keys.

Categories

Resources