I am using Gmail API on Android and I have a problem for file attachment.
I followed example below:
https://developers.google.com/gmail/api/guides/sending#creating_messages_with_attachments
and the problem is arisen here:
String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
I want to attach a video file about 8MB, but this line shows 'out of memory' error.
It is okay when I send image file attachment. (Typically below 1MB).
How can I deal with it?
I don't know android, so I may be way off base, but their code shows:
mimeBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileDir + filename);
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(filename);
String contentType = Files.probeContentType(FileSystems.getDefault()
.getPath(fileDir, filename));
You are encoding the base64 directly, which explodes into a fairly large string. The FileDataSource likely works around that.
Related
I'm trying to implement Google Speech API in Android by following this demo: https://github.com/GoogleCloudPlatform/android-docs-samples
I was able to successfully reproduce the example in my app by using the given "audio.raw" file located in R.raw, and everything works perfectly. However, when I try to use my own audio files, it returns "API successful" without any transcription text. I'm not sure if it has to do with the files' path or the encoding, so I'll include information on both just in case.
Encoding
My audio files are obtained by recording a voice through MediaRecorder. These are the settings:
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_WB);
myAudioRecorder.setAudioSamplingRate(16000);
myAudioRecorder.setAudioEncodingBitRate(16000);
myAudioRecorder.setAudioChannels(1);
myAudioRecorder.setOutputFile(outputFile);
SpeechService's recognizeInputStream() function in the API:
mApi.recognize(
RecognizeRequest.newBuilder()
.setConfig(RecognitionConfig.newBuilder()
.setEncoding(RecognitionConfig.AudioEncoding.AMR_WB) //originally it was LINEAR16
.setLanguageCode("en-US")
.setSampleRateHertz(16000)
.build())
.setAudio(RecognitionAudio.newBuilder()
.setContent(ByteString.readFrom(stream))
.build())
.build(),
mFileResponseObserver);
Encoding guidelines by Google: https://cloud.google.com/speech/docs/best-practices
From what I understand, I can use AMR_WB and 16kHz instead of the default LINEAR16, I'm just not sure if I'm doing it right.
Path
This is the example that is fully working (with the audio file from the repo):
mSpeechService.recognizeInputStream(getResources().openRawResource(R.raw.audio));
However, none of the following options work, even with the exact same file:
InputStream inputStream = new URL("[website]/test/audio.raw").openStream();
mSpeechService.recognizeInputStream(inputStream);
Neither:
Uri uri = Uri.parse("android.resource://[package]/raw/audio");
InputStream inputStream = getActivity().getContentResolver().openInputStream(uri); //"getActivity()" because this is in a Fragment
mSpeechService.recognizeInputStream(inputStream);
To be clear, the result on the above paths is the same as on my custom audio files: "API successful" with no transcription. One of the options I have tried for my custom audio files, with the same thing happening, is this:
FileInputStream fis = new FileInputStream(filePath);
mSpeechService.recognizeInputStream(fis);
The only reason I'm not 100% sure the problem is in the path is because if the API is returning with success, then the file was found in the specified path. The problem should be the encoding, but then it's weird that the same file ("audio.raw") sent in different ways produces different results.
Anyway, thank you in advance! :)
EDIT:
To be clear, it's not that it returns an empty string in the transcription. It just never enters the "onSpeechRecognized" function that also exists in the demo, so no transcription is given.
I created webapp which sends file by FileRepresentation. Client is an Android app. How can I get File from Restlet Response object on the client side?
The file content will be present within the payload. So you can extract it like any payload with Restlet, as described below:
ClientResource cr = new ClientResource(...);
Representation rep = cr.get();
In fact, the FileRepresentation class is provided in order to fill request / response from a file but can't be used to extract content of a response.
To have access to your response content on the client side, it depends on the file type. If you receive an ascii content, you can do something like that:
Representation representation = cr.get();
String fileContent = representation.getText();
If it's a binary file, you need to work with a stream, as described below:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
cr.get().write(outputStream);
byte[] fileContent = outputStream.toByteArray();
Hope it helps you,
Thierry
To edit a Google Drive native doc on my Android app, I'm downloading the file to a .docx format (converting), editing the file in an editor capable of editing MS Word docx files, then I'm uploading the file back to its native Google doc format.
I'm using the following code:
File liveFileInfo = sService.files().get(mItem.getFileId()).execute();
mInputStream = new FileInputStream(pFile); //pFile is the java.io.File of the source XXX.docx file
InputStreamContent mediaContent = new InputStreamContent("application/vnd.openxmlformats-officedocument.wordprocessingml.document",
new BufferedInputStream(mInputStream));
mediaContent.setLength(pFile.length());
Drive.Files.Update update = sService.files().update(mItem.getFileId(), liveFileInfo, mediaContent);
update.setConvert(true);
MediaHttpUploader uploader = update.getMediaHttpUploader();
int chunkSize = getChunkSize(mItem);
uploader.setChunkSize(chunkSize);
uploader.setProgressListener(new MediaHttpUploaderProgressListener() {
#Override
public void progressChanged(MediaHttpUploader uploader)
throws IOException {
// update UI
}
});
File uploadedFile = update.execute();
The code runs without errors, but the contents of the file contains all the weird characters you normally see when the wrong format is uploaded or an incorrect file type.
So my question is whether it is possible to update an existing file using this process? Or is the conversion process only supported with INSERTed files? Is there anything wrong with the code above?
I figured out what I missed. Add the following line to the code above to fix the problem:
liveFileInfo.setMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
I don't know how to get an InputStream(Read gzipped local xml file) from the locally stored gzip xml file.
employee.gz
If someone Can help I really appreciate. Thanks
This link works with zip. http://techdroid.kbeanie.com/2010/10/unzip-files-in-android.html
I am not sure if it will work with gz files, but you could give it a try. There's a documentation on GZIPInputStream class on the dev docs.
http://developer.android.com/reference/java/util/zip/GZIPInputStream.html
This piece of code works.
GZIPInputStream inputStream = new GZIPInputStream(new FileInputStream(new File(
"path to file")));
String str = IOUtils.convertStreamToString(inputStream);
I have used a util class which converts the input stream to a string. You might want to do the reading part manually.
I'm trying to post a notification that lets the user open a locally stored file. My code looks like this:
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(filename));
notificationIntent.setData(uri);
Where "filename" is the full path to a locally stored file, usually in the /mnt/sdcard/download directory. The files I want to display are of various types: images, PDF documents, HTML, etc.
This works, but sometimes Android tries to open the file as the wrong type. For example, a jpeg file will open in a web browser view and instead of seeing the image, I see the binary data from the file displayed as text. Other times it works file. For example, some PDF files correctly open in a PDF viewer and some do not.
I'm not sure why this is. The documentation says I should not have to pass an explicit content type. If I do set the content type explicitly, things seem to work fine. The problem is, I don't always know what the content type should be (the file is downloaded from an external source and can be anything, and no, the MIME type is not in the HTTP headers, I checked for that).
What can I do here? Is there some function I can call with a filename to have Android return me the best content type for that file? Moreover, why is this not happening automatically when the Intent is processed?
Thanks.
You've most likely figured this out; I'm posting in case someone else is stuck on this. I do the following to get the mime-type of the file:
//Get the file path
Uri path = Uri.fromFile(file);
MimeTypeMap type_map = MimeTypeMap.getSingleton();
//Get the extension from the path
String extension = MimeTypeMap.getFileExtensionFromUrl(path.toString());
extension = extension.toLowerCase();
if (extension.contains(".")) {
extension = extension.substring(extension.lastIndexOf("."));
}
String mime_type = type_map.getMimeTypeFromExtension(extension);