Skip to content

Instantly share code, notes, and snippets.

@danielmai
Created July 30, 2015 05:53
Show Gist options
  • Save danielmai/39eb3156ebf1b71817c7 to your computer and use it in GitHub Desktop.
Save danielmai/39eb3156ebf1b71817c7 to your computer and use it in GitHub Desktop.
MediaStore loader sortOrder example
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
public static final int MEDIASTORE_LOADER = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLoaderManager().initLoader(MEDIASTORE_LOADER, null, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = new String[] {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.TITLE
};
// Try changing the sort order here to ASC, filtering the logs by "MainActivity" for convenience.
// You'll notice that the _ID value order changes depending on whether the sortOrder is ASC or DESC.
String sortOrder = MediaStore.Images.ImageColumns._ID + " DESC";
return new CursorLoader(this,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
while (cursor.moveToNext()) {
int _id = cursor.getInt(0);
String title = cursor.getString(1);
Log.d(LOG_TAG, _id + " " + title);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment