title: Query directory with CursorLoader
body: <p>So this has been keeping me busy all day.</p>
  
  <p>I am customizing a gallery in which the user can select one or multiple images, for which I am using an existing project which makes use of a <code>CursorLoader</code>. Almost every project uses the media gallery URI to query all images on the memory. However, I only want a specific directory to be scanned and the images within displayed.</p>
  
  <p>Few lines of code which do partly what I want:</p>
  
  <pre><code>final String imagesDirectory = "/storage/sdcard0/DCIM/"
  String selection = MediaStore.Images.Media.DATA + " LIKE '" + imagesDirectory + "%'";
  cl = new CursorLoader(MultiImageChooserActivity.this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, img.toArray(new String[img.size()]), selection, null, null);
  </code></pre>
  
  <p>The selection part of this code I found on SO as well, but it also retrieves all images in subdirectories, which I do not want. A solution could be to check whether the the <code>MediaStore.Images.Media.DATA</code> column contains the same amount of slashes as <code>imagesDirectory</code>, which should work:</p>
  
  <pre><code>imagesDirectory: /storage/sdcard0/DCIM/                   -&gt; 4
  /storage/sdcard0/DCIM/photo.jpg                           -&gt; 4, direct child
  /storage/sdcard0/DCIM/subdir/otherphoto.jpg               -&gt; 5, in subdir
  </code></pre>
  
  <p>I found that in SQLite, a query like this should work (to check the occurences of the<code>/</code>):</p>
  
  <pre><code>SELECT LENGTH(col) - LENGTH(REPLACE(col, '/', ''))
  </code></pre>
  
  <p>in which <code>col</code> should be <code>MediaStore.Images.Media.DATA</code>, but as of yet I've tried a lot of different <code>selection</code> variants, but I haven't managed to filter the data. And since you can't give a <code>CursorLoader</code> a <code>rawQuery</code> (like a <code>Cursor</code>), I couldn't do that either.</p>
  
  <p>Another thing I tried was to not use <code>MediaStore.Images.Media.EXTERNAL_CONTENT_URI</code> as content URI, but rather a URI from the directory. So I tried this:</p>
  
  <pre><code>final String imagesDirectory = "/storage/sdcard0/DCIM/"
  cl = new CursorLoader(MultiImageChooserActivity.this, 
      Uri.fromFile(new File(imagesDirectory)), 
      img.toArray(new String[img.size()]), null, null, null);
  </code></pre>
  
  <p>but to no avail thusfar. </p>
  
  <p><strong>Question: How do I query all images in a directory, but not its subdirectories, using a <code>CursorLoader</code>?</strong></p>
  
  <p>I'm no hero with SQLite, queries and <code>CursorLoaders</code>, so that might explain a little. Also, I did search SO for similar questions, but there's not much to find on this particular topic. Even Googling <code>directory cursorloader</code> does not answer anything. Most result are SO posts about sorting by directory... </p>
  
  <p>Thanks in advance.</p>