How to list all videos from specific folder in android - 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

Related

Display specfic folder videos in a listview with Thumbnails android

I am trying to display video files in listview from folder 'xyz' on sdcard, i have successfully displayed but problem is that it displays all video files stored on sdcard even out of folder 'abc' actually i want only video files stored in folder 'xyz' to be displayed. I am googling since 4 days but didn't find any solution for that. My code is that is showing all videos and working perfectly :
private Cursor videocursor;
private int video_column_index;
ListView videolist;
int count;
String[] thumbColumns = null ;
File videoFiles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init_phone_video_grid();
#SuppressWarnings("deprecation")
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.list);
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(MainActivity.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();
ViewHolder holder;
String id = null;
convertView = null;
if (convertView == null) {
convertView = LayoutInflater.from(vContext).inflate(R.layout.listitem, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtSize = (TextView) convertView.findViewById(R.id.txtSize);
holder.thumbImage = (ImageView) convertView.findViewById(R.id.imgIcon);
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);
holder.txtTitle.setText(id);
holder.txtSize.setText(" Size(KB):" + videocursor.getString(video_column_index));
String[] proj = { MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj,
MediaStore.Video.Media.DISPLAY_NAME + "=?",
new String[] { id }, null);
cursor.moveToFirst();
long ids = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID));
ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(
crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND,
options);
holder.thumbImage.setImageBitmap(curThumb);
curThumb = null;
}
return convertView;
}
}
static class ViewHolder {
TextView txtTitle;
TextView txtSize;
ImageView thumbImage;
}
Try this
public static final String[] VIDEO_PROJECTION = {MediaStore.Video.Media._ID, MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DATA};
public static final Uri VIDEO_SOURCE_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
Querying the data using the content resolver
CursorLoader cursorLoader = new CursorLoader(getActivity(), VIDEO_SOURCE_URI, VIDEO_PROJECTION, MediaStore.Video.Media.DATA + " like ? ", new String[]{"%FOLDER_NAME%"},
MediaStore.Video.Media.DATA + " COLLATE NOCASE ASC;");
It retrievers all the video files from the FOLDER_NAME. Since there can be one or more folders with a name so it is better to provide absolute path.

sd card video content display (album wise) ( android)

hi guys i am making an android application IN which i have to display all the video contents of the sd card (album wise).....it means when WE WILL LOAD THE APPLICATION only the names of albums should be displayED.... AND when we click on the particular album ITS VIDEOS FILES SHOULD BE DISPLAYED................... i have been able to display the album names BUT THE PROBLEM IS THAT there is duplicate album names (i.e. IF TWO VIDEO files are of same album) then two different albums are being displaying...........so i want all the videos of same album should be in one "album name"........... and on the click of that album name "all its video contents should be displayed"
any help will be appreciated below is the main class (AlbumVideo.class)
public class AlbumVideo extends Activity {
private Cursor audiocursor;
private int audio_column_index;
ListView audiolist;
int count;
int album=1;
int dura;
int i1 =R.drawable.ic_launcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagexml1);
init_phone_videos_grid();
}
#SuppressWarnings("deprecation")
private void init_phone_videos_grid() {
System.gc();
final String[] projection = new String[] {
MediaStore.Video.VideoColumns.ALBUM };
final String sortOrder = VideoColumns.ALBUM + " COLLATE LOCALIZED ASC";
audiocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, null, null, sortOrder);
count = audiocursor.getCount();
audiolist = (ListView) findViewById(R.id.PhoneVideo);
audiolist.setAdapter(new AudioAdapter(getApplicationContext()));
audiolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
#SuppressWarnings("rawtypes")
public void onItemClick(AdapterView parent, View v, int position,
long id) {
System.gc();
audio_column_index = audiocursor
.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.ALBUM);
audiocursor.moveToPosition(position);
String filename = audiocursor.getString(audio_column_index);
Intent intent = new Intent(AlbumVideo.this,
AlbumVideoDetail.class);
intent.putExtra("albumfilename",filename);
intent.putExtra("album",album);
startActivity(intent);
}
};
public class AudioAdapter extends BaseAdapter
{
private Context vContext;
CheckBox cb;
int position=0;
int check=0;
String a[]=new String[count];
public AudioAdapter(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();
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.list_item1, parent, false);
final Button title = (Button) row.findViewById(R.id.button);
title.setTextColor(Color.parseColor("#000000"));
if (convertView == null) {
audio_column_index =audiocursor.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.ALBUM );
audiocursor.moveToPosition(position);
String TITLE = audiocursor.getString(audio_column_index);
String a[]=new String[count];
Toast.makeText(AlbumVideo.this, "music will be available shortly"+TITLE, Toast.LENGTH_LONG).show();
title.setText(TITLE);
}
return (row);
}
}
}
and the second class to display the songs of the particular album is ("AlbumVideoDetail.class")
public class AlbumVideoDetail extends Activity {
private Cursor videocursor;
private int video_column_index;
ListView videolist;
int count;
String title=null;
String desc=null;
int dura;
int i1 =R.drawable.ic_launcher;
String filename;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagexml);
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("albumfilename");
// String filename1 = filename.substring(filename.indexOf("sdcard"),filename.length());
// String filename2= filename1.substring(7);
Toast.makeText(AlbumVideoDetail.this, "music will be available shortly"+filename, Toast.LENGTH_LONG).show();
init_phone_videos_grid();
}
#SuppressWarnings("deprecation")
private void init_phone_videos_grid() {
System.gc();
String[] proj = { MediaStore.Video.Media.DATA,
MediaStore.Video.Media._ID, MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.MIME_TYPE,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.SIZE,};
String where = android.provider.MediaStore.Video.Media.ALBUM + "=?";
String whereVal[] = { filename };
String orderBy = android.provider.MediaStore.Video.Media.TITLE;
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, where, whereVal, orderBy);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
}
public class VideoAdapter extends BaseAdapter {
private Context vContext;
CheckBox cb;
int position=0;
int check=0;
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();
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.list_item2, parent, false);
final TextView title = (TextView) row.findViewById(R.id.title);
TextView desc = (TextView) row.findViewById(R.id.desc);
TextView dura = (TextView) row.findViewById(R.id.duration);
title.setTextColor(Color.parseColor("#000000"));
desc.setTextColor(Color.parseColor("#000000"));
dura.setTextColor(Color.parseColor("#000000"));
if (convertView == null) {
video_column_index =videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videocursor.moveToPosition(position);
final String TITLE = videocursor.getString(video_column_index);
title.setText(TITLE);
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videocursor.moveToPosition(position);
String DESC= videocursor.getString(video_column_index);
int desd=Integer.parseInt(DESC);
int kb = (int) ((desd / 1000) % 1000);
int mb = (int) ((desd / 1000) / 1000);
String KB=Integer.toString(kb);
String MB=Integer.toString(mb);
String DESC1 = MB + "." + KB +"mb";
desc.setText(DESC1);
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
videocursor.moveToPosition(position);
String DURA= videocursor.getString(video_column_index);
int duro = Integer.parseInt(DURA);
int seconds = (int) ((duro / 1000) % 60);
int minutes = (int) ((duro / 1000) / 60);
String secs=Integer.toString(seconds);
String mins=Integer.toString(minutes);
String DURA1 = mins + ":" + secs;
dura.setText(DURA1);
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videocursor.moveToPosition(position);
final String filename = videocursor.getString(video_column_index);
} return (row);
}
}
}
wow after so much time spent on the internet at last found the solution for it !!!!!!! it an easy n very short step .,][.....i hope it will be helpful to someone ..........
private void init_phone_videos_grid() {
System.gc();
String[] proj = { MediaStore.Video.Media.DATA,
MediaStore.Video.Media._ID, MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.MIME_TYPE,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.SIZE,};
String where = android.provider.MediaStore.Video.Media.ALBUM + "=?";
String whereVal[] = { filename };
String orderBy = android.provider.MediaStore.Video.Media.TITLE;
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "DISTINCT "
+proj, where, whereVal, orderBy);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
}
just to add the word "distinct" in the class "album detail"....n it will sort d query according to yourt requirement....
Change the following:
final String[] projection = new String[] {MediaStore.Video.VideoColumns.ALBUM };
into
final String[] projection = new String[]{ "DISTINCT " +MediaStore.Video.VideoColumns.ALBUM};

Get Images and Videos from Android Phone into Custom Gallery

I'm trying to create a custom gallery that allows users to pick from all the photos and videos contained on their Android device. I know how to create a gallery of just photos and just videos, but if I want to combine both, how can I do this?
I think the issue comes down to how I create my cursor. To select all videos, I created the cursor this way:
String[] videoParams = {MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DATE_TAKEN,
MediaStore.Video.Thumbnails.DATA};
videocursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoParams, null, null, null);
If I want to query all the media files, not just video, what do I do?
This is what I tried, based off of: Custom Gallery with Images and Videos in android to select multiple items
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String jpg_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
String png_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
String mp4_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp4");
String[] selectionArgs = new String[]{jpg_mimeType, png_mimeType, mp4_mimeType};
mediaCursor = getContentResolver().query(MediaStore.Files.getContentUri("internal"), null, selectionMimeType, selectionArgs, MediaStore.Files.FileColumns.DATE_ADDED);
This gives me the error java.lang.IllegalArgumentException: Cannot bind argument at index 3 because the index is out of range. The statement has 1 parameters at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
Perhaps my approach is completely wrong, but I can't find any examples of custom android galleries using both images and videos, which is bizarre to me as this seems like it would be a common thing to create.
Here's all of my code, in case it's helpful:
public class GridViewCompatActivity extends Activity {
GridViewCompat gridView;
private static final String TAG = "GridViewCompatActivity";
Cursor videocursor;
Cursor mediaCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view_compat);
gridView = (GridViewCompat) findViewById(R.id.gridView1);
// NOTE: We are using setChoiceMode, as I said, its a drop-in replacement
gridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
gridView.setAdapter(new ImageAdapter(getApplicationContext()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> view, View arg1, int pos, long id) {
// We need to invalidate all views on 4.x versions
GridViewCompat gridView = (GridViewCompat) view;
gridView.invalidateViews();
}
});
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checkArray;
checkArray = gridView.getCheckedItemPositions();
String selectedPos = "Selected positions: ";
int count = checkArray.size();
for (int i = 0; i < count; i++) {
if (checkArray.valueAt(i))
selectedPos += checkArray.keyAt(i) + ",";
}
Intent intent = new Intent();
intent.putExtra("result", selectedPos);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
Log.d(TAG, "number of media: " + Integer.toString(MediaStore.Files.FileColumns.DATA.length()));
int mediaParams = MediaStore.MediaColumns.DATA.length();
return mediaParams;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new grid view item for each item referenced by the Adapter
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
CheckBox checkBox;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(R.layout.grid_view_item, parent, false);
}
imageView = (ImageView) convertView.findViewById(R.id.imageView1);
checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
GridViewCompat gvc = (GridViewCompat) parent;
if (gvc.getChoiceMode() == ListView.CHOICE_MODE_MULTIPLE) {
SparseBooleanArray checkArray;
checkArray = gvc.getCheckedItemPositions();
checkBox.setChecked(false);
if (checkArray != null) {
if (checkArray.get(position)) {
checkBox.setChecked(true);
}
}
}
// imageView.setImageResource(mThumbIds[position]);
Bitmap bmThumbnail;
Log.d(TAG, "position: " + position);
mediaCursor = getContentResolver().query(MediaStore.Files.getContentUri("internal"), null, selectionMimeType, selectionArgs, MediaStore.Files.FileColumns.DATE_ADDED);
Log.d(TAG, Integer.toString(mediaCursor.getCount()));
for (int i = 0; i < mediaCursor.getCount(); i++){
mediaCursor.moveToPosition(i);
Boolean isVideo = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA)).length() > 0;
Log.d(TAG, "isVideo: " + isVideo);
String mediaPath = "";
if(isVideo){
mediaPath = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
video_paths.add(mediaPath);
}else{
mediaPath = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Images.Media.DATA));
video_paths.add(mediaPath);
}
Log.d(TAG, "mediaPath: " +mediaPath);
}
mediaCursor.moveToPosition(position);
String video_path = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.d(TAG, "video_path: " + video_path);
imageView.setImageBitmap(ThumbnailUtils.createVideoThumbnail(video_path, Thumbnails.MICRO_KIND));
return convertView;
}
ArrayList<String> video_paths = new ArrayList<String>();
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String jpg_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
String png_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
String mp4_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp4");
String[] selectionArgs = new String[]{jpg_mimeType, png_mimeType, mp4_mimeType};
// String[] videoParams = {MediaStore.Video.Media._ID,
// MediaStore.Video.Media.DATA,
// MediaStore.Video.Media.DATE_TAKEN,
// MediaStore.Video.Thumbnails.DATA};
// }
}
}
public class GalleryFragment extends Fragment
{
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private int[] typeMedia;
private ImageAdapter imageAdapter;
#SuppressLint("NewApi") #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.gallery_gridview, container, false);
String[] columns = { MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.MEDIA_TYPE,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.TITLE,
};
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
+ " OR "
+ MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
final String orderBy = MediaStore.Files.FileColumns.DATE_ADDED;
Uri queryUri = MediaStore.Files.getContentUri("external");
#SuppressWarnings("deprecation")
Cursor imagecursor = getActivity().managedQuery(queryUri,
columns,
selection,
null, // Selection args (none).
MediaStore.Files.FileColumns.DATE_ADDED + " DESC" // Sort order.
);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Files.FileColumns._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.typeMedia = new int[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 4;
bmOptions.inPurgeable = true;
int type = imagecursor.getColumnIndex(MediaStore.Files.FileColumns.MEDIA_TYPE);
int t = imagecursor.getInt(type);
if(t == 1)
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
getActivity().getContentResolver(), id,
MediaStore.Images.Thumbnails.MINI_KIND, bmOptions);
else if(t == 3)
thumbnails[i] = MediaStore.Video.Thumbnails.getThumbnail(
getActivity().getContentResolver(), id,
MediaStore.Video.Thumbnails.MINI_KIND, bmOptions);
arrPath[i]= imagecursor.getString(dataColumnIndex);
typeMedia[i] = imagecursor.getInt(type);
}
GridView imagegrid = (GridView) v.findViewById(R.id.PhoneImageGrid);
Button reSizeGallery = (Button) v.findViewById(R.id.reSizeGallery);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
reSizeGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ChatViewerAdapter.ScreenResize(getActivity());
}
});
return v;//super.onCreateView(inflater, container, savedInstanceState);
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#SuppressLint("NewApi") public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(
R.layout.gallery_view, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.videoICON = (ImageView) convertView.findViewById(R.id.videoICON);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageview.getLayoutParams().height = height/6;
holder.imageview.getLayoutParams().width = width/4;
holder.imageview.setId(position);
if(typeMedia[position] == 1)
holder.videoICON.setVisibility(View.GONE);
else if(typeMedia[position] == 3)
holder.videoICON.setVisibility(View.VISIBLE);
holder.imageview.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int id = v.getId();
Display display = ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int height = display.getHeight();
final int height_half = (int) (height/2.5);
RelativeLayout fragment_layout = (RelativeLayout) getActivity().findViewById(R.id.fragment_gallery);
fragment_layout.setVisibility(View.VISIBLE);
fragment_layout.getLayoutParams().height = height_half;
GalleryImageChooseFragment f_img_choose =new GalleryImageChooseFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Bundle args = new Bundle();
args.putString("PATH", arrPath[id]);
f_img_choose.setArguments(args);
ft.show(f_img_choose);
ft.replace(R.id.fragment_tattle, f_img_choose);
ft.addToBackStack("f_img_choose");
ft.commit();
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
ImageView videoICON;
int id;
}
}
Download source code form here (Get all videos from gallery android).
public void fn_video() {
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name,column_id,thum;
String absolutePathOfImage = null;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME,MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};
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.Video.Media.BUCKET_DISPLAY_NAME);
column_id = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
Log.e("column_id", cursor.getString(column_id));
Log.e("thum", cursor.getString(thum));
Model_Video obj_model = new Model_Video();
obj_model.setBoolean_selected(false);
obj_model.setStr_path(absolutePathOfImage);
obj_model.setStr_thumb(cursor.getString(thum));
al_video.add(obj_model);
}
}
This function will return arraylist of gallery images and videos in descending order. Just pass this function to adapter and show gallery stuff in recyclerview in kotlin.
#SuppressLint("Range")
fun getAllGalleryMedia(): ArrayList<Media> {
val result = ArrayList<Media>()
val projection = arrayOf(
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.MEDIA_TYPE,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.TITLE
)
val selection = (MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
+ " OR "
+ MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO)
val queryUri = MediaStore.Files.getContentUri("external")
Handler(Looper.getMainLooper()).post {
val cursorLoader = CursorLoader(
context,
queryUri,
projection,
selection,
null,
MediaStore.Files.FileColumns.DATE_ADDED + " DESC"
)
val cursor: Cursor? = cursorLoader.loadInBackground()
if (cursor != null) {
while (cursor.moveToNext()) {
val id = cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID))
val displayName =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME))
val imagePath =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA))
val dateAdded =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATE_ADDED))
val mimeType =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE))
result.add(Media(id, displayName, imagePath, dateAdded, mimeType))
}
cursor.close()
}
}
return result
}
This is model class,you can modify according to your needs.
class Media:java.io.Serializable{
var id:Long=0
var displayName:String=""
var imagePath:String=""
var dateAdded:String=""
var mimeType:String=""
var isSelected:Boolean = false
constructor(){
// empty constructor
}
constructor(
id: Long,
displayName: String,
imagePath: String,
dateAdded: String,
mimeType: String
){
this.id = id
this.displayName = displayName
this.imagePath = imagePath
this.dateAdded = dateAdded
this.mimeType = mimeType
}}

how to show thumbimage in gridview from sdcard

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;
}
}
}

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;
}

Categories

Resources