How do I get the Uri from a file that is in the internal memory in Android

0

What I want is to be able to take out the Uri to pass it to another function but it does not work any way

I am creating an app that uses the OneDrive sdk, which provides this example example of uploading files

private void upload(final int requestCode) {
    //mensajeToast("Entro al uploat "+mItemId);
    final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setType(ACCEPTED_UPLOAD_MIME_TYPES);
    startActivityForResult(intent, requestCode);
}

When you receive the object in the onActivityResult

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {

    final BaseApplication application = (BaseApplication) this.getApplication();

    final IOneDriveClient oneDriveClient = application.getOneDriveClient();

    if (requestCode == REQUEST_CODE_SIMPLE_UPLOAD
            && data != null
            && data.getData() != null
            && data.getData().getScheme().equalsIgnoreCase(SCHEME_CONTENT)) {

        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setTitle(R.string.upload_in_progress_title);
        dialog.setMessage(getString(R.string.upload_in_progress_message));
        dialog.setIndeterminate(false);
        dialog.setCancelable(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setProgressNumberFormat(getString(R.string.upload_in_progress_number_format));
        dialog.show();
        final AsyncTask<Void, Void, Void> uploadFile = new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(final Void... params) {

                try {

                    final ContentResolver contentResolver = getContentResolver();
                    final ContentProviderClient contentProvider = contentResolver.acquireContentProviderClient(data.getData());
                    final byte[] fileInMemory = FileContent.getFileBytes(contentProvider, data.getData());
                    contentProvider.release();

                    // Repara el nombre del archivo (necesario para las fotos del carrete de la cámara, etc.)
                    final String filename = FileContent.getValidFileName(contentResolver, data.getData());

                    final Option option = new QueryOption("@name.conflictBehavior", "fail");
                    oneDriveClient
                            .getDrive()
                            .getItems(mItemId)
                            .getChildren()
                            .byId(filename)
                            .getContent()
                            .buildRequest(Collections.singletonList(option))
                            .put(fileInMemory,
                                    new IProgressCallback<Item>() {
                                        @Override
                                        public void success(final Item item) {
                                            dialog.dismiss();
                                              mensajeToast("Archivo subido "+item.name);

                                            //refresh();
                                        }

                                        @Override
                                        public void failure(final ClientException error) {
                                            dialog.dismiss();
                                            if (error.isError(OneDriveErrorCodes.NameAlreadyExists)) {
                                                mensajeToast("Hay conflicto con el nombre de otro archivo ");
                                            } else {
                                                mensajeToast(application.toString());
                                                mensajeToast(error.getMessage());
                                            }
                                        }

                                        @Override
                                        public void progress(final long current, final long max) {
                                            dialog.setProgress((int) current);
                                            dialog.setMax((int) max);
                                        }
                                    });
                } catch (final Exception e) {
                    Log.e(getClass().getSimpleName(), e.getMessage());
                    Log.e(getClass().getSimpleName(), e.toString());
                }
                return null;
            }
        };
        uploadFile.execute();
    }
}

All that works well

Now what I want is to upload that file without giving you the possibility to choose the file if I choose it and upload it

My code is like this

private void subirCopia(){

    //guardo un archivo de prueba para subirlo
    OutputStreamWriter escritor, escrito = null;
    String nomb = "1002";
    try {
        //creo la cabezera con mode_apped
        escrito = new OutputStreamWriter(openFileOutput(nomb + ".txt", Context.MODE_APPEND));
        escrito.write("Para preparar la importacion de instorial" + "\r\n");
        escrito.close();

        Toast.makeText(this, "REGISTRADO EL TXT PRUEBA", Toast.LENGTH_SHORT).show();
    } catch (Exception ex) {
        Toast.makeText(this, "Instorial no pudo ser registrado", Toast.LENGTH_SHORT).show();
    }

    //Inicio el codigo para subir
    final BaseApplication application = (BaseApplication) this.getApplication();
    final IOneDriveClient oneDriveClient = application.getOneDriveClient();

    String name = "1002";
    String conten = "content"; //ni idea pero lo tiene el otro codigo al empezar el Uri, creo que es para comprobar que si es el archivo que se pidio
    //este es el uri que recogio el otro codigo con el onActivityResult en el bloque de codigo recogido de la memoria externa
    //final Uri ruta = Uri.parse("content://com.android.externalstorage.documents./document/primary%3APrestaCOP%2F1002.txt");
    File data = Environment.getDataDirectory(); //enlace a la memoria interna
    String origen = data+"/data/com.example.andresperezmelo.onedriveejemploanalizes/files/" + name + ".txt";

    final File archivo = new File(data, origen);

    final Uri ruta = Uri.fromFile(archivo);

    mensajeToast("Uri del archivo "+ruta);

    Log.d("entro linea 426","426 linea");
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setTitle(R.string.upload_in_progress_title);
    dialog.setMessage(getString(R.string.upload_in_progress_message));
    dialog.setIndeterminate(false);
    dialog.setCancelable(false);
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    dialog.setProgressNumberFormat(getString(R.string.upload_in_progress_number_format));
    dialog.show();
    final AsyncTask<Void, Void, Void> uploadFile = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(final Void... params) {

            try {
                  Log.d("entro linea 73","ruta "+ruta);
                final ContentResolver contentResolver = getContentResolver();
                Log.i("Entro a la linea 475","ruta "+ruta);
                final ContentProviderClient contentProvider = contentResolver.acquireContentProviderClient(ruta);
                Log.i("Entro a la linea 477","ruta "+ruta);
                final byte[] fileInMemory = FileContent.getFileBytes(contentProvider, ruta);
                Log.i("Entro a la linea 479","ruta "+ruta);
                contentProvider.release();
                         Log.i("Entro a la linea 481","ruta "+ruta);
                // Repara el nombre del archivo (necesario para las fotos del carrete de la cámara, etc.)
                final String filename = FileContent.getValidFileName(contentResolver, ruta);

                final Option option = new QueryOption("@name.conflictBehavior", "fail");
                oneDriveClient
                        .getDrive()
                        .getItems(mItemId)
                        .getChildren()
                        .byId(filename)
                        .getContent()
                        .buildRequest(Collections.singletonList(option))
                        .put(fileInMemory,
                                new IProgressCallback<Item>() {
                                    @Override
                                    public void success(final Item item) {
                                        dialog.dismiss();
                                        mensajeToast("Archivo subido "+item.name);

                                        //refresh();
                                    }

                                    @Override
                                    public void failure(final ClientException error) {
                                        dialog.dismiss();
                                        if (error.isError(OneDriveErrorCodes.NameAlreadyExists)) {
                                            mensajeToast("Hay conflicto con el nombre de otro archivo ");
                                        } else {
                                            mensajeToast(application.toString());
                                            mensajeToast(error.getMessage());
                                        }
                                    }

                                    @Override
                                    public void progress(final long current, final long max) {
                                        dialog.setProgress((int) current);
                                        dialog.setMax((int) max);
                                    }
                                });
            } catch (final Exception e) {
                Log.e(getClass().getSimpleName(), e.getMessage());
                Log.e(getClass().getSimpleName(), e.toString());
                Log.i("Falla.......... 490","fallo ......."+e.toString());
            }
            return null;
        }
    };
    uploadFile.execute();
}

This is the error that occurs when trying to run the FileContent class and the getFileBytes method

java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.ParcelFileDescriptor android.content.ContentProviderClient.openFile(android.net.Uri, java.lang.String)' on a null object reference

this is the code of the method

static byte[] getFileBytes(final ContentProviderClient contentProvider, final Uri data)
        throws IOException, RemoteException {
   final ParcelFileDescriptor descriptor = contentProvider.openFile(data, "r");
   if (descriptor == null) {
       throw new RuntimeException("\n" + "No se puede obtener el archivo ParcelFileDescriptor");
   }

   final int fileSize = (int) descriptor.getStatSize();
   return getFileBytes(contentProvider, data, 0, fileSize);
}

I would like to know how I can collect that and upload the files that I try to upload are .txt and .db and they are in the internal memory of the phone.

Thank you if anyone can help me

Annex captures of the telephone and pc

    
asked by anDres 16.02.2018 в 18:37
source

1 answer

0

The value of ContentProvider is null, apparently it is because data has no value:

final ContentProviderClient contentProvider = contentResolver.acquireContentProviderClient(data.getData());
                    final byte[] fileInMemory = FileContent.getFileBytes(contentProvider, data.getData());

Although you have a validation, this would not be done if any of the elements is not met:

if (requestCode == REQUEST_CODE_SIMPLE_UPLOAD
            && data != null
            && data.getData() != null
            && data.getData().getScheme().equalsIgnoreCase(SCHEME_CONTENT))

Ensures to send correctly the value of data

    
answered by 16.02.2018 в 19:34