title: While selecting a PDF file from recent files folder in Android 11 is giving NulllPointException:Uri
body: <p>The below shows the way how I tried and it gives me NulllPointException: Uri   While selecting a PDF file from the recent files folder in Android 11.
  Please let me know How to get pdf file path from recent folder</p>
  <pre><code>            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
                  if (Environment.isExternalStorageManager()) {
                      //todo when permission is granted
                      Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                      intent.addCategory(Intent.CATEGORY_OPENABLE);
                      intent.setType(&quot;*/*&quot;);
                      String[] mimetypes = {&quot;image/*&quot;, &quot;application/*&quot;};
                      intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
                      intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
                      startActivityForResult(intent, REQ_PDF);
                  } else {
                      //request for the permission
                      Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                      Uri uri = Uri.fromParts(&quot;package&quot;, getPackageName(), null);
                      intent.setData(uri);
                      startActivity(intent);
                  }
              } else {
                  Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                  intent.addCategory(Intent.CATEGORY_OPENABLE);
                  intent.setType(&quot;*/*&quot;);
                  String[] mimetypes = {&quot;image/*&quot;, &quot;application/*&quot;};
                  intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
                  intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
                  startActivityForResult(intent, REQ_PDF);
              }
          }
      });
  
     @SuppressLint({&quot;SetTextI18n&quot;, &quot;NewApi&quot;})
  @Override
  public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      InputStream inputStream = null;
      try {
          if (requestCode == REQ_PDF &amp;&amp; resultCode == RESULT_OK &amp;&amp; data != null) {
  
              path = data.getData();
              inputStream = this.getContentResolver().openInputStream(path);
              byte[] pdfInBytes = new byte[inputStream.available()];
              inputStream.read(pdfInBytes);
              // Toast.makeText(getContext(), &quot;&quot;+value, Toast.LENGTH_SHORT).show();
              String encodedCode = Base64.encodeToString(pdfInBytes, Base64.DEFAULT);
              filePath = PathUtil.getPathFromUri(this, path);
              // filePath= FileUtils.getPath(this,path);
              if (filePath == null) {
                  // Toast.makeText(this, &quot;null&quot;, Toast.LENGTH_SHORT).show();
                  SharedPrefMannager.showAlertDialog(InvoiceGenerationActivity.this, &quot;Alert!&quot;, &quot;Please select a file from internal storage&quot;, true);
              } else {
  
                  file = new File(filePath);
                  file_size = Integer.parseInt(String.valueOf(file.length() / 1024));
              }
              tv_attachFile.setText(&quot;Change File&quot;);
              tv_fileLocation.setVisibility(View.VISIBLE);
              tv_fileLocation.setText(filePath);
  
              //Toast.makeText(getContext(), encodedCode, Toast.LENGTH_SHORT).show();
          }
      } catch (IOException e) {
          e.printStackTrace();
          Toast.makeText(InvoiceGenerationActivity.this, &quot;Something went wrong &quot; + e, Toast.LENGTH_SHORT).show();
      }
  }
  
  
  
  
  public class PathUtil 
   {
      private static Uri contentUri = null;
       
      @SuppressLint(&quot;NewApi&quot;)
      public static String getPathFromUri(final Context context, final Uri uri) {
          // check here to is it KITKAT or new version
          final boolean isKitKatOrAbove = Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.KITKAT;
          String selection = null;
          String[] selectionArgs = null;
  
          // DocumentProvider
          if (isKitKatOrAbove &amp;&amp; DocumentsContract.isDocumentUri(context, uri)) {
              // ExternalStorageProvider
              if (isExternalStorageDocument(uri)) {
                  String docId = DocumentsContract.getDocumentId(uri);
                  String[] split = docId.split(&quot;:&quot;);
                  final String type = split[0];
                  String fullPath = getPathFromExtSD(split);
  
                  if (fullPath != &quot;&quot;) {
                      return fullPath;
                  } else {
                      return null;
                  }
                  //return getPathFromExtSD(split);
                 /* String fullPath =Environment.getExternalStorageState() + &quot;/&quot; + split[1];
                  if (fullPath != &quot;&quot;) {
                      return fullPath;
                  } else {
                      return null;
                  }*/
              }
              // DownloadsProvider
              else if (isDownloadsDocument(uri)) {
                  if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {
                      final String id;
                      Cursor cursor = null;
                      try {
                          cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
                          if (cursor != null &amp;&amp; cursor.moveToFirst()) {
                              String fileName = cursor.getString(0);
                              String path = getExternalStorageDirectory().toString() + &quot;/Download/&quot; + fileName;
                              if (!TextUtils.isEmpty(path)) {
                                  return path;
                              }
                          }
                      } finally {
                          if (cursor != null)
                              cursor.close();
                      }
                      id = DocumentsContract.getDocumentId(uri);
                      if (!TextUtils.isEmpty(id)) {
                          if (id.startsWith(&quot;raw:&quot;)) {
                              return id.replaceFirst(&quot;raw:&quot;, &quot;&quot;);
                          }
                          String[] contentUriPrefixesToTry = new String[]{
                                  &quot;content://downloads/public_downloads&quot;,
                                  &quot;content://downloads/my_downloads&quot;,
                                  &quot;content://downloads/all_downloads&quot;
                          };
                          for (String contentUriPrefix : contentUriPrefixesToTry) {
                              try {
                                  final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
  
                                  return getDataColumn(context, contentUri, null, null);
                              } catch (NumberFormatException e) {
                                  //In Android 8 and Android P the id is not a number
  
                                  return uri.getPath().replaceFirst(&quot;^/document/raw:&quot;, &quot;&quot;).replaceFirst(&quot;^raw:&quot;, &quot;&quot;);
                              }
                          }
                      }
  
                  } else {
                      final String id = DocumentsContract.getDocumentId(uri);
  
                      if (id.startsWith(&quot;raw:&quot;)) {
                          return id.replaceFirst(&quot;raw:&quot;, &quot;&quot;);
                      }
                      try {
                          if (Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.O) {
                              contentUri = ContentUris.withAppendedId(
                                      Uri.parse(&quot;content://downloads/public_downloads&quot;), Long.parseLong(id)); //public
                          }
                          if (contentUri != null) {
                              return getDataColumn(context, contentUri, null, null);
                          }
                      } catch (NumberFormatException e) {
                          e.printStackTrace();
                          Toast.makeText(context, &quot;&quot; + e, Toast.LENGTH_SHORT).show();
                      }
  
  
                  }
              }
              // MediaProvider
              else if (isMediaDocument(uri)) {
                  final String docId = DocumentsContract.getDocumentId(uri);
                  final String[] split = docId.split(&quot;:&quot;);
                  final String type = split[0];
                  Uri contentUri = null;
                  if (&quot;image&quot;.equals(type)) {
                      contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                  } else if (&quot;application&quot;.equals(type)) {
                      contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; //MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                  } else if (&quot;audio&quot;.equals(type)) {
                      contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                  }
                  selection = &quot;_id=?&quot;;
                  selectionArgs = new String[]{split[1]};
                  return getDataColumn(context, contentUri, selection,
                          selectionArgs);
  
  
              } else if (isGoogleDriveUri(uri)) {
                  return getDriveFilePath(uri, context);
              }
          } else if (&quot;content&quot;.equalsIgnoreCase(uri.getScheme())) {
  
              if (isGooglePhotosUri(uri)) {
                  return uri.getLastPathSegment();
              }
  
              if (isGoogleDriveUri(uri)) {
                  return getDriveFilePath(uri, context);
              }
              if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {
                  return getMediaFilePathForN(uri, context);
              } else {
                  return getDataColumn(context, uri, null, null);
              }
          }
          // File
          else if (&quot;file&quot;.equalsIgnoreCase(uri.getScheme())) {
              return uri.getPath();
          }
          return null;
      }
  
      private static boolean fileExists(String filePath) {
          File file = new File(filePath);
  
          return file.exists();
      }
  
      private static String getPathFromExtSD(String[] pathData) {
          String type = pathData[0];
          String relativePath = &quot;/&quot; + pathData[1];
          String fullPath = &quot;&quot;;
  
          if (&quot;primary&quot;.equalsIgnoreCase(type)) {
              fullPath = getExternalStorageDirectory() + relativePath;
              if (fileExists(fullPath)) {
                  return fullPath;
              }
          }
  
          fullPath = System.getenv(&quot;SECONDARY_STORAGE&quot;) + relativePath;
          if ((null == fullPath) || (fullPath.length() == 0)) {
              fullPath = System.getenv(&quot;SECONDARY_SDCARD_STORAGE&quot;);
              return fullPath;
          }
        /*  if (fileExists(fullPath)) {
              return fullPath;
          }*/
  
          fullPath = System.getenv(&quot;EXTERNAL_STORAGE&quot;) + relativePath;
          if ((null == fullPath) || (fullPath.length() == 0)) {
              fullPath = System.getenv(&quot;EXTERNAL_SDCARD_STORAGE&quot;);
              return fullPath;
          }
       /*   if (fileExists(fullPath)) {
              return fullPath;
          }*/
  
          return fullPath;
      }
  
      private static String getDriveFilePath(Uri uri, Context context) {
          Uri returnUri = uri;
          Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
          InputStream inputStream = null;
          FileOutputStream outputStream = null;
          int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
          int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
          returnCursor.moveToFirst();
          String name = (returnCursor.getString(nameIndex));
          String size = (Long.toString(returnCursor.getLong(sizeIndex)));
          File file = new File(context.getCacheDir(), name);
          try {
              inputStream = context.getContentResolver().openInputStream(uri);
              outputStream = new FileOutputStream(file);
              int read = 0;
              int maxBufferSize = 1 * 1024 * 1024;
              int bytesAvailable = inputStream.available();
  
              //int bufferSize = 1024;
              int bufferSize = Math.min(bytesAvailable, maxBufferSize);
  
              final byte[] buffers = new byte[bufferSize];
              while ((read = inputStream.read(buffers)) != -1) {
                  outputStream.write(buffers, 0, read);
              }
              Log.e(&quot;File Size&quot;, &quot;Size &quot; + file.length());
              inputStream.close();
              outputStream.close();
              Log.e(&quot;File Path&quot;, &quot;Path &quot; + file.getPath());
              Log.e(&quot;File Size&quot;, &quot;Size &quot; + file.length());
          } catch (Exception e) {
              Log.e(&quot;Exception&quot;, e.getMessage());
          } finally {
              if (inputStream != null) {
                  try {
                      inputStream.close();
                  } catch (Exception e) {
                  }
              }
  
              if (outputStream != null) {
                  try {
                      outputStream.close();
                  } catch (Exception e) {
                  }
              }
          }
          return file.getPath();
      }
  
      private static String getMediaFilePathForN(Uri uri, Context context) {
          Uri returnUri = uri;
          Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
  
          int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
          int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
          returnCursor.moveToFirst();
          String name = (returnCursor.getString(nameIndex));
          String size = (Long.toString(returnCursor.getLong(sizeIndex)));
          File file = new File(context.getFilesDir(), name);
          try {
              InputStream inputStream = context.getContentResolver().openInputStream(uri);
              FileOutputStream outputStream = new FileOutputStream(file);
              int read = 0;
              int maxBufferSize = 1 * 1024 * 1024;
              int bytesAvailable = inputStream.available();
  
              //int bufferSize = 1024;
              int bufferSize = Math.min(bytesAvailable, maxBufferSize);
  
              final byte[] buffers = new byte[bufferSize];
              while ((read = inputStream.read(buffers)) != -1) {
                  outputStream.write(buffers, 0, read);
              }
              Log.e(&quot;File Size&quot;, &quot;Size &quot; + file.length());
              inputStream.close();
              outputStream.close();
              Log.e(&quot;File Path&quot;, &quot;Path &quot; + file.getPath());
              Log.e(&quot;File Size&quot;, &quot;Size &quot; + file.length());
          } catch (Exception e) {
              Log.e(&quot;Exception&quot;, e.getMessage());
          }
          return file.getPath();
      }
  
  
      private static String getDataColumn(Context context, Uri uri,
                                          String selection, String[] selectionArgs) {
          Cursor cursor = null;
          final String column = &quot;_data&quot;;
          final String[] projection = {column};
  
          try {
  
              cursor = context.getContentResolver().query(uri, projection, selection,
                      selectionArgs, null);
  
              if (cursor != null &amp;&amp; cursor.moveToFirst()) {
                  final int index = cursor.getColumnIndexOrThrow(column);
                  return cursor.getString(index);
              }
          } catch (Exception e) {
              //   Toast.makeText(context, &quot;Something went wrong&quot;, Toast.LENGTH_SHORT).show();
          } finally {
              if (cursor != null)
                  cursor.close();
          }
  
          return null;
      }
  
      private static boolean isExternalStorageDocument(Uri uri) {
          return &quot;com.android.externalstorage.documents&quot;.equals(uri.getAuthority());
      }
  
      private static boolean isDownloadsDocument(Uri uri) {
          return &quot;com.android.providers.downloads.documents&quot;.equals(uri.getAuthority());
      }
  
      private static boolean isMediaDocument(Uri uri) {
          return &quot;com.android.providers.media.documents&quot;.equals(uri.getAuthority());
      }
  
      private static boolean isGooglePhotosUri(Uri uri) {
          return &quot;com.google.android.apps.photos.content&quot;.equals(uri.getAuthority());
      }
  
      private static boolean isGoogleDriveUri(Uri uri) {
          return &quot;com.google.android.apps.docs.storage&quot;.equals(uri.getAuthority()) || &quot;com.google.android.apps.docs.storage.legacy&quot;.equals(uri.getAuthority());
      }
  
  }
  </code></pre>
  <p>Any help would be appreciated. I am testing on an android R device. Why is it that when selecting the file from a RECENT section in the file browser I am not getting any file path meanwhile selecting the same file in the STORAGE section is returning file path?</p>