In my application there is a button, that, when pressed, is supposed to open either the picture gallery, or the video gallery, or the audioplayer.
Please how would I construct an intent to perform that?
Try with this just onclick of any button pass the file path and then this method poen any type of file according to that file
File file = new File(filePath);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Uri uri = Uri.parse("www.google.com");
Intent type_intent = new Intent(Intent.ACTION_VIEW, uri);
Uri data = Uri.fromFile(file);
type_intent.setDataAndType(data, type);
startActivity(type_intent);
For images
private void getallimages(File dir)
{
String[] STAR = { "*" };
controller.images.clear();
final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();//this is my wrapper class
if(new File(imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA))).length()<=10485760)
{
imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
imageItem.id = id;
imageItem.selection = false; //newly added item will be selected by default this it do for check box unselect u dont need to fill this
controller.images.add(imageItem);//this i just add all info in wrapper class
}
}
}
for audio
private void getallaudio()
{
String[] STAR = { "*" };
controller.audioWrapper.clear();
Cursor audioCursor = cntx.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
if (audioCursor != null)
{
if (audioCursor.moveToFirst())
{
do
{
String path = audioCursor.getString(audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
controller.audioWrapper.add(new MediaWrapper(new File(path).getName(), path, "Audio",false));
}while (audioCursor.moveToNext());
}
}
}
and for video
private void getallvideo()
{
String[] STAR = { "*" };
controller.videoWrapper.clear();
Cursor videoCursor = cntx.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
if (videoCursor != null)
{
if (videoCursor.moveToFirst())
{
do
{
String path = videoCursor.getString(videoCursor.getColumnIndex(MediaStore.Images.Media.DATA));
controller.videoWrapper.add(new MediaWrapper(new File(path).getName(), path, "Video",false,color_string));
}while (videoCursor.moveToNext());
}
}
}
I would realize it this way:
On Button click, pop up a custom dialog box with 3 buttons.
picture gallery button
video gallery button
audio player button
Depending on user selection, you start the intent which corresponds to the action.
Related
I want to show all audio files from app-specific directorie in listView. Here is my code-
public void getMusic() {
File allSong = new File(String.valueOf(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)));
Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor songCursor = contentResolver.query(songUri, null, null, null, null);
if (songCursor != null && songCursor.moveToFirst()) {
int songTitle = songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int songArtist = songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int songPath = songCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
do {
songsList.add(new SongsList(songCursor.getString(songTitle), songCursor.getString(songArtist), songCursor.getString(songPath)));
} while (songCursor.moveToNext());
songCursor.close();
}
}
This is app-specific directorie
File allSong = new File(String.valueOf(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)));
Now I want to retrieve all files from above mentioned directorie.
Need help. Thanks in advance.
I am trying to fetch the album art of all the songs present on the phone. I am using MediaStore to fetch all the songs title,artist etc. How should I fetch album art ? I tried using MediaMetaDataRetriever but getting confused how to use it for multiple files. Can anyone please tweak this code?
Activity class:
public void getSongList() {
// retrieve song info
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null,
null);
metaRetriver.setDataSource(MainActivity.this,musicUri); // now how to loop over this
if (musicCursor != null && musicCursor.moveToFirst()) {
// get columns
int titleColumn = musicCursor.getColumnIndex(MediaColumns.TITLE);
int idColumn = musicCursor.getColumnIndex(BaseColumns._ID);
int artistColumn = musicCursor.getColumnIndex(AudioColumns.ARTIST);
// add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
} while (musicCursor.moveToNext());
}
Once you have the album id, which you can get from that same cursor, you can query a different URI for the cover art path. see below for an example of approximately how I do it:
private static String getCoverArtPath(Context context, long androidAlbumId) {
String path = null;
Cursor c = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + "=?",
new String[]{Long.toString(androidAlbumId)},
null);
if (c != null) {
if (c.moveToFirst()) {
path = c.getString(0);
}
c.close();
}
return path;
}
You could get a Map of all album art by id using something like this (untested)
private static Map<Long, String> getCoverArtPaths(Context context) {
String HashMap<Long, String> map = new HashMap<Long, String>();
Cursor c = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
null,
null,
null);
if (c != null) {
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
map.add(c.getLong(0), c.getString(1));
}
c.close();
}
// returns a mapping of Album ID => art file path
return map;
}
I got it working like this. Hope it helps someone :)
public void getSongList() {
// retrieve song info
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null,
null);
if (musicCursor != null && musicCursor.moveToFirst()) {
// get columns
int titleColumn = musicCursor.getColumnIndex(MediaColumns.TITLE);
int idColumn = musicCursor.getColumnIndex(BaseColumns._ID);
int artistColumn = musicCursor.getColumnIndex(AudioColumns.ARTIST);
int column_index = musicCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
// add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String pathId = musicCursor.getString(column_index);
Log.d(this.getClass().getName(), "path id=" + pathId);
metaRetriver.setDataSource(pathId);
try {
art = metaRetriver.getEmbeddedPicture();
Options opt = new Options();
opt.inSampleSize = 2;
songImage = BitmapFactory .decodeByteArray(art, 0, art.length,opt);
}
catch (Exception e)
{ imgAlbumArt.setBackgroundColor(Color.GRAY);
}
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist,songImage));
// if(songImage!=null)
// {
// songImage.recycle();
// }
} while (musicCursor.moveToNext());
}
For Fast rendering
If you are using recylerview, listview to render song list and it is making slow due to getting album art from song path then you can first check if ImageView has already background image set then don't process anything. It will reduce lot of processing and make scrolling fast even if song list is very large. I was facing same problem. I just did same as mentioned and recyclerview rendering with album art became smooth otherwise it was getting stuck during scroll.
My be this will help someone.
My code for recyclerview:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
if (holder instanceof MusicAdapter.MusicViewHolder) {
MusicAdapter.MusicViewHolder vh = (MusicAdapter.MusicViewHolder) holder;
vh.tvTitle.setText(musicList.get(position).title.toString());
vh.tvArtistAndAblum.setText(musicList.get(position).artist.toString() + " | " + musicList.get(position).album.toString());
Drawable background = vh.ivMusicIcon.getBackground();
if(background == null) {
String pathId = musicList.get(position).path;
MediaMetadataRetriever metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(pathId);
try {
byte[] art = metaRetriver.getEmbeddedPicture();
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inSampleSize = 2;
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length,opt);
BitmapDrawable ob = new BitmapDrawable(context.getResources(), songImage);
vh.ivMusicIcon.setBackground(ob);
}
catch (Exception e)
{
vh.ivMusicIcon.setImageResource(R.drawable.compact_disc);
}
}
} else if (holder instanceof FooterViewHolder) {
FooterViewHolder vh = (FooterViewHolder) holder;
}
} catch (Exception e) {
e.printStackTrace();
}
}
Anyone know how to get a listing of all images that show up in the Android Gallery?
This query is only gets pictures taken locally on the phone. Does anyone know the URI where the Picasa image database is stored?? Appreciate the help.
private void getListOfAllPictures()
{
final String[] filePathColumn = { MediaStore.Images.Media._ID, MediaColumns.DATA, MediaColumns.DISPLAY_NAME, Images.Media.ORIENTATION, Images.Media.LATITUDE, Images.Media.LONGITUDE };
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
filePathColumn, null, null, null);
Vector<ImageDescriptor> imageDescriptors = new Vector<ImageDescriptor>();
if(cursor != null)
{
cursor.moveToFirst();
int IMG_ID_INDEX = cursor.getColumnIndex(MediaStore.Images.Media._ID);
int DATA_INDEX = cursor.getColumnIndex(MediaColumns.DATA);
int LATITUDE_INDEX = cursor.getColumnIndex(Images.Media.LATITUDE);
int LONGITUDE_INDEX = cursor.getColumnIndex(Images.Media.LONGITUDE);
int ORIENTATION_INDEX = cursor.getColumnIndex(Images.Media.ORIENTATION);
while(!cursor.isAfterLast())
{
//Blah Blah
cursor.moveToNext();
}
}
cursor.close();
Log.v(TAG, "Found " + imageDescriptors.size() + " images.");
}
ok its my code and it work for me it give all images which i can see in Android Gallery
just call this function from this line
getallimages(Environment.getExternalStorageDirectory());
and my function is below
private void getallimages(File dir)
{
String[] STAR = { "*" };
final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();
imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
imageItem.id = id;
imageItem.selection = false; //newly added item will be selected by default
controller.images.add(imageItem);
}
}
After taking a photo by using intent ACTION_IMAGE_CAPTURE with given location to save photo on some devices (my test device is Sony Ericsson Mt11i with android 2.3) default camera app is saving a duplicate image in camera photos folder.
So my app checks if the photo is duplicated and deletes it. But the camera app also saving the thumbnail for taken photo, so i'm deleting it too, but even after I delete this thumbnail there is somewhere still information about this thumbnail, and in device's gallery app image is still present with default image. If I check details of this image there is still information of this photo (date,location). These are my methods for handling duplicated photo:
public static void handleTakenPicture(Context context, int lastId, File tempFile) {
/*
* Checking for duplicate images
* This is necessary because some camera implementation not only save where you want them to save but also in their default location.
*/
if (lastId == 0)
return;
final String[] projection = {MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.SIZE, MediaStore.Images.ImageColumns._ID};
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
final String imageWhere = MediaStore.Images.Media._ID + ">?";
final String[] imageArguments = {Integer.toString(lastId)};
Cursor imageCursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, imageWhere, imageArguments,
imageOrderBy);
// List<File> cameraTakenMediaFiles = new ArrayList<File>();
File gFile = null;
if (imageCursor.getCount() > 0) {
// while( imageCursor.moveToNext() ) {
imageCursor.moveToFirst();
// int id =
// imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
String path = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
gFile = new File(path);
// Long takenTimeStamp =
// imageCursor.getLong(imageCursor.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN));
// Long size =
// imageCursor.getLong(imageCursor.getColumnIndex(MediaStore.Images.Media.SIZE));
// cameraTakenMediaFiles.add(new File(path));
//}
}
imageCursor.close();
//File imageFile = new File(imageFilePath);
if (!tempFile.exists() && gFile != null) {
// was not saved where I wanted, but the camera saved one in the media folder
// try to copy over the one saved by the camera and then delete
try {
Prefsy.copyFile(gFile, tempFile);
gFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
if(gFile != null)
{
gFile.delete();
try { // DELETING THUMBNAIL
Cursor th = context.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Images.ImageColumns.DATA},
MediaStore.Images.Thumbnails.IMAGE_ID + " = ?", new String[] {"" + lastId}, MediaStore.Images.Thumbnails._ID + " DESC");
L(th.getCount()+"");
if (th.getCount() > 0)
{
th.moveToFirst();
L(th.getString(0));
L(new File(th.getString(0)).delete()+"");
L(context.getContentResolver().delete(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
MediaStore.Images.Thumbnails.IMAGE_ID + " = ?", new String[] {"" + lastId})+"");
}
th.close();
} catch (Exception e) {
}
}
/*for( File cameraTakenFile : cameraTakenMediaFiles ) {
// delete the one duplicated
cameraTakenFile.delete();
}*/
}
public static int getLastImageId(Context context){
final String[] imageColumns = { MediaStore.Images.Media._ID };
final String imageOrderBy = MediaStore.Images.Media._ID+" DESC";
final String imageWhere = null;
final String[] imageArguments = null;
Cursor imageCursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, imageWhere, imageArguments, imageOrderBy);
if(imageCursor.moveToFirst()){
int id = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
imageCursor.close();
return id;
}else{
return 0;
}
}
L() is Log method
I am trying to convert the image paths of selected images in my grid view to uris, so that I can then pass those onto my photo editor, and edit from there.
if (cb.isChecked()) {
String paths = imagePaths.get(i);
Uri uri = Uri.parse(paths);
editImagesUri[count] = uri;
count++;
}
That is my code where I am getting my NullPointerException, and I just can't seem to figure out what the problem is.
I have changed around the content in the if statement a few times so that it essentially does the same thing, but the error is still the same.
This is the value of paths:
imagePaths = new ArrayList<String>();
imagePaths = getPathOfAllImages(getActivity());
This is the value of uri:
private static Uri[] editImagesUri;
getPathOfAllImages is a method I found on this website as an answer. Here is the code for it:
public static ArrayList<String> getPathOfAllImages(Activity activity) {
ArrayList<String> absolutePathOfImageList = new ArrayList<String>();
String absolutePathOfImage = null;
String nameOfFile = null;
String absolutePathOfFileWithoutFileName = null;
Uri uri;
Cursor cursor;
int column_index;
int column_displayname;
int lastIndex;
int counter = 0;
// absolutePathOfImages.clear();
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaColumns.DATA,
MediaColumns.DISPLAY_NAME };
cursor = activity.managedQuery(uri, projection, null, null, null);
column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
column_displayname = cursor
.getColumnIndexOrThrow(MediaColumns.DISPLAY_NAME);
// cursor.moveToFirst();
while (cursor.moveToNext()) {
// for(int i=0; i<cursor.getColumnCount();i++){
// Log.i(TAG,cursor.getColumnName(i)+".....Data Present ...."+cursor.getString(i));
// }
// Log.i(TAG,"=====================================");
absolutePathOfImage = cursor.getString(column_index);
nameOfFile = cursor.getString(column_displayname);
lastIndex = absolutePathOfImage.lastIndexOf(nameOfFile);
lastIndex = lastIndex >= 0 ? lastIndex
: nameOfFile.length() - 1;
absolutePathOfFileWithoutFileName = absolutePathOfImage
.substring(0, lastIndex);
if (absolutePathOfImage != null) {
absolutePathOfImageList.add(absolutePathOfImage);
}
}
// Log.i(TAG,"........Detected images for Grid....."
// + absolutePathOfImageList);
return absolutePathOfImageList;
}