0

I have an Intent of ACTION_GET_CONTENT in my app and I need to put the picked file ( there will be different files, ppt, doc...) in a java.io File.

I'm able to get the data and put it into a android.net Uri. Is there a way I ca create a java File from this Uri?

I need it to be a file in order to upload it do google drive using the google drive API

This is the code to upload to the drive, I need to convert the uri to a temporary file in order to pass it as the javaFile of this method

 public Task<File> uploadFileWithMetadata(java.io.File javaFile, boolean isSlide,  @Nullable final String folderId, PostFileHolder postFileHolder) {
        return Tasks.call(mExecutor, () -> {

            Log.i("upload file", "chegou" );

            String convertTo; // string to convert to gworkspace
            if(isSlide){
                convertTo = TYPE_GOOGLE_SLIDES;
            }
            else{
                convertTo = TYPE_GOOGLE_DOCS;
            }

            List<String> folder;
            if (folderId == null) {
                folder = Collections.singletonList("root");
            } else {
                folder = Collections.singletonList(folderId);
            }

            File metadata = new File()
            .setParents(Collections.singletonList(folderId))
            .setName(postFileHolder.getDisplayName())
            .setMimeType(convertTo);

            Log.i("convert to: ", convertTo );

            // the convert to is the mimeType of the file, withg gworkspace it is a gdoc or gslide, with others is the regular mimetype
            FileContent mediaContent = new FileContent(postFileHolder.getConvertTo(), javaFile);

            Log.i("media content", "chegou" );
            // até aqui com gworkspace chega
            File uploadedFile = mDriveService.files().create(metadata, mediaContent)
                    .setFields("id")
                    .execute();

            Log.i("File ID: " , uploadedFile.getId());

            return uploadedFile;
        });
}

This is my code to get the Uri

 case REQUEST_CODE_FILE_PICKER:

                    // get uri from file picked
                    Uri url = data.getData();
                    break;
}
Nina
  • 79
  • 2
  • 10

1 Answers1

0

Solved it!

Here's how I did it:

        // my uri
        Uri fileUri = Uri.parse(postFileHolder.getFileUri());
        
        // create a null InputSream
        InputStream iStream = null;
        try {
            // create a temporary file
            File fileToUpload = File.createTempFile("fileToUpload", null, this.getCacheDir());
          
            iStream = getContentResolver().openInputStream(fileUri);
            
           // use function to get the bytes from the created InputStream
            byte[] byteData = getBytes(iStream);

            convert byteArray to File
            FileOutputStream fos = new FileOutputStream(fileToUpload);
            fos.write(byteData);
            fos.flush();
            fos.close();

            if(fileToUpload == null){
                Log.i("create file", "null");
            }
            else{
                Log.i("create file", "not null:  "+ fileToUpload.getTotalSpace());
                getEGDrive(fileToUpload);
            }
}
 catch (FileNotFoundException e) {
                Log.i("error create file uri", e.getLocalizedMessage());

                e.printStackTrace();
            } catch (IOException e) {
                Log.i("error create file uri", e.getLocalizedMessage());

                e.printStackTrace();
            }

And here's the function to transform the InputStream into byteArray:

 public byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }

Got big part of the answer from: https://stackoverflow.com/a/10297073/14990708

Nina
  • 79
  • 2
  • 10
  • `getContentResolver().openInputStream(fileUri)` That all is not needed as you can use the uri from ACTION_GET_CONTENT you obtained in onActiviltyResult like getContentResolver().openInputStream(data.getData()). Throw away that File converting stuff. – blackapps Jan 20 '21 at 17:42
  • @blackapps That's really way better! Is there a way I can pass this file to another activity? Because I will upload the file in one activity and actually save it in the next one – Nina Jan 20 '21 at 20:46
  • Yes, put as an extra the string data.getData().toString() in the intent to start that activity. But probably the permission to read the file is not valid there. If so change to ACTION_OPEN_DOCUMENT and take persistable uri permission first. – blackapps Jan 20 '21 at 21:44
  • @blackapps how can I put getContentResolver().openInputStream(data.getData()) in the file? – Nina Jan 21 '21 at 11:51
  • It is unclear which problem you have. Please show your onActivityResult code where you have or call that code. We wanna see how you proceed from there. – blackapps Jan 21 '21 at 11:56
  • I pass the data to a uri and send the uri to the next activity and use that method to transform the uri into a java file in the next activity, because I will only upload the file in the next activity. You said that using getContentResolver().openInputStream(data.getData()) would be better to put the data in the file, but this way I will have to send the actual file to the next activity, which I can't ( I think). So you told me to put as an extra the string data.getData().toString() in the intent to start that activity. How can I transform this string of the data into the file? – Nina Jan 21 '21 at 13:07
  • You willl not transform an uri to a file. You know already that you can open an inputstream for the uri directly. So use that. In the second activity you get your uri back with extracting the string from the extras. Ui uri = Uri.parse( .. string obtained from intent...). And.. the string obtained from intent should be the same as you put in the intent in the first activity. There you did put data.getData().toString(). – blackapps Jan 21 '21 at 13:10
  • @blackapps Allright, but how do I use those to put the data into the file? Sorry, I'm very new to this part of java, but I'm starting to understand. Also, instead of getting the string, can't I just pass the uri as a string? because that's what I'm currently doing. I get the uri, convert to string to put in a object and then convert to uri again ( I know I have to convert more times, but it is because I need the uri to other things) – Nina Jan 21 '21 at 13:12
  • intent.putExtra( "uristring", data.getData().toString()); – blackapps Jan 21 '21 at 13:13
  • I have no idea what you mean with "put the data into the file". – blackapps Jan 21 '21 at 13:14
  • @blackapps I mean create a java file with the data from the string – Nina Jan 21 '21 at 13:15
  • Which data from which string? If i'm not mistaken you use ACTION_GET_CONTENT to let the user pick a file. It seems that you want to copy that file to google drive. Ok. But about which data you are talking... i have no idea... and why you wanna create a java file (whatever that would be) i have no idea. – blackapps Jan 21 '21 at 13:17
  • Sorry... I have no idea why you posted that what comes to me as irrelevant code and having nothing to do with my remarks. – blackapps Jan 21 '21 at 13:20