ByteArray and stream conversion from Android

4 posts, 1 answers
  1. Dimitar
    Dimitar avatar
    42 posts
    Member since:
    May 2014

    Posted 01 Sep Link to this post

    Hi, 

    I have found :

     " I would like to provide some more info. We don not provide automatic conversion from java.nio.ByteBuffer to JavaScript ArrayBuffer. We provide ArrayBuffer.from function instead." 

    But as I see now "from" not supported , so what could be the the way to receive this Android Byte Array in Native Script and save it as file.

    I have this in Native script code which return a descritpor for a file 

    app.android.context.getContentResolver().openInputStream(args.intent.getData()) 

     

  2. nikolay.tsonev
    Admin
    nikolay.tsonev avatar
    285 posts

    Posted 04 Sep Link to this post

    Hi Dimitar,

    If I understand you correctly, you would like to receive the Binary data for a specific file and to save it in new file with different in different directory
    Regarding that, in NativeScirpt you could use a readSync method to get the Binary data of the needed file and save the binary data in a new place with writeSync. This scenario is demonstrated in the documentation here

    If this is not applicable for your case, please provide some more info about your scenario and what is the expected final result. This will help us to understand your case better.

    Bear in mind that the readSync method will return for Android native Android Binary array.



    Regards,
    nikolay.tsonev
    Progress Telerik
    Did you know that you can open private support tickets which are reviewed and answered within 24h by the same team who built the components? This is available in our UI for NativeScript Pro + Support offering.
  3. Dimitar
    Dimitar avatar
    42 posts
    Member since:
    May 2014

    Posted 04 Sep Link to this post

    My Scenario is a little bit different. I don't have access to the real path so , can't using the readSync. This is the way how I receive the file 

    let intent = new android.content.Intent() ;
     
    intent.setType("application/pdf");
     
    intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
    intent.addCategory(android.content.Intent.CATEGORY_OPENABLE);
     
    app.android.foregroundActivity.startActivityForResult(intent,3) ;
     
    app.android.on(app.AndroidApplication.activityResultEvent, function (args: app.AndroidActivityResultEventData)
    {
     
        if (args.requestCode == 3)
            app.android.off (app.AndroidApplication.activityResultEvent) ;
             
        if (args.requestCode == 3 && args.resultCode != 0 && args.intent != null)
        {
            console.log("Event: " + args.eventName + ", Activity: " + args.activity +
            ", requestCode: " + args.requestCode + ", resultCode: " + args.resultCode + ", Intent: " + args.intent);
     
     
            var pdfBytes = getFilePDF(app.android.context.getContentResolver().openInputStream(args.intent.getData()));

     

    I have this code which return and open a stream for receiving the file. 
    The android implementation of getFilePDF functions is look like : 

    public byte[] getFilePDF(InputStream stream) {
        byte[] buffer = new byte[4096];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            int size = stream.read(buffer);
            while(size!=-1)
            {
                byteArrayOutputStream.write(buffer,0,size);
                size = stream.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toByteArray();
    }

     

    SO I am trying to implment getFilePDF function in Nativesscipt . or if there other way to read the stream from openInputStream

     

     

     

     

     

     

  4. Answer
    nikolay.tsonev
    Admin
    nikolay.tsonev avatar
    285 posts

    Posted 04 Sep Link to this post

    Hello,

    Thank you for the further description of the case.

    In your scenario, you could use the ByteArrayOutputStream class to generate the source buffer from the selected file from the picker and to create a new file with the NativeScript file-system module. Then you could save the file with the writeSync method, which will save the binary source in the file.
    I am attaching sample code, where this scenario is demonstrated.
    TypeScript
    import { EventData } from 'data/observable';
    import { Page } from 'ui/page';
    import { HelloWorldModel } from './main-view-model';
    import * as app from "application"
    import {openUrl} from "utils/utils";
    import * as fs from "tns-core-modules/file-system";
    declare var android:any;
    declare var java:any;
    // Event handler for Page "navigatingTo" event attached in main-page.xml
    export function navigatingTo(args: EventData) {
     
        let page = <Page>args.object;
         
     
        page.bindingContext = new HelloWorldModel();
    }
     
    export function onTap(){
        let intent = new android.content.Intent() ;
         
       intent.setType("application/pdf");
         
       intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
       intent.addCategory(android.content.Intent.CATEGORY_OPENABLE);
     
        // >> --------------------- Create new pdf file ----------------------
        var fileName = "test2.pdf";
        var androidDownloadsPath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString();
        var newFilePath = androidDownloadsPath+"/"+fileName;
        console.log("filePath "+newFilePath);
        var destinationFile =  fs.File.fromPath(newFilePath);
        console.log("byteArrayOutputStream", destinationFile.path);
        // << --------------------- Create new pdf file ----------------------
     
     
       app.android.foregroundActivity.startActivityForResult(intent,3) ;
         
       app.android.on(app.AndroidApplication.activityResultEvent, function (args: app.AndroidActivityResultEventData)
       {
         
           if (args.requestCode == 3)
               app.android.off (app.AndroidApplication.activityResultEvent) ;
                 
           if (args.requestCode == 3 && args.resultCode != 0 && args.intent != null)
           {
               console.log("Event: " + args.eventName + ", Activity: " + args.activity +
               ", requestCode: " + args.requestCode + ", resultCode: " + args.resultCode + ", Intent: " + args.intent);
               console.log("---------------------------");
               console.dir(args.intent.getData());
               console.log("---------------------------");
            console.log(args.intent.getData().getEncodedPath());
            console.log(args.intent.getData().getHost());
            openUrl(args.intent.getData().getHost());
            // >> -------------------Get buffer---------------------
            var pdfBytes = getFilePDF(app.android.context.getContentResolver().openInputStream(args.intent.getData()));
            // << -------------------Get buffer---------------------
     
            // >> -------------------Save the buffer in the new file---------------
               destinationFile.writeSync(pdfBytes, e=> { console.log(e) });
            // << -------------------Save the buffer in the new file---------------
           }
        });
    }
     
    function getFilePDF( stream) {
        console.log("---------------------------");
        console.log("getFilePDF");
        let buffer = new (<any>Array).create("byte",4096);
        let byteArrayOutputStream = new     java.io.ByteArrayOutputStream();
        try {
            let size = stream.read(buffer);
            while(size!=-1)
            {
                byteArrayOutputStream.write(buffer,0,size);
                // console.log("byteArrayOutputStream");
                // console.log(byteArrayOutputStream);
                size = stream.read(buffer);
            }
        } catch (e) {
            console.log(e)
        }
        return byteArrayOutputStream.toByteArray();
    }


    In the sample code is created "test2.pdf" file, which is saved in the device download folder.

    Regards,
    nikolay.tsonev
    Progress Telerik
    Did you know that you can open private support tickets which are reviewed and answered within 24h by the same team who built the components? This is available in our UI for NativeScript Pro + Support offering.
Back to Top