How to SetModifiedDate() Drive SDK - android

i'm developing an app using google drive SDK currently on Android using eclipse, i encounter an error which happen everytime i try to update modified date from file that i upload. this my code.
com.google.api.services.drive.model.File f=null;
File a=new File(file[1]);
com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle(file[1].substring(file[1].lastIndexOf("/")+1, file[1].length()));
Uri selectedUri = Uri.fromFile(a);
String fileExtension
= MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString());
String mimeType
= MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
body.setMimeType(mimeType);
System.out.println(DateTime.parseRfc3339(file[2]));
body.setModifiedDate(DateTime.parseRfc3339(file[2]));
//this modified date code causing error
FileContent mediaContent = new FileContent(mimeType, a);
try {
f = service.files().insert(body, mediaContent).setConvert(true).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
handleException(e);
}
can someone tell me how to setModifiedDate in correct way, i'm totally stuck here..
thanks in advance

You can only set the date on a files().update not on files().insert. Also make sure you set the parameter setModifiedDate to true if you use update.
service.files().update(body,mediacontent).setSetModifiedDate(true).execute();

Related

Why is the filelist array null in Java with Android Studio?

I am using Android Studio with Java.
I have written a method (namely deleteWithExtension) to delete files from device internal memory. This method is adding some test files and tries to get the listof these files.
But the problem is that, the code never goes in the for-loop because of the array theFiles[] returns null. As you can see that, the code begins with sample files adding process so it should not be empty. I can also see those sample files in the Device File Explorer of Android Studio.
public static void CreateFile(Context mContext, String fileName, String textToBeWritten) {
try {
File dosya = new File(mContext.getFilesDir() + fileName);
dosya.createNewFile();
FileWriter fw = new FileWriter(dosya);
BufferedWriter yazici = new BufferedWriter(fw);
yazici.write(textToBeWritten);
yazici.flush();
yazici.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void deleteWithExtension(Context mContext, String extension) {
//First let's add a few sample files with same extension.
CreateFile(mContext,"SampleFile1.smp","anything1");
CreateFile(mContext,"SampleFile2.smp","anything2");
CreateFile(mContext,"SampleFile3.smp","anything3");
CreateFile(mContext,"SampleFile4.smp","anything4");
CreateFile(mContext,"SampleFile5.smp","anything5");
//Now, 5 sample files have been added. Let get them and put in an array.
File dir = mContext.getFilesDir();
final String[] theFiles = dir.list();
for (final String file : theFiles) {
//do something here....
int aa=9;
//The code never goes into here, because array theFiles is always null but 5 sample files was added at first.
}
}
replace the CreateFile() method as follows. I hope I can help you.
public static void CreateFile(Context mContext, String fileName, String textToBeWritten) {
try {
File dosya = new File(mContext.getFilesDir() + File.separator + fileName);
dosya.createNewFile();
FileWriter fw = new FileWriter(dosya);
BufferedWriter yazici = new BufferedWriter(fw);
yazici.write(textToBeWritten);
yazici.flush();
yazici.close();
} catch (Exception e) {
e.printStackTrace();
}
}

[Android ]Intent.ACTION_VIEW - Not found

I am having an issue, I have never had problem opening files via ACTION_VIEW the next way:
File file = new File(getActivity().getFilesDir(), TEMP_FILE_NAME);
String dataType = "image/*";
if (file.exists()) {
Intent fileIntent = new Intent(Intent.ACTION_VIEW);
fileIntent.setDataAndType(Uri.fromFile(file), dataType);
fileIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(fileIntent, "Open file");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "There is a problem when opening the file");
}
} else {
Toast.makeText(getContext(), "Invalido", Toast.LENGTH_LONG).show();
}
The problem I am having right now is that even though the file exists when I choose the app to open the file it immediately closes and tells me Not found. I have put the image I am loading in an image view and there is no problem, so the file is valid but for some reason it has conflicts when I am opening it via intent.
I am aware that it may have something to do with the way I am creating the file, I am retrieving it from Google drive so I am writing the file using the Apache Commons library the next way:
DriveContents contents = result.getDriveContents();
InputStream inputStream = contents.getInputStream();
File file = new File(getActivity().getFilesDir(), TEMP_FILE_NAME);
try {
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
What is it I am doing wrong? I am not totally sure if the problem has to do with the copy method executing asynchronously or something like that.
Thanks in advance.
I have never had problem opening files via ACTION_VIEW the next way
That code will never work, as third-party apps have no rights to work with files on getFilesDir() of your app.
What is it I am doing wrong?
You are attempting to serve an inaccessible file to third-party programs. Use FileProvider to serve the file, using FileProvider.getUriForFile() to get the Uri to use in your ACTION_VIEW Intent.

Android - Google Drive SDK - Open file

I am used to opening my files in my apps using the next code:
public void openFile(#NonNull String uri) {
checkNotNull(uri);
File file = new File(uri);
String dataType = null;
if (ContentTypeUtils.isPdf(uri)) dataType = "application/pdf";
else if (ContentTypeUtils.isImage(uri)) dataType = "image/*";
if (file.exists() && dataType != null) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), dataType);
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open file");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "There is a problem when opening the file :(");
}
} else {
Toast.makeText(getContext(), "Invalido", Toast.LENGTH_LONG).show();
}
}
I had always used static files so this was enough, but now I am using the Google Drive SDK for Android. I possess the driveId of the file I want to open but the problem is I cannot find a clean way to open the file contents I obtain by doing this:
Drive.DriveApi.fetchDriveId(mGoogleApiClient, documentFile.getDriveId())
.setResultCallback(driveIdResult -> {
PendingResult<DriveApi.DriveContentsResult> open =
driveIdResult.getDriveId().asDriveFile().open(
mGoogleApiClient,
DriveFile.MODE_READ_ONLY,
null);
open.setResultCallback(result -> {
DriveContents contents = result.getDriveContents();
InputStream inputStream = contents.getInputStream();
// I know I can get the input stream, and use it to write a new file.
});
});
So the only thing that comes to my mind is creating a static route to create a file every time I have to open it, and erasing it every time I have to open a new file.
What I have understood up until now is that the Google Drive API for Android already saves an instance of the file so what I have in mind sounds unnecessary, I would like to know if there is a better way to achieve this. Is there a way I can open the file and do something similar to what I do with the Intent.ACTION_VIEW in a cleaner way?
Thanks in advance.
Well since it seems this will not be answered I will post what I did. All I did was create a temp file where I put my contents to be read. I still don't know if it was the best choice so this question will still be opened for a better answer.
open.setResultCallback(result -> {
DriveContents contents = result.getDriveContents();
InputStream inputStream = contents.getInputStream();
writeTempFile(inputStream);
});
And here the implementation of the `writeTempFile`:
private synchronized File writeTempFile(#NonNull InputStream inputStream) {
checkNotNull(inputStream);
File filePath = new File(mActivity.getFilesDir(), "TempFiles");
if (!filePath.exists()) filePath.mkdirs();
File file = new File(filePath, TEMP_FILE);
try {
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copyLarge(inputStream, outputStream);
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
return file;
}

Retrieve filename from a web folder

I am using AsyncTask to download a file from a web folder. However, the name of the file will be different every time.
Is there a way to get the name of the file in a web folder? (There will be only 1 file in that folder at a given time).
http://www.example.com/myfolder/myfile_1
Try the ApacheURLLister (I didn't tested it but it may work):
URL url;
List serverDir = null;
try {
url = new URL("http://www.abc.com/myfolder/");
ApacheURLLister lister = new ApacheURLLister();
serverDir = lister.listAll(url);
}
catch (Exception e) {
e.printStackTrace();
Log.e("ERROR ON GETTING FILE","Error is " +e);
}
System.out.println(serverDir);
return serverDir;

Pictures wont save on Samsung Nexus

I have a Problem. I start from my own Application the Build-In Photoapplication with a Photo-Intent.
String photoName = System.currentTimeMillis() + ".jpg";
File file = new File(getFilesDir(),//Environment.getExternalStoragePublicDirectory(
//Environment.DIRECTORY_DCIM),
photoName); // Anlegen der Datei im entsprechenden
// Verzeichnis
FileOutputStream fos = null;
try {
fos = openFileOutput(photoName, Context.MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputFileUri = Uri.fromFile(file);
intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//startActivity(intentPhoto);
startActivityForResult(intentPhoto, TAKE_PICTURE);
This is my Code to start the Activity. As you can see, the first thing i do is to set up the file in the directory and then give the intent the location of the file to store it.
But everytime i take a picture it is not saved to the Pictures Directory. The only way to save the picture is to turn off the phone and restart it. Then every picture I have taken befor is there. This happens since the last updated to 4.1.1. Befor i updated the phone, everything worked fine, but since the update I have this problem.
Can somebody help me? Does anyone have the same Issue?
Make sure you offer the new file to be scanned:
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// code to execute when scanning is complete
}
});
You can pass in a null argument for the OnScanCompletedListener if you don't need to be notified when the scanner has picked it up, but you might want to at least put a logging statement there.
It works fine now, the problem was that I create the File by my self, with:
File file = new File(..);
But you have to use:
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "IMG_"+ timeStamp+.jpg");
And put it into the intent to save the file at once without restarting the phone.

Categories

Resources