How to convert a content Uri into a File

Viewed 11480

I know there are a ton of questions about this exact topic, but after spending two days reading and trying them, none seamed to fix my problem.

This is my code:

I launch the ACTION_GET_CONTENT in my onCreate()

Intent selectIntent = new Intent(Intent.ACTION_GET_CONTENT);
        selectIntent.setType("audio/*");
        startActivityForResult(selectIntent, AUDIO_REQUEST_CODE);

retrieve the Uri in onActivityResult()

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AUDIO_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            if ((data != null) && (data.getData() != null)) {
                audio = data.getData();
            }
        }
    }

pass the Uri to another activity and retrieve it

Intent debugIntent = new Intent(this, Debug.class);
            Bundle bundle = new Bundle();
            bundle.putString("audio", audio.toString());
            debugIntent.putExtras(bundle);
            startActivity(debugIntent);

Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        audio = Uri.parse((String) bundle.get("audio"));

The I have implemented this method based on another SO answer. To get the actual Path of the Uri

public static String getRealPathFromUri(Activity activity, Uri contentUri) {
        String[] proj = { MediaStore.Audio.Media.DATA };
        Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

and in the Debug activity's onCreate() I try to generate the file:

File audioFile = new File(getRealPathFromUri(this, audio));

This is how the error looks like:

Caused by: java.lang.NullPointerException at java.io.File.(File.java:262) at com.dancam.lietome.Debug.onCreate(Debug.java:35)

When I run the app I get a NPE on this last line. The audio Uri, isn't NULL though so I don't understand from what it is caused.

I'd really appreciate if you helped me out.

This is the library I'm trying to work with.

Note: I know exactly what NPE is, but even debugging I couldn't figure out from what it is caused in this specific case.

3 Answers

I ran into same problem for Android Q, so I end up creating a new file and use input stream from content to fill that file Here's How I do it in kotlin:

private var pdfFile: File? = null

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                when (requestCode) {
                    REQUEST_CODE_DOC -> {
                        data.data?.let {
                            if (it.scheme.equals("content")) {
                                val pdfBytes =
                                    (contentResolver?.openInputStream(it))?.readBytes()
                                pdfFile = File(
                                    getExternalFilesDir(null),
                                    "Lesson ${Calendar.getInstance().time}t.pdf"
                                )

                                if (pdfFile!!.exists())
                                    pdfFile!!.delete()
                                try {
                                    val fos = FileOutputStream(pdfFile!!.path)
                                    fos.write(pdfBytes)
                                    fos.close()
                                } catch (e: Exception) {
                                    Timber.e("PDF File", "Exception in pdf callback", e)
                                }
                            } else {
                                pdfFile = it.toFile()
                            }

                        }
                    }
                }
            }
        }
    }
Related