Tuesday, October 23, 2012

List images in MediaStore.Images.Media

This exercise demonstrate how to list images in MediaStore.Images.Media.

List images in MediaStore.Images.Media


Modify MainActivity.java extends ListActivity.
package com.example.androidlistimages;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.ListAdapter;
import android.app.ListActivity;
import android.database.Cursor;

public class MainActivity extends ListActivity {
 
 //define source of MediaStore.Images.Media, internal or external storage
 Uri sourceUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
 //Uri sourceUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        
        String[] from = {MediaStore.MediaColumns.TITLE};
        int[] to = {android.R.id.text1};

        CursorLoader cursorLoader = new CursorLoader(
          this, 
          sourceUri, 
          null, 
          null, 
          null, 
          MediaStore.Audio.Media.TITLE);
        
        Cursor cursor = cursorLoader.loadInBackground();
        
        ListAdapter adapter = new SimpleCursorAdapter(
          this, 
          android.R.layout.simple_list_item_1, 
          cursor, 
          from, 
          to, 
          CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        setListAdapter(adapter);
    }


}


download filesDownload the files.

Remark:
Compare with my old exercise, "List audio media in MediaStore.Audio.Media" and "Start activity to play MediaStore.Video.Media by intent with action of Intent.ACTION_VIEW", both managedQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) and SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) are deprecated. See how we use CursorLoader here.

Next:
- Get path of image in MediaStore.Images.Media from SimpleCursorAdapter
- List images in MediaStore.Images.Media, with multiple selection.

Compare with:
- Query Contacts database, display in ListView.

More:
Insert the bitmap to MediaStore with title and List images title in MediaStore

No comments:

Post a Comment