How to send document to apps script kotlin android - android

Currently Iam sending string and image file as string. to sheet via Apps script (sheet extension). Now I need to send a document files like (.zip, .glb, .obj, .arp, etc) I need to send these type of files to google sheet. so now I need to make user selected files as .zip. so now I need to send that .zip file to google sheet. but I couldnt do that.
private fun startUploading() {
try {
val map: HashMap<String, String> = HashMap()
map["instagramLink"] = binding.creatorInstaID.text.toString()
map["tutorialLink"] = binding.youTubeLink.text.toString()
map["detailDescription"] = binding.detailDescription.text.toString()
map["coverImage"] = userImage!!
mainViewModel.saveProduct(map)
}
catch (e:Exception){
Toast.makeText(context, "Fill all the details", Toast.LENGTH_SHORT).show()
}
}
Here userImage is the user selected image which is converted as string.
other values are string values it can be sent to google sheet easily.
now how can i send a custom file types to google sheet. as like this.

The only workaround I found is converting the encode the file to base64. Then add the string of base64 to the Google Sheet. I made a sample file with a Zip file store in Google Drive. You might need to adjust the code as needed.
Also, remember that character limit of a Google Cell is 50,000, so I added an if statement in case the encode file has more than 50,000 characters and split the string in an array of 45000 characters.
Note: The same sample code can be use on any type of files.
function encode64() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")
// get the file from Google Drive using the ID
let file = DriveApp.getFileById("Drive_Zip_File_ID");
//convert the zip file to blob
let file_in_blop = file.getBlob();
//convert the blop to bytes
let file_in_bytes = file_in_blop.getBytes();
//encode the bytes to base64
let encoded = Utilities.base64Encode(file_in_bytes);
//get the length of charactes from the base 64 encode
let length_string = encoded.length
//split the string to array in chunks less than 45000 characters
if (length_string > 50000){
const result = encoded.match(/.{1,45000}/g) ?? [];
for (let i = 0; i < result.length; i++) {
sheet.getRange(i+2,2).setValue(result[i]);
}
}else(sheet.getRange("B2").setValue(result));
}

Related

ByteString what does the parameters exactly do?

I wanna upload some files which are 30 MB Max to my server with okhttp websocket.
The websocket transfer allows String or ByteString only.
So I want to convert my file to ByteString and then upload this to my server via websocket(Nodejs).
I use ByteString.of() to convert this byteArray like this.
val file = "../tmp/file.jpg"
try {
val encoded:ByteArray = Files.readAllBytes(Paths.get(file))
val byteString = ByteString.of(encoded,0,1024)
..send data
Log.d("log1","DATA DONE")
} catch (e: IOException) {
Log.d("log1","ERROR:"+e)
}
But what confuses me is that ByteString function takes 3 parameters..
First: ByteArray
Second: Offset
Third: Bytecount
My question is what does the last 2 parameters do and the reason behind it? I don't find any clear documentation about this. Just the roadmap that its added.
If you have any links or suggestions please let me know.
-Offset is actually where you want to start reading your bytes from.
Assume a Text file with the following data
Computer-science World
Quantum Computing
now the offset for the first line is 0 <0,Computer Science World> for the second line the offset will be <23,Quantum Computing>
-ByteCount is the number of bytes you want to count(include)
Let's help you with a piece of simple code
byte[] bytes1 = "Hello, World!".getBytes(Charsets.UTF_8);
ByteString byteString = ByteString.of(bytes1, 2, 9);
// Verify that the bytes were copied out.
Sytem.out.print(byteString.utf8());
Answer is : llo, Worl
So basically, method can be used as a substring. But since you want to send in all the bytes, you can simply use
fun of(vararg data: Byte): ByteString

Append line of text to Azure Block Blob from Android

I want to append a line of text to an existing Azure cloud block blob from an Android device.
In VB.Net I would AcquireLease, getBlockBlobReference, DownloadToFile, add the line on the local files system, UploadToFile, ReleaseLease . Simple and secure, if a bit long-winded.
In Android, it looks a little more tricky. At the moment, my best solution is this:
CloudBlockBlob blob1=container.getBlockBlobReference(chosenOne+".txt");
String proposedLeaseId1 = UUID.randomUUID().toString();
OperationContext operationContext1 = new OperationContext();
blob1.acquireLease(15, proposedLeaseId1, null /*access condition*/,null/* BlobRequestOptions */, operationContext1);
AccessCondition condition = new AccessCondition();
condition.setLeaseID(proposedLeaseId1);
BlobInputStream blobIn = blob1.openInputStream();
blob1.downloadAttributes();
long blobLengthToUse = blob1.getProperties().getLength();
byte[] result = new byte[(int) blobLengthToUse];
blob1.downloadToByteArray(result,0);
blobIn.close();
CloudBlockBlob blob1 = container.getBlockBlobReference(chosenOne+".txt");
String proposedLeaseId1 = UUID.randomUUID().toString();
OperationContext operationContext1 = new OperationContext();
blob1.acquireLease(15, proposedLeaseId1, null /*access condition*/,null/* BlobRequestOptions */, operationContext1);
AccessCondition condition = new AccessCondition();
condition.setLeaseID(proposedLeaseId1);
BlobInputStream blobIn = blob1.openInputStream();
blob1.downloadAttributes();
long blobLengthToUse = blob1.getProperties().getLength();
byte[] result = new byte[(int) blobLengthToUse];
blob1.downloadToByteArray(result,0);
blobIn.close();
blob1.deleteIfExists(DeleteSnapshotsOption.NONE,condition, null, operationContext1);
BlobOutputStream blobOut = blob1.openOutputStream();
//this is a byte by byte write ...
//which is fine ... but no use if you want to replace ...
/*int next = blobIn.read();
while (next != -1) {
blobOut.write(next);
next = blobIn.read();
}*/
blobOut.write(result);
String strTemp="This is just a test string";
blobOut.write(strTemp.getBytes());
blobOut.close();
Apart from being extremely long-winded, I am concerned that as soon as I delete the blob, the lease will go and that I may hit integrity issues. I would appreciate any help in making this code simpler and more secure. I know that Microsoft are planning to introduce append blobs in 3Q 2015, but I want to implement this now.
You can call PutBlock to upload the appended content (the maximum size of each block is 4MB, so please split the appended content into blocks if required), and then call PutBlockList on this blob by passing in the previously committed blocks plus and newly appended blocks.

Read Json into APK Asobe AIR as3

I need to read a .json that I have within my .APK. I have tried many times I've even spend more than 1 day in it.
I think the problem is that FLHAS PROFESSIONAL use, but not want to give surrendered.
Nor loaded pictures new URLRequest(pictURL) :
Here are some codes that do not work on your phone (Android):
var pictLdr:Loader = new Loader();
var pictURL:String = "basecon/avatar3d.jpg";
var pictURLReq:URLRequest = new URLRequest(pictURL);
pictLdr.load(pictURLReq);
this.addChild(pictLdr);
And so I read the JSON and does not work
var tempFiles:File = File.desktopDirectory;
tempFiles = tempFiles.resolvePath("basecon/conversaciones.json");
trace(tempFiles.url); // app-storage:/images
//file:///storage/sdcard1/basecon/conversaciones.json
Why? How Can I read my JSON ?
The PO has done his best to ask a question in English but it did end up being a little off. What he meant is "how to read a json file", it's not that he can't read it, it's that he doesn't know how.
A File object gives you information about a file but not about its contents so trying to read a file with a File object won't work. You simply need to load that file and read its contents.
var tempFiles:File = File.applicationDirectory;
var jsonFile:File = tempFiles.resolvePath("basecon/conversaciones.json");
var fileLoader:URLLoader = new URLLoader();
fileLoader.addEventListener(Event.COMPLETE, handleFile);
fileLoader.load(new URLRequest(jsonFile.url));
Then in the handleFile listener:
var jsonData:String = String(fileLoader.data);
var jsonObject:Object = JSON.parse(jsonData);
Pretty simple.

javamail fetch mail pop3 android

I want to fetch emails in android by using javamail.
but I encountered some problems.
in POP3, if I want to fetch the content of a certain mail, the javamail will download all the content of the mail including the attachments. if the attachments are large enough, the android program will throw oom exception. But I tried in IMAP protocal, it only fetch the skeleton of the content first and even if there are some large attachments, it works well.
so, how could I fetch the content of a certain email using pop3 protocal when there are large attachment in the email?
following codes work well with imap, but not with pop3.
public void getContent(Part part) throws Exception {
String contentType = part.getContentType();
int nameindex = contentType.indexOf("name");
boolean conname = false;
if (nameindex != -1)
conname = true;
if (part.isMimeType("text/plain") && !conname) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("text/html") && !conname) {
String html = (String) part.getContent();
Spanned plainText = Html.fromHtml(html);
bodytext.append(plainText);
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int counts = multipart.getCount();
for (int i = 0; i < counts; i++) {
BodyPart mpart = multipart.getBodyPart(i);
Log.d("type,"," "+ i+mpart.getContentType());
String disposition = mpart.getDisposition();
if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE))))
continue;
String contype = mpart.getContentType();
if(contype.toLowerCase().indexOf("application")!=-1||contype.toLowerCase().indexOf("name")!=-1)
continue;
getContent(multipart.getBodyPart(i));
}
} else if (part.isMimeType("message/rfc822")) {
getContent((Part) part.getContent());
}
}
I do not know the specifics of JavaMail, however:
IMAP provides methods in it's protocol for downloading MIME Parts of a message, allowing the message to be picked apart on the server and downloaded in parts.
POP3s basic protocol only has support for downloading the entire message. With the optional TOP extension, it will allow you to download the first n lines of a message.
If JavaMail has specific extensions to stream the download of a message to disk (rather than all in memory), that should allow you to get around your Out Of Memory error.
JavaMail 1.4.4 and later can cache POP3 messages in a tmp file on disk, thus using less memory. See the javadocs for the com.sun.mail.pop3 package for the properties to set. You'll still need to be careful how you process the contents of the mail, e.g., using getInputStream instead of getContent to process large attachments.

Why are foreign characters not read using inputStream?

I have a text file which contains data I need to preload into a SQLite database. I saved in in res/raw.
I read the whole file using readTxtFromRaw(), then I use the StringTokenizer class to process the file line by line.
However the String returned by readTxtFromRaw does not show foreign characters that are in the file. I need these as some of the text is Spanish or French. Am I missing something?
Code:
String fileCont = new String(readTxtFromRaw(R.raw.wordstext));
StringTokenizer myToken = new StringTokenizer(fileCont , "\t\n\r\f");
The readTxtFromRaw method is:
private String readTxtFromRaw(Integer rawResource) throws IOException
{
InputStream inputStream = mCtx.getResources().openRawResource(rawResource);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
return byteArrayOutputStream.toString();
}
The file was created using Eclipse, and all characters appear fine in Eclipse.
Could this have something to do with Eclipse itself? I set a breakpoint and checked out myToken in the Watch window. I tried to manually replace the weird character for the correct one (for example í, or é), and it would not let me.
Have you checked the several encodings?
what's the encoding of your source file?
what's the encoding of your output stream?
the byteArrayOutputStream.toString() converts according to the platform's default character encoding. So I guess it will strip the foreign characters or convert them in a way that they are not displayed in your output.
Have you already tried to use byteArrayOutputStream.toString(String enc)? Try "UTF-8" or "iso-8859-1" or "UTF-16" for the encoding.

Categories

Resources