Trying to put all files inside folder but getting result.getDriveFolder().getDriveId().getResourceId() always null. i searched and found some links and i tried to go with the steps mentioned in this linkenter link description here
Here's my code :-
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
public ArrayList songsList = new ArrayList();
private static final String TAG = "drive-quickstart";
private GoogleApiClient mGoogleApiClient;
public static ArrayList<File> listAllMusicFiles = new ArrayList<File>();
protected static final int REQUEST_CODE_RESOLUTION = 1;
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
private DriveId mFolderDriveId;
public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final File mainDir = new File(Environment.getExternalStorageDirectory()
.getPath());
loadSdcardfiles(mainDir);
}
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive(final File file) {
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
final DriveContents driveContents = result
.getDriveContents();
Log.i(TAG, "New contents created.");
OutputStream outputStream = result.getDriveContents()
.getOutputStream();
try {
#SuppressWarnings("resource")
FileInputStream fileInputStream = new FileInputStream(
file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
DriveFolder folder = mFolderDriveId.asDriveFolder();
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setTitle(file.getName()).setStarred(true)
.build();
// create a file on root folder
folder.createFile(mGoogleApiClient, metadataChangeSet,
driveContents).setResultCallback(fileCallback);
// Drive.DriveApi
// .getRootFolder(mGoogleApiClient)
// .createFile(mGoogleApiClient,
// metadataChangeSet, driveContents)
// .setResultCallback(fileCallback);
try {
} catch (Exception e) {
}
}
});
}
private void loadSdcardfiles(File aFile) {
if (aFile.isFile()) {
if (aFile.getAbsolutePath().endsWith(".mp3")) {
listAllMusicFiles.add(aFile);
}
} else if (aFile.isDirectory()) {
File[] listOfFiles = aFile.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
loadSdcardfiles(listOfFiles[i]);
}
}
} else {
}
}
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API).addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#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();
}
}
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
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);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(this, "API client connected" + listAllMusicFiles.get(0),
1000).show();
if (listAllMusicFiles.size() == 0) {
return;
} else {
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("Siddharth").build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFolder(mGoogleApiClient, changeSet)
.setResultCallback(callback);
}
}
#Override
public void onConnectionSuspended(int cause) {
Toast.makeText(this, "GoogleApiClient connection suspended", 1000)
.show();
}
final private ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;
}
mFolderDriveId = result.getDriveId();
for (int i = 0; i < listAllMusicFiles.size(); i++) {
saveFileToDrive(listAllMusicFiles.get(i));
}
}
};
final ResultCallback<DriveFolderResult> callback = new ResultCallback<DriveFolderResult>() {
#Override
public void onResult(final DriveFolderResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the folder");
return;
}
showMessage("Created a folder: "
+ result.getDriveFolder().getDriveId());
mFolderDriveId = result.getDriveFolder().getDriveId();
DriveFolder folder = Drive.DriveApi.getFolder(mGoogleApiClient,
result.getDriveFolder().getDriveId());
folder.addChangeSubscription(mGoogleApiClient);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file with content: "
+ result.getDriveFile().getDriveId());
}
};
public class MyDriveEventService extends DriveEventService {
#Override
public void onChange(ChangeEvent event) {
Log.d(TAG, event.toString());
Drive.DriveApi.fetchDriveId(mGoogleApiClient,
mFolderDriveId.getResourceId()).setResultCallback(
idCallback);
}
}
}
Can any one suggest me that how to do this, Thanks In advance
finally yes , it was there in my provided links...
here are the changes i made
#Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(this, "API client connected" + listAllMusicFiles.get(0),
1000).show();
if (listAllMusicFiles.size() == 0) {
return;
} else {
if (count == 0) {
count++;
mcreateFolder();
}
}
}
public void mcreateFolder() {
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle(
"Siddharth").build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFolder(mGoogleApiClient, changeSet)
.setResultCallback(callback);
}
final ResultCallback<DriveFolderResult> callback = new ResultCallback<DriveFolderResult>() {
#Override
public void onResult(final DriveFolderResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the folder");
return;
}
showMessage("Created a folder: "
+ result.getDriveFolder().getDriveId());
mFolderDriveId = result.getDriveFolder().getDriveId();
Drive.DriveApi.getFolder(mGoogleApiClient, mFolderDriveId)
.addChangeListener(mGoogleApiClient, mChgeLstnr);
mCnt = 0;
mPoker = new Handler();
mPoker.postDelayed(mPoke, mWait);
}
};
final private ChangeListener mChgeLstnr = new ChangeListener() {
#Override
public void onChange(ChangeEvent event) {
// showMessage("event: " + event + " resId: "
// + event.getDriveId().getResourceId());
}
};
private final Runnable mPoke = new Runnable() {
public void run() {
if (mPoker != null && mFolderDriveId != null
&& mFolderDriveId.getResourceId() == null
&& (mCnt++ < ENOUGH)) {
MetadataChangeSet meta = new MetadataChangeSet.Builder()
.build();
Drive.DriveApi
.getFolder(mGoogleApiClient, mFolderDriveId)
.updateMetadata(mGoogleApiClient, meta)
.setResultCallback(
new ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(
DriveResource.MetadataResult result) {
if (result.getStatus().isSuccess()
&& result.getMetadata()
.getDriveId()
.getResourceId() != null) {
showMessage("resId COOL "
+ result.getMetadata()
.getDriveId()
.getResourceId());
mPoker.removeCallbacksAndMessages(mPoke);
Drive.DriveApi.fetchDriveId(
mGoogleApiClient,
result.getMetadata()
.getDriveId()
.getResourceId())
.setResultCallback(
idCallback);
} else {
mPoker.postDelayed(mPoke,
mWait *= 2);
}
}
});
} else {
mPoker = null;
}
}
};
Alot many thanks to #seanpj for such a beautiful elaboration.
cannot get folderId that i just created on google drive
Unpredictable result of DriveId.getResourceId() in Google Drive Android API
I really appreciate your effort.
Related
First time I am using GoogleApiClient and want to upload all the text messages to google drive when the share button in the app is clicked. But the data is not uploading on the drive.
MainActivity :
public class MainActivity extends AppCompatActivity {
RecyclerView rv;
SmsAdapter adapter;
FloatingActionButton fab;
Cursor c;
ExportTask task;
ArrayList<CustomSms> smslistSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
smslistSearch = new ArrayList<>();
rv = (RecyclerView) findViewById(R.id.messages_view);
LinearLayoutManager llm = new LinearLayoutManager(MainActivity.this);
rv.setLayoutManager(llm);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i =new Intent(MainActivity.this,SendSms.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
final ArrayList<CustomSms> smslist, smsgrouplist;
smslist = new ArrayList<>();
smsgrouplist = new ArrayList<>();
//Fetch inobx sms message
c = getContentResolver().query(SmsApplication.INBOX_URI, null, null, null, null);
while (c.moveToNext()) {
String address = c.getString(c.getColumnIndexOrThrow("address"));
String date = c.getString(c.getColumnIndexOrThrow("date"));
String body = c.getString(c.getColumnIndexOrThrow("body"));
smslist.add(new CustomSms(address, date, body));
}
smslistSearch = smslist;
Map<String, CustomSms> map = new LinkedHashMap<>();
for (CustomSms ays : smslist) {
CustomSms existingValue = map.get(ays.address);
if(existingValue == null){
map.put(ays.address, ays);
}
}
smsgrouplist.clear();
smsgrouplist.addAll(map.values());
adapter = new SmsAdapter(MainActivity.this);
adapter.updateList(smsgrouplist);
rv.setAdapter(adapter);
rv.addOnItemTouchListener(
new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// TODO Handle item click
ArrayList<CustomSms> smsinsidegroup = new ArrayList<CustomSms>();
String n = smsgrouplist.get(position).address;
for (int i = 0; i < smslist.size(); i++) {
if(smslist.get(i).address.equals(n))
smsinsidegroup.add(smslist.get(i));
}
Intent i = new Intent(MainActivity.this, ReadAllSms.class);
i.putParcelableArrayListExtra("messages", smsinsidegroup);
startActivity(i);
}
})
);
}
catch (Exception e)
{
e.printStackTrace();
}
}
class ExportTask extends AsyncTask<Void, Integer, Uri> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Exporting to file ...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(0);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Uri doInBackground(Void... params) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
FileOutputStream fos = null;
try {
File f = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt");
fos = new FileOutputStream(f);
int count = c.getCount(), i = 0;
StringBuilder sb = new StringBuilder();
if (c.moveToFirst()) {
do {
sb.append(c.getString(c.getColumnIndex("address")))
.append("\n");
sb.append(c.getString(c.getColumnIndex("body")))
.append("\n");
sb.append("\n");
publishProgress(++i*100/count);
} while (!isCancelled() && c.moveToNext());
}
fos.write(sb.toString().getBytes());
return Uri.fromFile(f);
} catch (Exception e) {
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {}
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Uri result) {
super.onPostExecute(result);
pDialog.dismiss();
if (result == null) {
Toast.makeText(MainActivity.this, "Export task failed!",
Toast.LENGTH_LONG).show();
return;
}
Intent i = new Intent(MainActivity.this,UploadData.class);
startActivity(i);
}
}
#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_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
Intent i = new Intent(MainActivity.this,SearchActivity.class);
i.putParcelableArrayListExtra("search", smslistSearch);
startActivity(i);
return true;
}
if (id == R.id.action_share) {
/*Intent i = new Intent(MainActivity.this,UploadData.class);
startActivity(i);*/
task = new ExportTask();
task.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
if (task != null) {
task.cancel(false);
task.pDialog.dismiss();
}
super.onPause();
}
}
UploadData :
public class UploadData extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "upload_file";
private static final int REQUEST_CODE = 101;
private File textFile;
private GoogleApiClient googleApiClient;
public static String drive_id;
public static DriveId driveID;
FrameLayout rl;
TextView success;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_data);
rl = (FrameLayout) findViewById(R.id.frame);
success = (TextView) findViewById(R.id.success);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
View root = rl.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.colorBackOrig));
textFile = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt");
buildGoogleApiClient();
}
#Override
protected void onStart() {
super.onStart();
Log.i(TAG, "connecting...");
googleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (googleApiClient != null) {
Log.i(TAG, "disConnecting...");
googleApiClient.disconnect();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
Log.i(TAG, "In onActivityResult() - connecting...");
googleApiClient.connect();
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "in onConnected() - connected");
Drive.DriveApi.newDriveContents(googleApiClient)
.setResultCallback(driveContentsCallback);
}
#Override
public void onConnectionSuspended(int cause) {
switch (cause) {
case 1:
Log.i(TAG, "Connection suspended - Cause: " + "Service disconnected");
break;
case 2:
Log.i(TAG, "Connection suspended - Cause: " + "Connection lost");
break;
default:
Log.i(TAG, "Connection suspended - Cause: " + "Unknown");
break;
}
}
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback = new
ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Error creating the new file of contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
new Thread() {
#Override
public void run() {
OutputStream outputStream = driveContents.getOutputStream();
addTextfileToOutputStream(outputStream);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("SmsBackup")
.setMimeType("text/plain")
.setDescription("This is a text file uploaded from device")
.setStarred(true).build();
Drive.DriveApi.getRootFolder(googleApiClient)
.createFile(googleApiClient, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
};
private void addTextfileToOutputStream(OutputStream outputStream) {
byte[] buffer = new byte[1024];
int bytesRead;
try {
BufferedInputStream inputStream = new BufferedInputStream(
new FileInputStream(textFile));
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
}
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(UploadData.this,
"Error adding file to Drive", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(UploadData.this,
"File successfully added to Drive", Toast.LENGTH_SHORT).show();
showProgress(false);
rl.setBackgroundColor(getResources().getColor(R.color.colorBack));
View root = rl.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.colorBack));
success.setVisibility(View.VISIBLE);
final PendingResult<DriveResource.MetadataResult> metadata
= result.getDriveFile().getMetadata(googleApiClient);
metadata.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(DriveResource.MetadataResult metadataResult) {
Metadata data = metadataResult.getMetadata();
drive_id = data.getDriveId().encodeToString();
driveID = data.getDriveId();
}
});
}
};
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
}
}
private void buildGoogleApiClient() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
progressBar.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
}
You might want to check on how you work with File Contents, first you might want to check if there is a value on the variable textFile that you have set.
The example below illustrates how to append "hello world" to the DriveContents.
try {
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("hello world");
} catch (IOException e) {
e.printStackTrace();
}
There is a related SO question - Upload text file to Google Drive using Android that you might want to check out. The answer in the question reminds the OP regarding how to feed the file with contents.
Lastly, you might want to check this github. This code show how to insert the content of the chat into a file and save it to the drive.
Hope this helps.
I'm uploading files to Google Drive using Google Drive api . I would like to know, how i can put a check for duplicate files. Because currently when my service runs, it uploads the file to google drive which was already uploaded before,
Here's my code:
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
public ArrayList songsList = new ArrayList();
private static final String TAG = "drive-quickstart";
private GoogleApiClient mGoogleApiClient;
public static ArrayList<File> listAllMusicFiles = new ArrayList<File>();
public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
private SharedPreferences sharedPreferences;
/**
* DriveId of an existing file to be used in file operation samples..
*/
public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
/**
* Next available request code.
*/
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
private static final String DRIVE_ID = "driveId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final File mainDir = new File(Environment.getExternalStorageDirectory()
.getPath());
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
loadSdcardfiles(mainDir);
}
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive(final File file) {
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
final DriveContents driveContents = result
.getDriveContents();
// Otherwise, we can write our data to the new contents.
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = result.getDriveContents()
.getOutputStream();
// Write the bitmap data from it.
try {
#SuppressWarnings("resource")
FileInputStream fileInputStream = new FileInputStream(
file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setTitle(file.getName()).build();
// create a file on root folder
Drive.DriveApi
.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient,
metadataChangeSet, driveContents)
.setResultCallback(fileCallback);
try {
} catch (Exception e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
private void loadSdcardfiles(File aFile) {
if (aFile.isFile()) {
if (aFile.getAbsolutePath().endsWith(".mp3")) {
listAllMusicFiles.add(aFile);
}
} else if (aFile.isDirectory()) {
File[] listOfFiles = aFile.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
loadSdcardfiles(listOfFiles[i]);
}
}
} else {
}
}
}
#SuppressWarnings("unchecked")
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API).addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#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();
}
}
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
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);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(this, "API client connected" + listAllMusicFiles.get(0),
1000).show();
if (listAllMusicFiles.size() == 0) {
return;
} else {
for (int i = 0; i < listAllMusicFiles.size(); i++) {
saveFileToDrive(listAllMusicFiles.get(i));
}
}
}
#Override
public void onConnectionSuspended(int cause) {
Toast.makeText(this, "GoogleApiClient connection suspended", 1000)
.show();
}
// private void storeSumFileId(DriveId driveId) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putString(DRIVE_ID, driveId.encodeToString());
// editor.apply();
//
// }
// final private ResultCallback<DriveResource.MetadataResult> metadataRetrievedCallback = new ResultCallback<DriveResource.MetadataResult>() {
// #Override
// public void onResult(DriveResource.MetadataResult result) {
// if (!result.getStatus().isSuccess()) {
// Log.v(TAG, "Problem while trying to fetch metadata.");
// return;
// }
//
// Metadata metadata = result.getMetadata();
// if (metadata.isTrashed()) {
// Log.v(TAG, "Folder is trashed");
// } else {
// Log.v(TAG, "Folder is not trashed");
// }
//
// }
// };
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file with content: "
+ result.getDriveFile().getDriveId());
// storeSumFileId(result.getDriveFile().getDriveId());
}
};
}
i found the following links, but was unable to use it in my code :
Google Drive Android API - Check if folder exists
https://developers.google.com/drive/android/trash#trash_or_untrash_a_file_or_folder
Can anyone tell me how to make ckeck of existing File on drive?
Thanks.
I have some problem with printing image to AGPtEK 58mm Mini Bluetooth Pocket POS Thermal Receipt Printer. I am trying to convert webview content into image (this is working fine) and after that I want to print it with this printer but it prints only solid black background. Here is my code:
public class PrintDemo extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int PERMISSIONS_REQUEST_BLUETOOTH = 1;
private static final String TAG_REQUEST_PERMISSION = "Request permission";
private static final int PERMISSIONS_REQUEST_INTERNET = 0;
private static final int PERMISSIONS_REQUEST_BT_ADMIN = 2;
private static final int PERMISSIONS_REQUEST_LOCATION = 3;
private static final String WEB_SITE = "Remembered Web Site";
private static final String IS_CHECKED = "Check box";
#Bind(R.id.btn_search)
Button btnSearch;
#Bind(R.id.btn_print)
Button btnSendDraw;
#Bind(R.id.btn_open)
Button btnSend;
#Bind(R.id.btn_close)
Button btnClose;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("State", "Connecting...");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("State", "Not found");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
String path;
File dir;
File file;
#Bind(R.id.check_box)
CheckBox checkBox;
#Bind(R.id.txt_content)
EditText edtContext;
#Bind(R.id.web_view)
WebView webView;
BluetoothService mService;
BluetoothDevice con_dev;
private SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.main);
ButterKnife.bind(this);
mService = new BluetoothService(this, mHandler);
if (!mService.isAvailable()) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.setWebViewClient(new WebViewClient() {
#SuppressLint("SdCardPath")
#Override
public void onPageFinished(final WebView view, String url) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
siteToImage(view);
}
}, 5000);
}
});
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
checkPermissions();
}
private void siteToImage(WebView view) {
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(
picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setRememberedWeb() {
if (checkBox.isChecked()) {
String rememberedWeb = sharedPref.getString(WEB_SITE, "");
if (!rememberedWeb.equals("")) {
edtContext.setText(rememberedWeb);
}
}
}
#Override
protected void onPause() {
super.onPause();
saveState(checkBox.isChecked());
}
#Override
protected void onResume() {
super.onResume();
checkBox.setChecked(load());
setRememberedWeb();
}
private void saveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IS_CHECKED, isChecked);
if (isChecked) {
editor.putString(WEB_SITE, edtContext.getText().toString());
} else {
editor.putString(WEB_SITE, getString(R.string.txt_content));
}
editor.apply();
}
private boolean load() {
return sharedPref.getBoolean(IS_CHECKED, false);
}
private boolean checkPermissions() {
int permissionCheck =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
int permissionInternet =
ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
int permissionBTAdmin =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN);
int permissionLocation =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bluetooth_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.BLUETOOTH)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTPermission();
}
return false;
} else if (permissionInternet == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_internet_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestInternetPermission();
}
return false;
} else if (permissionBTAdmin == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bt_admin_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTAdminPermission();
}
return false;
} else if (permissionLocation == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_location_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestLocationPermission();
}
return false;
} else {
return true;
}
}
private void requestLocationPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
private void requestBTAdminPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},
PERMISSIONS_REQUEST_BT_ADMIN);
}
private void requestInternetPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.INTERNET},
PERMISSIONS_REQUEST_INTERNET);
}
private void requestBTPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH},
PERMISSIONS_REQUEST_BLUETOOTH);
}
#Override
public void onStart() {
super.onStart();
if (!mService.isBTopen()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_print);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btn_open);
btnSend.setOnClickListener(new ClickEvent());
btnClose = (Button) this.findViewById(R.id.btn_close);
btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("TAG", ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, file.getPath());
sendData = pg.printDraw();
mService.write(sendData);
}
public void downloadContent() {
if (!edtContext.getText().toString().equals("") && !edtContext.getText().toString().equals("https://")) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(edtContext.getText().toString())
.build();
HttpService service = retrofit.create(HttpService.class);
Call<ResponseBody> result = service.getContent();
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
if (response.body() != null) {
String summary = response.body().string();
webView.loadData(summary, "text/html; charset=utf-8", null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
public interface HttpService {
#GET("/")
Call<ResponseBody> getContent();
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
downloadContent();
} else if (v == btnClose) {
mService.stop();
} else if (v == btnSendDraw) {
printImage();
}
}
}
}
The result is almost what I want you can see by yourself, but the printed image is not clear:
I fixed it guys, this was the problem, the method siteToImage(). Here are the changes I hope it will helps someone:
private void siteToImage() {
webView.measure(View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.setDrawingCacheEnabled(true);
webView.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(webView.getMeasuredWidth(),
webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Paint paint = new Paint();
int iHeight = b.getHeight();
c.drawBitmap(b, 0, iHeight, paint);
webView.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
b.compress(Bitmap.CompressFormat.PNG, 50, fos);
fos.flush();
fos.close();
b.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
I want to get File Or Folder ID when that file is changed from the web. I gone through Documentation Listening for Change Events Git Hub Demo But i am not able to implement it.
In my app i am trying to listen to changes and modify those changes to local files also (sync).
In this test code i am just creating a folder and attaching a listner to the folder.
but when i rename folder from web Listner in not listening why?
1>I tried with this code
DriveId ddid = sky.getDriveFolder().getDriveId();
DriveFolder df = Drive.DriveApi.getFolder(mGoogleApiClient, ddid);
df.addChangeListener(getGoogleApiClient(), changeListener2);
2> And also with this line
DriveFolderResult sky = Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet).await();
sky.getDriveFolder().addChangeListener(getGoogleApiClient(), changeListener2);
class file.
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private static final int PICKFILE_RESULT_CODE = 1;
private ContentsResult contentsresult;
private GoogleApiClient mGoogleApiClient;
String EXISTING_FILE_ID = "";
int folderCreated = 0;
SharedPreferences prefs;
ArrayList<String> dbfileid = new ArrayList<String>();
ArrayList<String> dbfilename = new ArrayList<String>();
String fdd="";
DriveFolderResult sky;
private DriveId mFolderDriveId;
String isfolder;
SharedPreferences sp;
String Shared="Shared";
String folderid="";
int j=0;
String songfileid="";
String realid ="";
#Override
protected void onResume() {
super.onResume();
initDrive();
}
private void initDrive() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(com.google.android.gms.drive.Drive.API)
.addScope(com.google.android.gms.drive.Drive.SCOPE_FILE).setAccountName("shivrajp130#gmail.com")
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
if (!result.hasResolution()) {
// show the localized error dialog.
showToast("Error in on connection failed");
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
showToast("error" + e.toString());
}
}
#Override
public void onConnected(Bundle connectionHint) {
showToast("Inside Connected");
sp = getSharedPreferences(Shared, Context.MODE_PRIVATE);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showToast("Thread Started");
createSkyFolder();
}
});
t.start();
}
private void createSkyFolder()
{
// TODO Auto-generated method stub
try
{
showToast("creating Folder");
if(!sp.getString(isfolder, "false").contains("created"))
{
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().
setTitle("Sky folder").build();
sky = Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet).await();
sky.getDriveFolder().addChangeListener(getGoogleApiClient(), changeListener2);
showToast("folder created");
sp.edit().putString(isfolder, "created").commit();
// To store secret ID string of file or folder so that we can later get a DriveId object.
realid = sky.getDriveFolder().getDriveId().encodeToString();
sp.edit().putString(folderid, realid).commit();
showToast("Real== "+realid);
}
Status s = Drive.DriveApi.requestSync(mGoogleApiClient).await();
if(s.isSuccess())
{
showToast("Success");
}
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
showToast("Connected");
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,
Toast.LENGTH_SHORT).show();
}
});
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
final private Listener<ChangeEvent> changeListener2 = new Listener<ChangeEvent>() {
#Override
public void onEvent(ChangeEvent event) {
showToast("Listening now");
showToast(String.format("The New Id Is %s", event.hasMetadataChanged()));
}
};
#Override
public void onConnectionSuspended(int cause) {
showToast("GoogleApiClient connection suspended");
}
}
Please provide any code snippet for the same.
skilled friends.
Could you someone help me with my problem, please? I'm trying to use GDAA (Google Drive API for Android = https://developers.google.com/drive/android/appfolder) for backup and restore my DB file. Not REST API.
I tried use their demo classes from here: https://github.com/googledrive/android-demos/, but no positive result.
I suceed with authentication and with save my DB file into App Folder in Google Drive, but I can not edit or retrieve this file. I only still create new and new files. Could you help me, please?
I call this Edit activity:
public class EditContentsActivity extends BaseDemoActivity {
private static final String TAG = "EditContentsActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
final ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
Intent intent = new Intent(getBaseContext(), CreateFileInAppFolderActivity.class);
startActivity(intent);
return;
}
DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(), result.getDriveId());
new EditContentsAsyncTask(EditContentsActivity.this).execute(file);
}
};
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
}
public class EditContentsAsyncTask extends ApiClientAsyncTask<DriveFile, Void, Boolean> {
public EditContentsAsyncTask(Context context) {
super(context);
}
#Override
protected Boolean doInBackgroundConnected(DriveFile... args) {
DriveFile file = args[0];
try {
DriveContentsResult driveContentsResult = file.open(
getGoogleApiClient(), DriveFile.MODE_WRITE_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
OutputStream outputStream = driveContents.getOutputStream();
String dbpath = "/data/" + "com.myapp" + "/databases/" + DatabaseHelper.DB_NAME;
FileInputStream fis = new FileInputStream(Environment.getDataDirectory() + dbpath);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
com.google.android.gms.common.api.Status status =
driveContents.commit(getGoogleApiClient(), null).await();
outputStream.flush();
outputStream.close();
fis.close();
return status.getStatus().isSuccess();
} catch (IOException e) {
Log.e(TAG, "IOException while appending to the output stream", e);
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
If I get "!result.getStatus().isSuccess()" I want to call Create Activity:
public class CreateFileInAppFolderActivity extends BaseDemoActivity {
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// create new contents resource
Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(driveContentsCallback);
}
final private ResultCallback<DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(EXISTING_FILE_ID)
.setMimeType(mimeType)
.build();
OutputStream os = result.getDriveContents().getOutputStream();
try {
String dbpath = "/data/" + "com.myapp" + "/databases/" + DatabaseHelper.DB_NAME;
FileInputStream fis = new FileInputStream(Environment.getDataDirectory() + dbpath);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
Drive.DriveApi.getAppFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
os.flush();
os.close();
fis.close();
throw new IOException("");
} catch (IOException e) {
Log.e("IOExceptions=", e.toString());
Drive.DriveApi.getAppFolder(getGoogleApiClient()).delete(getGoogleApiClient());
}
}
};
final private ResultCallback<DriveFileResult> fileCallback = new
ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file in App Folder: "
+ result.getDriveFile().getDriveId());
}
};
All extend this Base Demo Activity:
public abstract class BaseDemoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "BaseDriveActivity";
/**
* DriveId of an existing folder to be used as a parent folder in
* folder operations samples.
*/
public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
/**
* DriveId of an existing file to be used in file operation samples..
*/
public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
/**
* Next available request code.
*/
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
/**
* Google API client.
*/
private GoogleApiClient mGoogleApiClient;
/**
* Called when activity gets visible. A connection to Drive services need to
* be initiated as soon as the activity is visible. Registers
* {#code ConnectionCallbacks} and {#code OnConnectionFailedListener} on the
* activities itself.
*/
#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();
}
}
/**
* Called when activity gets invisible. Connection to Drive service needs to
* be disconnected as soon as an activity is invisible.
*/
#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 Activity:
public class RetrieveContentsActivity extends BaseDemoActivity {
private static final String TAG = "RetrieveContentsActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
}
final private ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
new RetrieveDriveFileContentsAsyncTask(
RetrieveContentsActivity.this).execute(result.getDriveId());
}
};
final private class RetrieveDriveFileContentsAsyncTask
extends ApiClientAsyncTask<DriveId, Boolean, String> {
public RetrieveDriveFileContentsAsyncTask(Context context) {
super(context);
}
#Override
protected String doInBackgroundConnected(DriveId... params) {
String contents = null;
DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(), params[0]);
DriveContentsResult driveContentsResult =
file.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
return null;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
BufferedReader reader = new BufferedReader(
new InputStreamReader(driveContents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
contents = builder.toString();
} catch (IOException e) {
Log.e(TAG, "IOException while reading from the stream", e);
}
driveContents.discard(getGoogleApiClient());
return contents;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result == null) {
showMessage("Error while reading from the file");
return;
}
showMessage("File contents: " + result);
}
}
And there is Authentication code:
public abstract class ApiClientAsyncTask<Params, Progress, Result>
extends AsyncTask<Params, Progress, Result> {
private GoogleApiClient mClient;
public ApiClientAsyncTask(Context context) {
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(context)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE);
mClient = builder.build();
}
#Override
protected final Result doInBackground(Params... params) {
Log.d("TAG", "in background");
final CountDownLatch latch = new CountDownLatch(1);
mClient.registerConnectionCallbacks(new ConnectionCallbacks() {
#Override
public void onConnectionSuspended(int cause) {
}
#Override
public void onConnected(Bundle arg0) {
latch.countDown();
}
});
mClient.registerConnectionFailedListener(new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult arg0) {
latch.countDown();
}
});
mClient.connect();
try {
latch.await();
} catch (InterruptedException e) {
return null;
}
if (!mClient.isConnected()) {
return null;
}
try {
return doInBackgroundConnected(params);
} finally {
mClient.disconnect();
}
}
/**
* Override this method to perform a computation on a background thread, while the client is
* connected.
*/
protected abstract Result doInBackgroundConnected(Params... params);
/**
* Gets the GoogleApliClient owned by this async task.
*/
protected GoogleApiClient getGoogleApiClient() {
return mClient;
}
Do you know the right approach with this demo, please?
Unfortunately, I don't have time to dig through all of the code above, but I can (at least) give you some general pointers.
First, the demos you mention do work, I've tested it and have it running. But since the demos cover just about any scenario, it is difficult to trace your possible error.
Now, the pointers:
When you create a file, you get back a DriveId.
You use that DriveId to retrieve the file
The content of the file is a binary byte array or stream
I've put together a basic CRUD wrapper for the GDAA, you can find it here.
In the GDAA.java class, you'll find 'createFile()' method. I think you have to give it the 'result.getDriveFile().getDriveId()' that you received in your 'fileCallback' above (as a parent). The content is passed in as a standard java.io.File
That method returns DriveId (in String form so I can easily cache it) and you can pass that DriveId to the 'read()' method that will give you a byte array (stream) back. Dump it to a java.io.File and you're done (don't forget to run it off-UI thread, they are blocking methods).
I would recommend to test it first using Drive's root (not app folder), so you can actually see the file in drive.google.com
Good Luck