how to show thumbimage in gridview from sdcard - android

iam using following code it is not displaying thumb image in gridview but displaying in emulator pls suggest me how to show thumb image in gridview from sdcard
String[] projection = {MediaStore.Images.Media._ID};
final String orderBy = MediaStore.Images.Media._ID+" DESC";
// Create the cursor pointing to the SDCard
Cursor cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
orderBy);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int size = cursor.getCount();
// If size is 0, there are no images on the SD Card.
if (size == 0) {
//No Images available, post some message to the user
}
int imageID = 0;
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
imageID = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 86, 96, true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}

Try this code, it will work
package com.video;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class StartActivity extends Activity {
//set constants for MediaStore to query, and show videos
private final static Uri MEDIA_EXTERNAL_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private GridView _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
protected Context _context;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_context = getApplicationContext();
setContentView(R.layout.main);
//set GridView for gallery
_gallery = (GridView) findViewById(R.id.videoGrdVw);
//set default as external/sdcard uri
_contentUri = MEDIA_EXTERNAL_CONTENT_URI;
//initialize the videos uri
//showToast(_contentUri.getPath());
initVideosId();
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(_context));
_gallery.setOnItemClickListener(_itemClickLis);
}
private AdapterView.OnItemClickListener _itemClickLis = new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, long id)
{
// Now we want to actually get the data location of the file
String [] proj={MEDIA_DATA};
// We request our cursor again
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
// We want to get the column index for the data uri
int count = _cursor.getCount();
//
_cursor.moveToFirst();
//
_columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
// Lets move to the selected item in the cursor
_cursor.moveToPosition(position);
// And here we get the filename
String filename = _cursor.getString(_columnIndex);
//*********** You can do anything when you know the file path :-)
showToast(filename);
//
}
};
private void initVideosId() {
try
{
//Here we set up a string array of the thumbnail ID column we want to get back
String [] proj={_ID};
// Now we create the cursor pointing to the external thumbnail store
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int count= _cursor.getCount();
// We now get the column index of the thumbnail id
_columnIndex = _cursor.getColumnIndex(_ID);
//initialize
_videosId = new int[count];
//move position to first element
_cursor.moveToFirst();
for(int i=0;i<count;i++)
{
int id = _cursor.getInt(_columnIndex);
//
_videosId[i]= id;
//
_cursor.moveToNext();
//
}
}catch(Exception ex)
{
showToast(ex.getMessage().toString());
}
}
protected void showToast(String msg)
{
Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
//
private class VideoGalleryAdapter extends BaseAdapter
{
public VideoGalleryAdapter(Context c)
{
_context = c;
}
public int getCount()
{
return _videosId.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgVw= new ImageView(_context);;
try
{
if(convertView!=null)
{
imgVw= (ImageView) convertView;
}
imgVw.setImageBitmap(getImage(_videosId[position]));
imgVw.setLayoutParams(new GridView.LayoutParams(96, 96));
imgVw.setPadding(8, 8, 8, 8);
}
catch(Exception ex)
{
System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +", "+ ex.getMessage());
}
return imgVw;
}
// Create the thumbnail on the fly
private Bitmap getImage(int id) {
Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(
getContentResolver(),
id, MediaStore.Video.Thumbnails.MICRO_KIND, null);
return thumb;
}
}
}

Related

BitmapFactory decodeFile FileNotFoundException

I have an app where you can select images from the gallery or Photos folder on the device. The selected file's paths are stored in an Intent so they can be passed around between Activities. I access the paths via intent.getDataString().
Once i have all the selected paths to the images, i store them in an ArrayList and pass that to an ImageAdapter, to display in a ListView.
I'm geting a FileNotFoundException, Has anyone any ideas why?
Thanks in advance
Matt.
import java.util.ArrayList;
import uk.co.mobilewebexpert.infowrapsynclibrary.ApplicationObj;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class QueuedImagesActivity extends Activity {
private static final String TAG = QueuedImagesActivity.class.getSimpleName();
private ImageAdapter adapter;
private ListView imageList;
ApplicationObj appObj;
Intent[] photos;
String path;
private ArrayList<String> imagePaths= new ArrayList<String>(); // Edit your code here..
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.image_listview);
appObj = (ApplicationObj) getApplication();
boolean includeBeingProcessed = true;
try {
photos = appObj.getQueuedPhotos(includeBeingProcessed);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < photos.length; i++){
path = photos[i].getDataString();
imagePaths.add(path);
Log.e(TAG, "path in QueuedImagesActivity = " + path);
}
imageList= (ListView) findViewById(R.id.listView1);
adapter= new ImageAdapter(getBaseContext(), imagePaths);
imageList.setAdapter(adapter);
}
}
.
import java.util.ArrayList;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private static final String TAG = ImageAdapter.class.getSimpleName();
static class RowItemHolder{
ImageView imageView;
}
private Context context;
private ArrayList<String> imagePaths= new ArrayList<String>();
public ImageAdapter(Context baseContext, ArrayList<String> imagePaths) {
// TODO Auto-generated constructor stub
this.context= baseContext;
this.imagePaths= imagePaths;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imagePaths.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
view= convertView;
RowItemHolder holder = null;
if(view== null){
LayoutInflater in =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = in.inflate(R.layout.image_view, parent, false);
holder= new RowItemHolder();
holder.imageView=(ImageView) view.findViewById(R.id.imageView1);
view.setTag(holder);
} else{
holder = (RowItemHolder) view.getTag();
}
//Edit the code here according to you needs..
//like creating option and converting to Bitmap,
//or you can do this job in the main activity.
//holder.imageView.setImageResource(imagePaths.get(position));
Log.e(TAG, "imagePaths.get(position) = " + imagePaths.get(position));
holder.imageView.setImageBitmap(BitmapFactory.decodeFile(imagePaths.get(position)));
return view;
}
}
.
07-02 07:51:33.941: E/QueuedImagesActivity(22700): path in QueuedImagesActivity = content://media/external/images/media/7496
07-02 07:51:33.951: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.961: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
07-02 07:51:33.971: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.971: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
07-02 07:51:33.981: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.981: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
07-02 07:51:33.991: E/ImageAdapter(22700): imagePaths.get(position) = content://media/external/images/media/7496
07-02 07:51:33.991: E/BitmapFactory(22700): Unable to decode stream: FileNotFoundException
The path you are getting is not real path of the Image it is a Uri.If you want to set it it ImageView set it like
imageView.setImageURI(Uri.parse(imagePaths.get(position)));
or
get the Real path by passing your URI and set it to ImageView
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
For more check here Uri to path conversion
It causes because intent.getDataString() returns the uri string. Use intent.getData().getPath() instead.
Try this way,hope this will help you to solve your problem.
public String getAbsolutePath(Uri uri) {
if(Build.VERSION.SDK_INT >= 19){
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA };
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}else{
return null;
}
}else{
String[] projection = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
Your problem is in appObj.getQueuedPhotos- it isn't returning filenames, its returning URIs, decodeFile expects a path. You can, for this case, do a quick string manipulation and remove the content:/ from the front, but you're better off fixing the URIs in your getQueuedPhotos function
content://media/external/images/media/7496 is not the actual location of the stored file, but just the Uri, hence android can't find the file on the specified path. However, you can use the URI to get the absolute path of the file and use that path when decoding.
Use this method to the get the absolute path :
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
From : https://stackoverflow.com/a/3414749/1239966
Check for the inputstream, you are passing just a URI.
BitmapFactory.decodeFile(imagePaths.get(position));
Hence the file is not found, get the absolute path of the Image and pass it over.

How to list all videos from specific folder in android

I am working on video recording application.I want to list the videos which I would be stored in particular folder.By the following code,I can able to fetch all videos from mobile.But i need to list the videos from particular folder.Can anyone guide me please.Thanks in Advance
public class VideoListActivity extends Activity {
private Cursor videocursor;
private int video_column_index;
ListView videolist;
int count;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_list);
init_phone_video_grid();
}
private void init_phone_video_grid() {
System.gc();
String[] proj = { MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.SIZE };
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.listView1);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
System.gc();
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videocursor.moveToPosition(position);
String filename = videocursor.getString(video_column_index);
Intent intent = new Intent(VideoListActivity.this, Viewvideo.class);
intent.putExtra("videofilename", filename);
startActivity(intent);
}
};
public class VideoAdapter extends BaseAdapter {
private Context vContext;
public VideoAdapter(Context c) {
vContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
TextView tv = new TextView(vContext.getApplicationContext());
String id = null;
if (convertView == null) {
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videocursor.moveToPosition(position);
id = videocursor.getString(video_column_index);
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videocursor.moveToPosition(position);
id += " Size(KB):" + videocursor.getString(video_column_index);
ImageView iv = new ImageView(vContext);
ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, position, MediaStore.Video.Thumbnails.MICRO_KIND, options);
iv.setImageBitmap(curThumb);
tv.setText(id);
} else
tv = (TextView) convertView;
return tv;
}
}
}
Try the following code:
public static ArrayList<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files;
files = parentDir.listFiles();
if (files != null) {
for (File file : files) {
if (file.getName().endsWith(".mp4") ||
file.getName().endsWith(".gif")) {
if (!inFiles.contains(file)) inFiles.add(file);
if (!inFiles.contains(file)) inFiles.add(file);
}
}
}
return inFiles;
}
Use :
private static final String WHATSAPP_STATUSES_LOCATION =
"/storage/emulated/0/yourfoldername";
getListFiles(new File(WHATSAPP_STATUSES_LOCATION));
use this code :
package com.vt.soc;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
//set constants for MediaStore to query, and show videos
private final static Uri MEDIA_EXTERNAL_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private GridView _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
String filename;
int flag = 0;
protected Context _context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_context = getApplicationContext();
setContentView(R.layout.activity_main);
//set GridView for gallery
_gallery = (GridView) findViewById(R.id.videoGrdVw);
//set default as external/sdcard uri
_contentUri = MEDIA_EXTERNAL_CONTENT_URI;
initVideosId();
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(_context));
_gallery.setOnItemClickListener(_itemClickLis);
flag = 1;
}
private AdapterView.OnItemClickListener _itemClickLis = new OnItemClickListener()
{
#SuppressWarnings({ "deprecation", "unused", "rawtypes" })
public void onItemClick(AdapterView parent, View v, int position, long id)
{
// Now we want to actually get the data location of the file
String [] proj={MEDIA_DATA};
// We request our cursor again
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
MEDIA_DATA + " like ? ", // WHERE clause; which rows to return (all rows)
new String[] {"%Movies%"}, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
// We want to get the column index for the data uri
int count = _cursor.getCount();
//
_cursor.moveToFirst();
//
_columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
// Lets move to the selected item in the cursor
_cursor.moveToPosition(position);
// And here we get the filename
filename = _cursor.getString(_columnIndex);
//*********** You can do anything when you know the file path :-)
showToast(filename);
Intent i = new Intent(MainActivity.this, Player.class);
i.putExtra("videoPath", filename);
startActivity(i);
//
}
};
#SuppressWarnings("deprecation")
private void initVideosId() {
try
{
//Here we set up a string array of the thumbnail ID column we want to get back
String [] proj={_ID};
// Now we create the cursor pointing to the external thumbnail store
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
MEDIA_DATA + " like ? ", // WHERE clause; which rows to return (all rows)
new String[] {"%Movies%"}, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int count= _cursor.getCount();
// We now get the column index of the thumbnail id
_columnIndex = _cursor.getColumnIndex(_ID);
//initialize
_videosId = new int[count];
//move position to first element
_cursor.moveToFirst();
for(int i=0;i<count;i++)
{
int id = _cursor.getInt(_columnIndex);
//
_videosId[i]= id;
//
_cursor.moveToNext();
//
}
}catch(Exception ex)
{
showToast(ex.getMessage().toString());
}
}
protected void showToast(String msg)
{
Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
//
private class VideoGalleryAdapter extends BaseAdapter
{
public VideoGalleryAdapter(Context c)
{
_context = c;
}
public int getCount()
{
return _videosId.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgVw= new ImageView(_context);;
try
{
if(convertView!=null)
{
imgVw= (ImageView) convertView;
}
imgVw.setImageBitmap(getImage(_videosId[position]));
imgVw.setLayoutParams(new GridView.LayoutParams(200, 200));
imgVw.setPadding(8, 8, 8, 8);
}
catch(Exception ex)
{
System.out.println("MainActivity:getView()-135: ex " + ex.getClass() +", "+ ex.getMessage());
}
return imgVw;
}
// Create the thumbnail on the fly
private Bitmap getImage(int id) {
Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(
getContentResolver(),
id, MediaStore.Video.Thumbnails.MICRO_KIND, null);
return thumb;
}
}
}
and add permission to manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
A bit late but posting for future viewers
Uri uri= MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String condition=MediaStore.Video.Media.DATA +" like?";
String[] selectionArguments=new String[]{"%FolderPath%"};
String sortOrder = MediaStore.Video.Media.DATE_TAKEN + " DESC";
String[] projection = { MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,projection, condition, selectionArguments, sortOrder);
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int pathColumn=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if(cursor!=null){
ContentResolver resolver = getApplicationContext().getContentResolver();
while(cursor3.moveToNext()){
String filePath=cursor.getString(pathColumn);
int id = cursor.getInt(idColumn );
Bitmap thumbNail = bitmap=MediaStore.Video.Thumbnails.getThumbnail(resolver, imageID,
MediaStore.Video.Thumbnails.MICRO_KIND, null);
}
}
use this code`
String path = Environment.getExternalStorageDirectory().toString()+"/Your Folder/";`
File f = new File(path);
File file[] = f.listFiles();
for (int i=0; i < file.length; i++)
{
Log.d("Files", "FileName:" + file[i].getName());
}
above code give you all file from the folder ,after you can separate
using it's extension

Display All Song From the SD card Genre Wise

I am Doing Musicplayer Application. and want to show All the Songs with respect to its Genre. if possible then please give me some hint for that. i able to display all the Song With Respect to Artist and Album but Facing Problem While Going For Genre Wise Song. my out put is displaying all the Songs in Each genre catagory. it is not saprating the Song According to genre. Mycode is Below.
LocalGenre.java
package com.PageViewerTilesDemo.src;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Window;
import android.widget.ExpandableListView;
import android.widget.TextView;
public class LocanGenre extends Activity {
ExpandableListView listLocalArtists;
TextView txttitle;
Cursor musiccursor, musiccursor1;
int music_column_index, music_column_index1;
int count, count1;
ArrayList<String> genresName = new ArrayList<String>();
ArrayList<String> genreID = new ArrayList<String>();
ArrayList<Integer> albumID = new ArrayList<Integer>();
ArrayList<String> numberOFSongs = new ArrayList<String>();
ArrayList<String> artistName = new ArrayList<String>();
ArrayList<String> path = new ArrayList<String>();
ArrayList<String> path12 = new ArrayList<String>();
ArrayList<ArrayList<String>> pathDisplay = new ArrayList<ArrayList<String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.localartists);
txttitle = (TextView) findViewById(R.id.title);
txttitle.setText("Genres");
listLocalArtists = (ExpandableListView) findViewById(R.id.listView1);
init_phone_music_grid();
listLocalArtists.setAdapter(new ExpandableListGenreAdapter(this, path, genresName,
genresName, pathDisplay,albumID));
}
private void init_phone_music_grid() {
// TODO Auto-generated method stub
System.gc();
String[] proj = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ALBUM_ID};
musiccursor1 = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null,
null);
count1 = musiccursor1.getCount();
if (count1 > 0) {
musiccursor1.moveToFirst();
do {
music_column_index1 = musiccursor1
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
String filename0 = musiccursor1.getString(music_column_index1);
path.add(filename0);
Log.i("LocalGenres ", "Path Main" + path);
music_column_index1 = musiccursor1
.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
String filename123 = musiccursor1
.getString(music_column_index1);
path12.add(filename123);
Log.i("LocalGenre", "Media ID " + path12);
music_column_index1 = musiccursor1
.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
int filename1 = musiccursor1.getInt(music_column_index1);
albumID.add(filename1);
Log.i("LOCAL Genres!!!", " ALBUM ID" + albumID);
} while (musiccursor1.moveToNext());
}
String[] projection = { MediaStore.Audio.Genres._ID,
MediaStore.Audio.Genres.NAME};
musiccursor = managedQuery(
MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, projection, null,
null, null);
genresName.clear();
count = musiccursor.getCount();
if (count > 0) {
musiccursor.moveToFirst();
do {
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
String filename = musiccursor.getString(music_column_index);
if(!genreID.contains(filename))
{
genreID.add(filename);
}
Log.i("Local Genres ", "Genre ID" + genreID);
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
String filename1 = musiccursor.getString(music_column_index);
if(!genresName.contains(filename1))
{
genresName.add(filename1);
}
Log.i("Local Genres ", "Genres Name " + genresName);
/*
* music_column_index = musiccursor
* .getColumnIndexOrThrow(MediaStore.Audio.Genres._COUNT);
*
* String filename3 = musiccursor.getString(music_column_index);
* artistName.add(filename3);
*
* Log.i("Local Albums ", "Album ID for Gen " + artistName);
*/
} while (musiccursor.moveToNext());
}
for (int j = 0; j < genreID.size(); j++) {
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i < path12.size(); i++) {
Log.i("EEEEEE", "Inside If path12.get(i) :"+path12.get(i));
Log.i("EEEEEE", "Inside If genreID.get(j) :"+genreID.get(j));
Log.i("EEEEEE", "Inside If Integer.parseInt(path12.get(i)) :"+Integer.parseInt(path12.get(i)));
Log.i("EEEEEE", "Inside If j : "+j);
if (path12.get(i).equalsIgnoreCase(genreID.get(j)) || Integer.parseInt(path12.get(i))>j) {
Log.i("EEEEEE", "Inside If");
arr.add(path.get(i));
}
else
Log.i("xxxxxxx", "Inside else");
arr.add(path.get(i));
}
Log.i("EEEEEE", "Inside outerloop " + arr);
pathDisplay.add(arr);
}
}
}
ExpandableListGenreAdapter.java
package com.PageViewerTilesDemo.src;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ExpandableListGenreAdapter extends BaseExpandableListAdapter{
private Context context;
private ArrayList<String> artist;
private ArrayList<String> genres;
private ArrayList<ArrayList<String>> children;
public ArrayList<String> pathmain ;
public ArrayList<Integer> genresID;
public ArrayList<Integer> albumID;
public ExpandableListGenreAdapter(Context context, ArrayList<String> path, ArrayList<String> groups,ArrayList<String> artist,
ArrayList<ArrayList<String>> children, ArrayList<Integer> albumID) {
this.context = context;
this.genres = groups;
this.artist = artist;
this.pathmain = path;
this.children = children;
this.albumID=albumID;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return children.get(groupPosition).get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
/*public Bitmap getAlbumart(int album_id)
{
Bitmap bm = null;
try
{
final Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
ParcelFileDescriptor pfd = context.getContentResolver()
.openFileDescriptor(uri, "r");
if (pfd != null)
{
FileDescriptor fd = pfd.getFileDescriptor();
bm = BitmapFactory.decodeFileDescriptor(fd);
}
} catch (Exception e) {
}
return bm;
}*/
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final String vehicle = (String) getChild(groupPosition, childPosition);
Log.i("ExpandableListAdapter", "Group Position "+groupPosition);
Log.i("ExpandableListAdapter", "Vehicle "+vehicle);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.tvChild);
ImageView imageview1=(ImageView)convertView.findViewById(R.id.ImageView01);
// bm=getAlbumart(albumids.get(1));
// Log.i("LIST ADAPTER","###################ALBUM IDS "+albumids.get(0)+"BITMAPPPPP###"+bm);
// imageview1.setImageBitmap(coverart.get(childPosition));
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.flag = true;
TestFragment3.flag = true;
Firstpage.flag = true;
Log.i("ExpandableListGenreAdapter", "path "+childPosition);
MainActivity.currentPosition = groupPosition;
Log.i("ExpandableListGenreAdapter", "currentPosition "+MainActivity.currentPosition);
MainActivity.genre=true;
MainActivity.currentgenreposition = albumID.get(childPosition);
Log.i("ExpandableListGenreAdapter", "currentGenrePosition "+MainActivity.currentgenreposition);
MainActivity.Media_full_path = "/sdcard/"+vehicle;
Log.i("ExpandableListAdapter", "Onclick "+MainActivity.Media_full_path);
((Activity)context).finish();
}
});
tv.setText(" " + vehicle.toString());
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return children.get(groupPosition).size();
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return genres.get(groupPosition);
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return genres.size();
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String group = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_layout, null);
}
TextView txtArtistsName = (TextView) convertView.findViewById(R.id.txtArtistsName);
TextView txtartistssongs = (TextView) convertView.findViewById(R.id.txtartistssongs);
txtArtistsName.setText(group);
txtartistssongs.setText(genres.get(groupPosition)+" Song(s)");
return convertView;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
Please Suggest me Where is i am missing from the Above Code. Thank You.
Hi hope this will help you. It displays the genres and their songs.
int index;
long genreId;
Uri uri;
Cursor genrecursor;
Cursor tempcursor;
String[] proj1 = {MediaStore.Audio.Genres.NAME, MediaStore.Audio.Genres._ID};
String[] proj2 = {MediaStore.Audio.Media.DISPLAY_NAME};
genrecursor = managedQuery(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, proj1, null, null, null);
if (genrecursor.moveToFirst()) {
do {
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
Log.i("Tag-Genre name", genrecursor.getString(index));
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
genreId = Long.parseLong(genrecursor.getString(index));
uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
tempcursor = managedQuery(uri, proj2, null,null,null);
Log.i("Tag-Number of songs for this genre", tempcursor.getCount() + "");
if (tempcursor.moveToFirst()) {
do {
index = tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
Log.i("Tag-Song name", tempcursor.getString(index));
} while(tempcursor.moveToNext());
}
} while(genrecursor.moveToNext());
}
I updated the answer of #Abhijeet for work with old versions
public void getGenres(int total) {
int index;
long genreId;
Uri uri;
Cursor genrecursor;
Cursor tempcursor;
String[] proj1 = {MediaStore.Audio.Genres.NAME, MediaStore.Audio.Genres._ID};
String[] proj2={MediaStore.Audio.Media.DISPLAY_NAME};
String result;
genrecursor = MyApplication.getAppContext().getContentResolver().query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, proj1, null, null, null);
ArrayList<Genre> genres = new ArrayList<Genre>();
Genre genre = null;
if (genrecursor!=null && genrecursor.moveToFirst()) {
do {
genre = new Genre();
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
if (BuildConfig.DEBUG) Log.i("Tag-Genre name", genrecursor.getString(index));
genre.setName(genrecursor.getString(index));
if(genre.getName().equalsIgnoreCase("")) {
genre.setName("no-genre");
}
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
genreId = Long.parseLong(genrecursor.getString(index));
uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
tempcursor = MyApplication.getAppContext().getContentResolver().query(uri, proj2, null, null, null);
if (BuildConfig.DEBUG) Log.i("Tag-Number of songs for this genre", tempcursor.getCount()+"");
genre.setNumberSongs( tempcursor.getCount());
if (!genres.contains(genre)) {
genres.add(genre);
}
if (tempcursor.moveToFirst()) {
do {
index = tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
if (BuildConfig.DEBUG) Log.i("Tag-Song name", tempcursor.getString(index));
for(int i = 0;i<songs.size();i++) {
if (BuildConfig.DEBUG) Log.i("SONG", songs.get(i).getDisplayName()+ " - "+ tempcursor.getString(index));
if (tempcursor!=null && songs!=null && tempcursor.getString(index).equalsIgnoreCase(songs.get(i).getDisplayName()) ) {
songs.get(i).setGenre(genre.getName());
if (genre.isOldVersion()) {
genre.setNumberSongs(genre.getNumberSongs()+1);
}
if (genre.getNumberSongs()==0) { //Is an oldversion of android, less than 3.0
genre.setOldVersion(true);
genre.setNumberSongs(1);
}
}
}
} while(tempcursor.moveToNext());
}
} while(genrecursor.moveToNext());
}
orderList(genres);
result = "";
for(int i = 0; i < 10 && i<genres.size() ;i++) {
result += genres.get(i).toString()+",";
}
result += "Total:"+total;
}

Fetch contact photo in android gives null

I want to fetch the photo of the contact while a user enters number.By using phone number i am getting users name but for image it shows null.
my code is following :
public class NewtempActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final EditText edit = (EditText) findViewById(R.id.editText1);
TextView txt = (TextView) findViewById(R.id.textView1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Girish", "Clicked");
String name = getContactNameFromNumber(edit.getText()
.toString(), getApplicationContext());
img.setImageBitmap(BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID));
Log.d("Girish",
""
+ (BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID)));
Toast.makeText(getApplicationContext(), name, name.length())
.show();
}
});
}
public String getContactNameFromNumber(String number, Context ctx) {
/*
* // define the columns I want the query to return String[] projection
* = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
* ContactsContract.PhoneLookup.NUMBER, };
*/
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
// Cursor c = ctx.getContentResolver().query( contactUri, projection,
// null,
Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
return name;
}
// return the original number if no match was found
return number;
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
Uri photoUri = Uri.withAppendedPath(contactUri,
Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, null, null, null,
null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
}
please suggest me where i am doing wrong.I have added read contact permission also
by going through your code i came to know like You are trying to get the contact name from the number. and using that you want the contact image.. but you never called the functions which you made for the contact pic..:).. so what you can do is take id from the contact number and take photo on that id. so you will get the photo for the number..
package com.android.SampleProject;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class NewtempActivity extends Activity {
private long id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final EditText edit = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("Girish", "Clicked");
String name = getContactNameFromNumber(edit.getText()
.toString(), getApplicationContext());
img.setImageBitmap(BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID));
img.setImageBitmap(loadContactPhoto(getContentResolver(), id));
Log.d("Girish",
""
+ (BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID)));
Toast.makeText(getApplicationContext(), name, name.length())
.show();
}
});
}
public String getContactNameFromNumber(String number, Context ctx) {
/*
* // define the columns I want the query to return String[] projection
* = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
* ContactsContract.PhoneLookup.NUMBER, };
*/
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
// Cursor c = ctx.getContentResolver().query( contactUri, projection,
// null,
Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
id = c.getLong(c
.getColumnIndex(ContactsContract.PhoneLookup._ID));
return name;
}
// return the original number if no match was found
return number;
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
Uri photoUri = Uri.withAppendedPath(contactUri,
Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, null, null, null,
null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
}

Get list of photo galleries on Android

I'm looking for:
A list of the existing photo gallery names (hopefully their top thumbnail as well)
The contents of the gallery (I can then load thumbnails and full size as needed)
How would I go about getting a list of the "Galleries" (don't know if that's the proper term in android for the groupings of images visible in the Gallery app...) and their contents? I need access to the gallery in it's structure without using the existing gallery display (I'm creating a totally new one, not an over layer to the photo requestor etc.)
I assume MediaStore.Images is where I need to be but I don't see anything that will give me the groupings...
Groupings are defined by MediaStore.Images.Media.BUCKET_DISPLAY_NAME. Here is the sample code to list the images and log their bucket name and date_taken:
// which image properties are we querying
String[] projection = new String[] {
MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN
};
// content:// style URI for the "primary" external storage volume
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
// Make the query.
Cursor cur = managedQuery(images,
projection, // Which columns to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
null // Ordering
);
Log.i("ListingImages"," query count=" + cur.getCount());
if (cur.moveToFirst()) {
String bucket;
String date;
int bucketColumn = cur.getColumnIndex(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int dateColumn = cur.getColumnIndex(
MediaStore.Images.Media.DATE_TAKEN);
do {
// Get the field values
bucket = cur.getString(bucketColumn);
date = cur.getString(dateColumn);
// Do something with the values.
Log.i("ListingImages", " bucket=" + bucket
+ " date_taken=" + date);
} while (cur.moveToNext());
}
/**
* Getting All Images Path
*
* #param activity
* #return ArrayList with images Path
*/
public static ArrayList<String> getAllShownImagesPath(Activity activity) {
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
ArrayList<String> listOfAllImages = new ArrayList<String>();
String absolutePathOfImage = null;
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaColumns.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME };
cursor = activity.getContentResolver().query(uri, projection, null,
null, null);
column_index_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
column_index_folder_name = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(absolutePathOfImage);
}
return listOfAllImages;
}
Here is the full solution in few simple steps:
The next few steps will guid you how to create a Vector that will hold the albums found on a given device. Every Album will hold a preview image as well an inner Vector that will hold all the images of the Album.
Create an object that will hold the images once extracted from storage. We are going to call it PhoneAlbum. This is how it's going to look:
public class PhoneAlbum {
private int id;
private String name;
private String coverUri;
private Vector<PhonePhoto> albumPhotos;
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String getCoverUri() {
return coverUri;
}
public void setCoverUri( String albumCoverUri ) {
this.coverUri = albumCoverUri;
}
public Vector< PhonePhoto > getAlbumPhotos() {
if ( albumPhotos == null ) {
albumPhotos = new Vector<>();
}
return albumPhotos;
}
public void setAlbumPhotos( Vector< PhonePhoto > albumPhotos ) {
this.albumPhotos = albumPhotos;
}
}
Create an object that will hold the images within the album called: PhonePhoto
public class PhonePhoto {
private int id;
private String albumName;
private String photoUri;
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getAlbumName() {
return albumName;
}
public void setAlbumName( String name ) {
this.albumName = name;
}
public String getPhotoUri() {
return photoUri;
}
public void setPhotoUri( String photoUri ) {
this.photoUri = photoUri;
}
}
Create an interface to handle the extracted images upon completion. We are going to call it OnPhoneImagesObtained. Here it is:
public interface OnPhoneImagesObtained {
void onComplete( Vector<PhoneAlbum> albums );
void onError();
}
Create a new class: DeviceImageManager
public class DeviceImageManager {
}
Once you created DeviceImageManager, add the following method:
public static void getPhoneAlbums( Context context , OnPhoneImagesObtained listener ){
// Creating vectors to hold the final albums objects and albums names
Vector< PhoneAlbum > phoneAlbums = new Vector<>();
Vector< String > albumsNames = new Vector<>();
// which image properties are we querying
String[] projection = new String[] {
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID
};
// content: style URI for the "primary" external storage volume
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
// Make the query.
Cursor cur = context.getContentResolver().query(images,
projection, // Which columns to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
null // Ordering
);
if ( cur != null && cur.getCount() > 0 ) {
Log.i("DeviceImageManager"," query count=" + cur.getCount());
if (cur.moveToFirst()) {
String bucketName;
String data;
String imageId;
int bucketNameColumn = cur.getColumnIndex(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int imageUriColumn = cur.getColumnIndex(
MediaStore.Images.Media.DATA);
int imageIdColumn = cur.getColumnIndex(
MediaStore.Images.Media._ID );
do {
// Get the field values
bucketName = cur.getString( bucketNameColumn );
data = cur.getString( imageUriColumn );
imageId = cur.getString( imageIdColumn );
// Adding a new PhonePhoto object to phonePhotos vector
PhonePhoto phonePhoto = new PhonePhoto();
phonePhoto.setAlbumName( bucketName );
phonePhoto.setPhotoUri( data );
phonePhoto.setId( Integer.valueOf( imageId ) );
if ( albumsNames.contains( bucketName ) ) {
for ( PhoneAlbum album : phoneAlbums ) {
if ( album.getName().equals( bucketName ) ) {
album.getAlbumPhotos().add( phonePhoto );
Log.i( "DeviceImageManager", "A photo was added to album => " + bucketName );
break;
}
}
} else {
PhoneAlbum album = new PhoneAlbum();
Log.i( "DeviceImageManager", "A new album was created => " + bucketName );
album.setId( phonePhoto.getId() );
album.setName( bucketName );
album.setCoverUri( phonePhoto.getPhotoUri() );
album.getAlbumPhotos().add( phonePhoto );
Log.i( "DeviceImageManager", "A photo was added to album => " + bucketName );
phoneAlbums.add( album );
albumsNames.add( bucketName );
}
} while (cur.moveToNext());
}
cur.close();
listener.onComplete( phoneAlbums );
} else {
listener.onError();
}
}
Now all you have left is to render the images to screen. In my case I like to use Picasso. Here is how I do it:
Picasso.with( getActivity() )
.load( "file:" + mPhoneAlbums.get( i ).getCoverUri() )
.centerCrop()
.fit()
.placeholder( R.drawable.temp_image )
.into( mAlbumPreview );
Don't forget to add a permission to read external storage in your manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
That's it. You are good to go!
Good luck!
I've found a way to get albums without iterating over every photo.
String[] projection = new String[]{
"COUNT(*) as count",
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATA,
"MAX (" + MediaStore.Images.ImageColumns.DATE_TAKEN + ") as max"};
Context context = ServiceProvider.getInstance().getApplicationContext();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
"1) GROUP BY (" + MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
null,
"max DESC");
cursor will contain as much elements, as distinct bucket name exists, and also you can get count inside every cursor position to get count of images inside album
here example:
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
//gets image path, it will always be a latest image because of sortOrdering by MAX date_taken
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
//gets count via alias ("as count" in projection)
int count = cursor.getInt(cursor.getColumnIndex("count"));
//do you logic here
...
} while (cursor.moveToNext());
}
cursor.close();
}
Some explanation about selection param:
contentResolver adds parentheses when compiling resulting query for sqlLite, so if we make selection like
"GROUP BY " + MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME
it will be compiled as "WHERE (GROUP BY bucket_display_name)" and will cause SQLiteException at runtime. Otherwise if we make selection like
"1) GROUP BY (" + MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME
it will be compiled as "WHERE (1) GROUP BY (bucket_display_name)", which is correct
Download the source code from here (Get all images from gallery in android programmatically)
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
xmlns:android="http://schemas.android.com/apk/res/android">
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gv_folder"
android:numColumns="2"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"></GridView>
</RelativeLayout>
MainActivity.java
package galleryimages.galleryimages;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gv_folder = (GridView)findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage = null;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getApplicationContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText(MainActivity.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
}

Categories

Resources