title: Android get path of latest taken photo
body: <p>I'm launching the camera from my app to take a photo. It also becomes available in the gallery.</p>
  
  <p>The common issue with this, is how to know the path of the photo. The proposed solutions are:</p>
  
  <ol>
  <li>save the path yourself, and send it over using <code>EXTRA_OUTPUT</code> </li>
  <li>take the path from the last taken photo in the gallery.</li>
  </ol>
  
  <p>Solution 1 <a href="https://stackoverflow.com/questions/16348757/mediastore-extra-output-renders-data-null-other-way-to-save-photos">isn't reliable</a>.</p>
  
  <p>I'm trying to make solution 2 work, with this code:</p>
  
  <pre><code>public static String getTakenPhotoPath(Context context) {
      try {
          String[] projection = {MediaStore.Images.Media.DATA};
          Cursor cursor = context.getContentResolver().query(
                  MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                  projection, null, null, null);
  
          int column_index_data = cursor
                  .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
          cursor.moveToLast();
  
          return cursor.getString(column_index_data);
      } catch (Exception ex) {
          ex.printStackTrace();
  
          return null;
      }
  }
  </code></pre>
  
  <p>This doesn't return the path of the latest photo; it returns the previous one. Before asking for the path of the latest photo, I'm doing this:</p>
  
  <pre><code>private void addToGallery(Uri urlType, String path) {
      if (!Strings.isNullOrEmpty(path)) {
          ContentValues values = new ContentValues();
          // Add the date meta data to ensure the image is added at the front of the gallery
          values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
          values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
          values.put(MediaStore.MediaColumns.DATA, path);
  
          getContentResolver().insert(urlType, values);
  
          Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
          Uri contentUri = Uri.fromFile(new File(path));
          mediaScanIntent.setData(contentUri);
          sendBroadcast(mediaScanIntent);
      }
  }
  </code></pre>