I'm trying to read photos existing in the sdcard with MediaStore.Images.Media.DATA but I'm always getting an empty cursor !!!
This is the code I'm using for the reading :
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
Cursor imagecursor = getContentResolver()
.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
MediaStore.Images.Media.DATA + " like ? ",
new String[] { "%"+eventName.trim()+"%" }, null);
imagecursor.setNotificationUri(getContentResolver(),
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
this.imageUrls = new ArrayList<String>();
Log.i("imagecursor.getCount()", Integer.toString(imagecursor.getCount()));
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor.getString(dataColumnIndex));
}
Of course I added this
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
to the AndroidManifest.xml
I found that the problem was with the Media Scanner so i solved it buy using a simple app called Scan Media witch scan the external storage and then the MediaStore will be able to find the new elements .
i donĀ“t know if this will help you but I is working me
String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/yoururl/";
Toast.makeText(getActivity(), targetPath, Toast.LENGTH_LONG).show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files){
myImageAdapter.add(file.getAbsolutePath());
}
in this example i get images and show in a grid view
Related
I have developed a android application which plays music on my phone.
I have created the following directory structure on my phone.
data
Music
Engish
Song 1
Song 2
Jazz
Song 1
Song 2
Code Snippet
To get the list of Music categories (returns the folder names)
filepath = new File(Environment.getExternalStorageDirectory().getAbsoluteFile().getPath() + "/data/Music/");
String[] directories = filepath.list(new FilenameFilter()
The list of categories gets populated on the phone
English
Jazz
When the user selects a category (eg: English), the list of songs get populated for that category.
To get the list of songs under a Category
File filepath = new File(Environment.getExternalStorageDirectory()
.getAbsoluteFile().getPath() + "/data/Music/");
folder = filepath.toString() + "/" + categoryName;
folder value = /storage/emulated/0/data/Music/English
folder = folder + "/%";
**folder value = /storage/emulated/0/data/Music/English/%**
String where = MediaStore.Audio.Media.DATA + " like ? ";
String[] whereArgs = new String[] { folder };
String[] col = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.SIZE };
musiccursor = getActivity().getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, col, where,
whereArgs,
"UPPER(" + MediaStore.Audio.Media.DISPLAY_NAME + ") ASC");
musiclist = (ListView) getView().findViewById(R.id.MusicList);
musiclist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
musiclist.setAdapter(new MusicAdapter(getActivity(),R.layout.song_list_item, musiccursor));
musiclist.setOnItemClickListener(musicgridlistener);
The above code works on my phone.
Now I want to move the songs to a SD (Storage) Card on my phone.
For that I had to create the following directory structure
On the card, there is already a folder Android/data.
Within that I had to create a folder called com.android.gmp/files/data (gmp is my package name).
So the directory struture is:
Android
data
com.android.gmp
files
data
Music
Engish
Song 1
Song 2
Jazz
Song 1
Song 2
The code to get the folders from the card
File[] storages = ContextCompat.getExternalFilesDirs(getActivity(), null);
if (storages.length > 1 && storages[0] != null && storages[1] != null) {
File file = storages[1];
String path = file.getAbsolutePath();
filepath = new File(path + "/data/Music/");
String[] directories = filepath.list(new FilenameFilter();
}
filepath value = /storage/3862-3539/Android/data/com.android.gmp/files/data/Music
The list of categories gets populated on the phone
English
Jazz
To get the songs under the category (No songs are returned - this is the issue)
folder = filepath.toString() + "/" + categoryName;
folder value = /storage/3862-3539/Android/data/com.android.gmp/files/data/Music/English/%
Same code as above
String where = MediaStore.Audio.Media.DATA + " like ? ";
String[] whereArgs = new String[] { folder };
String[] col = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.SIZE };
musiccursor = getActivity().getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, col, where,
whereArgs,
"UPPER(" + MediaStore.Audio.Media.DISPLAY_NAME + ") ASC");
musiclist = (ListView) getView().findViewById(R.id.MusicList);
musiclist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
musiclist.setAdapter(new MusicAdapter(getActivity(),R.layout.song_list_item, musiccursor));
musiclist.setOnItemClickListener(musicgridlistener);
This query does not work, does not get the songs under the folder - if anyone can let me know where the issue is.
There are lots of other classes in the application but this issue is specifically getting files under a folder on a SD card
I was able to find a solution for my issue.
I had to get a list of songs from a external storage (SD card)and populate a ListView using a cursor.
I already have code which was populating the songs from internal storage so did not want to make too many changes.
Below is the code snippet
Step 1. Create a new Content Provider (SongContentProvider inherited from ContentProvider)
`public class SongContentProvider extends ContentProvider
Overwrite the query method
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
//selection contains folder path (in my case = /storage/3862-3539/Android/data/com.android.gmp/files/data/Music/English
String[] matrixColumns = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.SIZE };
MatrixCursor songListCursor = new MatrixCursor(matrixColumns);
File directory = null;
File[] fileList = null;
directory = new File(selection);
fileList = directory.listFiles();
Arrays.sort(fileList);
Object[] mRow = new Object[4];
for(int i=0;i<fileList.length;i++){
mRow[0] = i;
mRow[1] = fileList[i];
mRow[2] = fileList[i].getName();
mRow[3] = "";
songListCursor.addRow(mRow);
}
return songListCursor;
}
`
Step 2. Call query from PlaySongFragment.java
private final Uri songContentProvider =
Uri.parse("content://com.android.gmp.songs/songs");
Cursor musiccursor = getActivity().getContentResolver().query(songContentProvider, null, folderPath, null, null);
musiclist.setAdapter(new MusicAdapter(getActivity(),R.layout.song_list_item, musiccursor));
Step 3. Add content provider to the manifest.xml
<provider
android:authorities="com.android.gmp.songs"
android:name=".SongContentProvider">
</provider>
I just need the path of folders that contain at least one file that ends with eg. .mp4 or .jpg . I already checked this thread: Android: how to get all folders with photos? but it's too slow for my use case. Is there a faster way to do that?
So I finally found a solution which is way faster than the mentioned above. I got all directories with images within ~100-150ms (around 3k files). In the example below all image files stored either on the internal or external storage gets checked and the parent directory is added to the array list. I excluded .gif and .giff files.
This method also works with videos therefore a few steps are required:
change queryUri to MediaStore.Video.Media.EXTERNAL_CONTENT_URI
change projection to MediaStore.Video.Media.DATA
change 'image/%' in includeImages to 'video/%'
delete + excludeGif from selection
public static ArrayList<String> getImageDirectories(Context mContext) {
ArrayList<String> directories = new ArrayList<>();
ContentResolver contentResolver = mContext.getContentResolver();
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = new String[]{
MediaStore.Images.Media.DATA
};
String includeImages = MediaStore.Images.Media.MIME_TYPE + " LIKE 'image/%' ";
String excludeGif = " AND " + MediaStore.Images.Media.MIME_TYPE + " != 'image/gif' " + " AND " + MediaStore.Images.Media.MIME_TYPE + " != 'image/giff' ";
String selection = includeImages + excludeGif;
Cursor cursor = contentResolver.query(queryUri, projection, selection, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
String photoUri = cursor.getString(cursor.getColumnIndex(projection[0]));
if(!directories.contains(new File(photoUri).getParent())){
directories.add(new File(photoUri).getParent());
}
} while (cursor.moveToNext());
}
return directories;
}
I have the following code where i am getting all the images from Camera but I want it from a certain folder as Pictures/SanPics. This folder is already created and has some images but it always returns NullPointerException.
CODE :
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Pictures" + File.separator + "SanPics";
File file = new File(path);
Uri myUri = Uri.fromFile(file);
Cursor imagecursor = getContentResolver().query(myUri, columns, orderBy, selectionArgs,null);
int image_column_index = imagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
Help will be much appreciated. Thanks in advance.
aI am having a problem in displaying all the videos inside a folder in SD card. Currently, I am able to display all the videos that can be found in SD card, but what I am trying to do is to display all the video inside the "PartyVideo" folder inside the SD card. Can you help me?Below is my code that display all the video in SD card.
final String[] columns = { MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID };
final String orderBy = MediaStore.Video.Media.DATE_TAKEN;
Cursor imagecursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns, null,null, orderBy + " DESC");
int image_column_index = imagecursor.getColumnIndex(MediaStore.Video.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[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.Video.Media.DATA);
thumbnails[i] = MediaStore.Video.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Video.Thumbnails.MICRO_KIND, null);
arrPath[i]= imagecursor.getString(dataColumnIndex);
}
GridView imagegrid = (GridView) findViewById(R.id.grid_GalleryImage);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
I tried many different code, and end up with this one. The code below gets all that video in the folder I want but I don't know how can I display it.
String[] fileList = null;
File videoFiles = new File(Environment.getExternalStorageDirectory()+"/PartyVideo");
if(videoFiles.isDirectory())
{
fileList=videoFiles.list();
}
for(int i=0;i<fileList.length;i++)
{
Log.e("Video:"+i+" File name",fileList[i]);
}
Use this File Browser library to browse through files and put the filter of video type in the following code
Intent intent = new Intent(getBaseContext(), FileDialog.class);
intent.putExtra(FileDialog.START_PATH, "/sdcard");
//can user select directories or not
intent.putExtra(FileDialog.CAN_SELECT_DIR, true);
//alternatively you can set file filter
intent.putExtra(FileDialog.FORMAT_FILTER, new String[] { "avi" });
startActivityForResult(intent, REQUEST_SAVE);
Just try this hope it will work for you.
http://android-er.blogspot.in/2011/05/display-video-thumbnail-in-listview.html
try this
Cursor videocursor = getActivity().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
columns,
MediaStore.Video.Media.DATA + " like ? ",
new String[]{"%/" + Your folder name + "/%"},
null);
i am trying to populate listview with video files from a folder created on sd card. I am using
managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,mystring, null, null, null);
But it populates all videos saved in sdcard, but i want only those videos which are saved in specific folder. I have also used
Uri uri = Uri.fromFile(filepath);
cursor = managedQuery(uri, mystring , null , null , null);
and
Uri uri = Uri.parse(filepath);
cursor = managedQuery(uri, mystring , null , null , null);
But it doesn't work. I have tried lot and got help from google still not succeded.
Is there any way to give path of that folder? or any other way?
you can use this code for get videos from specific folder as:
String selection=MediaStore.Video.Media.DATA +" like?";
String[] selectionArgs=new String[]{"%FolderName%"};
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
parameters, selection, selectionArgs, MediaStore.Video.Media.DATE_TAKEN + " DESC");
You can get a files form a specific location like this
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File("/sdcard/");
// or you can use File f=new File(Environment.getExternalStorageDirectory().getPAth());
File[] files = f.listFiles();
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
hey managedquery search the whole sdcard not the specific folder .
the above method is true of display the name of file but if you to display thumbnail create thumbmail and store in in Hashmap and populate it to the list of gallery adapter..........