Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Getting file name and path from onActivityResult

Tags:

file

android

path

What I am trying to achieve. I have a button, when the button is clicked the app opens a file picker and the user selects a file. The app then uses a FileInputStream to read the file and generates a byte[]. I have a TextView below the button which will then simply display the byte[].length. Here is the code in the button.onClick() event:

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*");

    requestFilePickerCode = parent.registerActivityResultListener(this);
    try
    {
        parent.startActivityForResult(intent, requestFilePickerCode);
    }
    catch (ActivityNotFoundException e)
    {
        Toast.makeText(task.getParent(), "Please install a file manager", Toast.LENGTH_SHORT).show();
    }

Now this code works and I have confirmed that it fires onActivityResult when the file is chosen. I simply print a Log to display data.toString() which produces the following output:

11-02 15:14:36.196 2535-2535/? V/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> content:/com.android.providers.downloads.documents/document/1

So it seems to be getting the selected file. When I run the app and I select a file it throws my custom error:

11-02 15:14:36.196 2535-2535/? E/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> File does not exist

This obviously indicates that I am not getting the file. Here is my code:

@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data)
{
    byte[] fileContent;

    // check that data is not null and assign to file if not null
    if (data != null)
    {
        Uri uri = data.getData();
        String uriString = uri.toString();
        file = new File(uriString);

        Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> " + file.toString());

        // declare file input stream and read bytes
        // write to string variable to test and test output
        FileInputStream fin = null;
        try
        {
            fin = new FileInputStream(file);
            fileContent = new byte[(int) file.length()];

            fin.read(fileContent);
            String test = new String(fileContent);
            Log.v(PebbleTypeHandlerBinary.class.toString(), "=====> " + test);
        }
        catch (FileNotFoundException e)
        {
            Toast.makeText(task.getParent(), "File not found", Toast.LENGTH_SHORT).show();
            Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> File does not exist");
        }
        catch (IOException e)
        {
            Toast.makeText(task.getParent(), "Error reading file", Toast.LENGTH_SHORT).show();
            Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error while reading the file");
        }
        finally
        {
            // close the file input stream to stop mem leaks
            try
            {
                if (fin != null)
                {
                    fin.close();
                }
            } catch (IOException e)
            {
                Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error closing the stream");
            }
        }

        Log.v(PebbleTypeHandlerBinary.class.toString(), data.toString());
    }

    return false;
}

Please can you guys review my code and help me to get this working. Any help would be appreciated.

like image 250
Owen Nel Avatar asked Oct 23 '25 04:10

Owen Nel


2 Answers

/* you can get just name and size with this method.

  • use Cursor .
  • Uri uri = data.getData();
  • get data from onActivityResult() */;

Cursor cursor = getContentResolver().query(uri, null, null, null, null);

    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
    cursor.moveToFirst();

    String name = cursor.getString(nameIndex);
    String size = Long.toString(cursor.getLong(sizeIndex));

    Toast.makeText(this, "name : "+name+"\nsize : "+size, Toast.LENGTH_SHORT).show();
like image 116
Abdelemjid Essaid Avatar answered Oct 25 '25 17:10

Abdelemjid Essaid


I managed to fix it as follows:

I used inputStream = task.getParent().getContentResolver().openInputStream(uri); to get an InputStream. Then used a ByteArrayOutputStream to write to a byte[]. See code below.

@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data)
{
    Uri uri = data.getData();
    byte[] fileContent;
    InputStream inputStream = null;

    try
    {
        inputStream = task.getParent().getContentResolver().openInputStream(uri);
        if (inputStream != null)
        {
            fileContent = new byte[(int)file.length()];
            inputStream.read(fileContent);
            fileContent = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read;
            while((read=inputStream.read(fileContent))>-1) baos.write(fileContent,0,read);
            fileContent = baos.toByteArray();
            baos.close();
            Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> Input Stream: " + inputStream);
            Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> Byte Array: " + fileContent.length);
        }
        else
        {
            Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Input Stream is null");
        }
    }
    catch (FileNotFoundException e)
    {
        Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> File not found", e);
    }
    catch (IOException e)
    {
        Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error reading file", e);
    }
    finally
    {
        if (inputStream != null)
        {
            try
            {
                inputStream.close();
            }
            catch (IOException e)
            {
                Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error reading file", e);
            }
        }
    }

    return false;
}

Thanks for all your help.

like image 32
Owen Nel Avatar answered Oct 25 '25 16:10

Owen Nel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!