I am new to android programming so can anyone please help me to find all .mp3 files in my android device.
You should use MediaStore. Here is an example code i'm using for something similar:
private static ArrayList<SongModel> LoadSongsFromCard() {
ArrayList<SongModel> songs = new ArrayList<SongModel>();
// Filter only mp3s, only those marked by the MediaStore to be music and longer than 1 minute
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"
+ " AND " + MediaStore.Audio.Media.MIME_TYPE + "= 'audio/mpeg'"
+ " AND " + MediaStore.Audio.Media.DURATION + " > 60000";
final String[] projection = new String[] {
MediaStore.Audio.Media._ID, //0
MediaStore.Audio.Media.TITLE, //1
MediaStore.Audio.Media.ARTIST, //2
MediaStore.Audio.Media.DATA, //3
MediaStore.Audio.Media.DISPLAY_NAME
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
Cursor cursor = null;
try {
// the uri of the table that we want to query
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; //getContentUriForPath("");
// query the db
cursor = _context.getContentResolver().query(uri,
projection, selection, null, sortOrder);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//if (cursor.getString(3).contains("AwesomePlaylists")) {
SongModel GSC = new SongModel();
GSC.ID = cursor.getLong(0);
GSC.songTitle = cursor.getString(1);
GSC.songArtist = cursor.getString(2);
GSC.path = cursor.getString(3);
// This code assumes genre is stored in the first letter of the song file name
String genreCodeString = cursor.getString(4).substring(0, 1);
if (!genreCodeString.isEmpty()) {
try {
GSC.genre = Short.parseShort(genreCodeString);
} catch (NumberFormatException ex) {
Random r = new Random();
GSC.genre = (short) r.nextInt(4);
} finally {
songs.add(GSC);
}
}
//}
cursor.moveToNext();
}
}
} catch (Exception ex) {
} finally {
if (cursor != null) {
cursor.close();
}
}
return songs;
}
Of course . you can . Code not tested.
File dir =new File(Environment.getExternalStorageDirectory());
if (dir.exists()&&dir.isDirectory()){
File[] files=dir.listFiles(new FilenameFilter(){
#Override
public boolean accept(File dir,String name){
return name.contains(".mp3");
}
});
}
You can use recursive searching. Use this function with path of directory where you wanna start search .mp3 files (for example "/mnt/sdcard").
public Vector<String> mp3Files = new Vector<String>();
private void searchInDirectory(String directory)
{
File dir = new File(directory);
if(dir.canRead() && dir.exists() && dir.isDirectory())
{
String []filesInDirectory = dir.list();
if(filesInDirectory != null)
{
for(int i=0; i<filesInDirectory.length; i++)
{
File file = new File(directory+"/"+filesInDirectory[i]);
if(file.isFile() && file.getAbsolutePath().toLowerCase(Locale.getDefault()).endsWith(".mp3"))
{
mp3Files.add(directory+"/"+filesInDirectory[i]);
}
else if(file.isDirectory() )
{
searchInDirectory(file.getAbsolutePath());
}
}
}
}
}
public ArrayList<String> searchMP3File(ArrayList<String> aListFilePath, String rootPath) {
File rootFile = new File(rootPath);
File[] aRootFileFilter = rootFile.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
if(pathname.getName().endsWith(".mp3"))
return true;
else
return false;
}
});
if(aRootFileFilter != null && aRootFileFilter.length > 0) {
for(int i = 0; i < aRootFileFilter.length; i++) {
aListFilePath.add(aRootFileFilter[i].getPath());
}
}
File[] aRootFile = rootFile.listFiles();
for(int i = 0; i < aRootFile.length; i++) {
if(aRootFile[i].isDirectory()) {
ArrayList<String> aListSubFile = searchMP3File(aListFilePath, aRootFile[i].getPath());
if(aListSubFile != null && aListSubFile.size() > 0)
aListFilePath = aListSubFile;
}
}
return aListFilePath;
}
private String[] videoExtensions;
videoExtensions = new String[2];
videoExtensions[0] = "mp3";
videoExtensions[1] = "3gp";
After this declaration in your onCreate() method, set below code in some method and call it. Do changes as per your need in my code.
try {
File file = new File("mnt/sdcard/DCIM/Camera");
File[] listOfFiles = file.listFiles();
videoArray = new ArrayList<HashMap<String, String>>();
videoHashmap = new HashMap<String, String>();
for (int i = videoIndex; i < listOfFiles.length; i++) {
File files = listOfFiles[i];
rowDataVideos = new HashMap<String, String>();
for (String ext : videoExtensions) {
if (files.getName().endsWith("." + ext)) {
videoHashmap.put("Video", files.getAbsolutePath());
videoArray.add(videoHashmap);
fileSize = files.length();
fileSizeInMb += convertSize(fileSize, MB);
thumb = ThumbnailUtils.createVideoThumbnail(files.getAbsolutePath(), MediaStore.Images.Thumbnails.MINI_KIND);
if (thumb != null) {
createTempDirectory();
try {
FileOutputStream out = new FileOutputStream(audiofile);
thumb.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Tue Apr 23 16:08:28 GMT+05:30 2013
lastModDate = new Date(files.lastModified()).toString();
dateTime = (dateToMilliSeconds(lastModDate) / 1000L);
rowDataVideos.put(VIDEOPATH, files.getAbsolutePath());
rowDataVideos.put(VIDEOSTATUS, "0");
rowDataVideos.put(VIDEOSIZEINMB, String.valueOf(fileSizeInMb));
rowDataVideos.put(VIDEODATE, String.valueOf(dateTime));
if (dateTime > (RESPONSE_TIMESTAMP_VIDEO / 1000L)) {
dataProvider.InsertRow(VIDEOS, rowDataVideos);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Related
I'm working on this project where I generated CSV files from contact list, and now I'm supposed to package all the files as a single zip archive using RxJava, so I'm trying to get the method to create an archive invoked using onComplete method. But the application is crashing with this error:
Attempt to invoke direct method 'boolean appjoe.wordpress.com.testdemo.Tab2$FileHelper.zip(java.lang.String, java.lang.String)' on a null object reference
This is my code:
path: /storage/emulated/0/Android/data/com.wordpress.appjoe/csv
File location = new File(Environment.getExternalStorageDirectory(), "Android/data/com.wordpress.appjoe/csv/");
File fileLocation;
FileOutputStream dest;
String path;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tab2, container, false);
mbutton = v.findViewById(R.id.extractContact);
mbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Permission has already been granted
Observer observer = new Observer() {
#Override
public void onSubscribe(Disposable d) {
mCursor = getCursor();
fCursor = getCursor();
location.mkdirs();
path = location.getAbsolutePath();
try {
dest = new FileOutputStream(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void onNext(Object o) {
contactData = o.toString();
fCursor.moveToPosition(count);
fileLocation = new File(path, getName(fCursor)+".csv");
try {
FileOutputStream fileOut = new FileOutputStream(fileLocation);
fileOut.write(contactData.getBytes());
fileOut.flush();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
mCursor.close();
fCursor.close();
// Creating archive once the CSV files are generated
if (fileHelper.zip(path, location.getParent())) {
Toast.makeText(getContext(), "Zip successful", Toast.LENGTH_SHORT).show();
}
Log.d("fileLocation", "location: " + location.getParent());
Log.d("fileLocation", "path: " + path);
Log.d("Observer_contact", "Completed");
}
};
io.reactivex.Observable.create(new ObservableOnSubscribe<String>() {
#Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
try {
for (count = 0; count < mCursor.getCount(); count++) {
emitter.onNext(loadContacts(count));
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
}
}).subscribeOn(Schedulers.io())
.distinct()
.subscribeWith(observer);
}
}
});
// Inflate the layout for this fragment
return v;
}
RxJava implementation to fetch contacts:
public String loadContacts(int i) {
StringBuilder mBuilder = new StringBuilder();
ContentResolver mContentResolver = getActivity().getContentResolver();
mCursor.moveToPosition(i);
if (mCursor.getCount() > 0 ) {
String id = getID(mCursor);
String name = getName(mCursor);
int hasPhoneNumber = hasNumber(mCursor);
if (hasPhoneNumber > 0) {
mBuilder.append("\"").append(name).append("\"");
Cursor cursor = mContentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "= ?",
new String[]{id}, null);
assert cursor != null;
while (cursor.moveToNext()) {
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
.replaceAll("\\s", "");
// if number is not existing in the list, then add number to the string
if (!(mBuilder.toString().contains(phoneNumber))) {
mBuilder.append(", ").append(phoneNumber);
}
}
cursor.close();
}
}
return mBuilder.toString();
}
Methods to get necessary information:
private Cursor getCursor() {
ContentResolver mContentResolver = getActivity().getContentResolver();
return mContentResolver.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
}
private String getID(Cursor cursor) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
return id;
}
private String getName(Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
return name;
}
private int hasNumber(Cursor cursor) {
return Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
}
Class to generate archive
// Custom class to help with zipping of generated CSVs
private class FileHelper {
private static final int BUFFER_SIZE = 2048;
private String TAG = FileHelper.class.getName();
private String parentPath = "";
private String destinationFileName = "Contacts_CSV.zip";
private boolean zip (String sourcePath, String destinationPath) {
new File(destinationPath).mkdirs();
FileOutputStream fileOutputStream;
ZipOutputStream zipOutputStream = null;
try {
if (!destinationPath.endsWith("/")) {
destinationPath = destinationPath + "/";
}
String destination = destinationPath + destinationFileName;
File file = new File(destination);
if (!file.exists()) {
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
parentPath = new File(sourcePath).getParent() + "/";
zipFile(zipOutputStream, sourcePath);
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
return false;
} finally {
if (zipOutputStream!=null)
try {
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
private void zipFile (ZipOutputStream zipOutputStream, String sourcePath) throws IOException {
java.io.File files = new java.io.File(sourcePath);
java.io.File[] fileList = files.listFiles();
String entryPath="";
BufferedInputStream input;
for (java.io.File file : fileList) {
if (file.isDirectory()) {
} else {
byte data[] = new byte[BUFFER_SIZE];
FileInputStream fileInputStream = new FileInputStream(file.getPath());
input = new BufferedInputStream(fileInputStream, BUFFER_SIZE);
entryPath = file.getAbsolutePath().replace(parentPath, "");
ZipEntry entry = new ZipEntry(entryPath);
zipOutputStream.putNextEntry(entry);
int count;
while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
zipOutputStream.write(data, 0, count);
}
input.close();
}
}
}
}
I solved this problem by removing the class FileHelper and making both the methods inside FileHelper private methods within the main class. That way, calling the methods from onComplete() didn't cause the program to crash, and it was successfully generating the zip file.
I am able to fetch all the images from any specified non hidden folder from device but how can I get all the images from a hidden specified folder.
As soon as I mention my hidden folder name in the query, cursor return null
public static List<MediaData> getAppScannedImages(Context context) {
Cursor imagecursor = null;
List<MediaData> gallerydata = new ArrayList<MediaData>();
try {
final String orderBy = Images.ImageColumns.DATE_TAKEN + " DESC";
imagecursor = context.getContentResolver()
.query(Images.Media.EXTERNAL_CONTENT_URI,
projectionImage,
Images.Media.BUCKET_DISPLAY_NAME + "='"
+ ".myHiddenFolder" + "'", null,
orderBy);
if (imagecursor != null) {
imagecursor.moveToFirst();
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
MediaData galData = new MediaData();
galData.setKey_id(i);
galData.setId(imagecursor.getString(0));
galData.setName(imagecursor.getString(1));
galData.setPath(imagecursor.getString(2));
galData.setDate(imagecursor.getString(3));
gallerydata.add(galData);
imagecursor.moveToNext();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (imagecursor != null) {
imagecursor.close();
}
}
return gallerydata;
}
You can try a different approach.
You have to find out the list of hidden folder from sd card and search all those folders for images.
the follwoing code is displays hidden files:
public void goTODir(File dir) {
//dir is initail dir like="/mnt/sdcard"
String imageType = ".jpg";
File[] listFile = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
goTODir(listFile[i]);
} else {
if (listFile[i].isHidden()){
if(listFile[i].getName().endsWith(imageType))
{
//add to your array list
}
}
}
}
}
}
String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path);
File listFile[] = dir.listFiles();
for (int i = 0; i < listFile.length; i++) {
if(listFile[i].getAbsolutePath().contains("your hidden folder name")){
File dirtest = new File(listFile[i].getAbsolutePath());
File listFiletest[] = dirtest.listFiles();
for (int j = 0; j < listFiletest.length; j++) {
get all images from hidden folder
}
}
}
For Kotlin Lover
companion object {
const val FOLDER_PATH = "/YourFolder/.hideen/"
}
/**
* Method to get all Image Path
* #return [ArrayList]
* */
fun getImagePath(): ArrayList<String> {
// image path list
val list: ArrayList<String> = ArrayList()
// fetching file path from storage
val file = File(Environment.getExternalStorageDirectory().toString() + FOLDER_PATH)
val listFile = file.listFiles()
if (listFile != null && listFile.isNullOrEmpty()) {
Arrays.sort(listFile, LastModifiedFileComparator.LASTMODIFIED_REVERSE)
}
if (listFile != null) {
for (imgFile in listFile) {
if (
imgFile.name.endsWith(".jpg")
|| imgFile.name.endsWith(".jpeg")
|| imgFile.name.endsWith(".png")
) {
val model : String = imgFile.absolutePath
list.add(model)
}
}
}
// return imgPath List
return list
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to get folder from SDcard which have multiple images.
I have done to get all folder but i want to get folder which have images.
Here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.domore.folderlist.MainActivity">
<!--<ListView-->
<!--android:id="#+id/listview"-->
<!--android:layout_width="fill_parent"-->
<!--android:layout_height="wrap_content">-->
<!--</ListView>-->
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:numColumns="2"
android:stretchMode="columnWidth" >
</GridView>
</LinearLayout>
Here, is my MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private File file;
private List<String> myList;
private ArrayAdapter adapter;
GridView listview;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File temp_file=new File(file,myList.get(position));
if(!temp_file.isFile()) {
file = new File(file, myList.get(position));
Log.e("CLICK PATH",""+file);
File list[] = file.listFiles();
myList.clear();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
//adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, myList);
listview.setAdapter(adapter);
// listview.setAdapter(new ImageAdapter(this,myList));
}
}
#Override
public void onBackPressed() {
// super.onBackPressed();
String parent = file.getParent().toString();
Log.e("PATH",parent);
file = new File(parent) ;
File list[] = file.listFiles();
myList.clear();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
// listview.setAdapter(new ImageAdapter(this,myList));
adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,myList);
listview.setAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(GridView)findViewById(R.id.gridview);
myList=new ArrayList<String>();
String root_sd= Environment.getExternalStorageDirectory().getPath().toString();
Log.e("PATH",""+root_sd);
file=new File(root_sd);
File list[]=file.listFiles();
for(int i=0;i<list.length;i++){
myList.add(list[i].getName());
}
adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,myList);
listview.setAdapter(adapter);
// listview.setAdapter(new ImageAdapter(this,myList));
listview.setOnItemClickListener(this);
}
}
Please, help me to solve out
in my application i write this code for load all photos:
Resolver = getContentResolver();
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
String[] directories = null;
if (u != null) {
c = managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst())) {
do {
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try {
dirList.add(tempDir);
} catch (Exception e) {
e.printStackTrace();
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for (int i = 0; i < dirList.size(); i++) {
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if (imageList == null)
continue;
for (File imagePath : imageList) {
try {
if (imagePath.isDirectory()) {
imageList = imagePath.listFiles();
}
if (imagePath.getName().toLowerCase(Locale.US).endsWith(".jpg")
|| imagePath.getName().toLowerCase(Locale.US).endsWith(".jpeg")
|| imagePath.getName().toLowerCase(Locale.US).endsWith(".png")) {
String path = imagePath.getAbsolutePath();
PhotosList.add(path);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
try this
public void searchImageFromSpecificDirectory() {
String path = null;
String uri = MediaStore.Images.Media.DATA;
// if GetImageFromThisDirectory is the name of the directory from which image will be retrieved
String condition = uri + " like '%/GetImageFromThisDirectory/%'";
String[] projection = { uri, MediaStore.Images.Media.DATE_ADDED,
MediaStore.Images.Media.SIZE };
Vector additionalFiles = null;
try {
if (additionalFiles == null) {
additionalFiles = new Vector<String>();
}
Cursor cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
condition, null, null);
if (cursor != null) {
boolean isDataPresent = cursor.moveToFirst();
if (isDataPresent) {
do {
path = cursor.getString(cursor.getColumnIndex(uri));
System.out.println("...path..."+path);
additionalFiles.add(path);
}while(cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try these lines of code:-
File[] file = Environment.getExternalStorageDirectory().listFiles();
for (File f : file)
{
if (f.isDirectory()) {
file[] innerFiles = f.listFiles();
for(int i=0; i< innerFiles.length;i++){
Log.i("Name", innerFiles[i].getPath() + "");
///here you make the check that FOLDER consits IMAGE ofr NOT
if( innerFiles[i].getPath().contains(".JPG") || innerFiles[i].getPath().contains(".jpg"))
{
// YOU CAN PERFORM YOURS OPERATION HERE
}
}
}
if (f.isFile()) { ... do stuff }
}
if (f.isFile()) { ... do stuff }
}
On one of my device, the following code can't make my video appear in Gallery:
File file = new File(path);
Uri uri = Uri.fromFile(file);
Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
activity.sendBroadcast(scanFileIntent);
So I use scanFile explicitly:
android.media.MediaScannerConnection.scanFile(activity, new String[]{file.getAbsolutePath()},
new String[]{"video/" + mMimeType}, null);
When my video is xxx.mpeg4, the value of mMimeType is mp4, the result is that the video can appear in MediaStore but I can't get the duration later(the returned value is always 0). Need help on this.
public static long[] getVideoDetail(Context context, Uri uri) {
long[] result = new long[] {DEFAULT_VIDEO_FRAME_WIDTH, DEFAULT_VIDEO_FRAME_HEIGHT, -1};
if(uri == null || (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()))) {
return result;
}
String[] projection = new String[] {MediaStore.Video.Media.RESOLUTION, MediaStore.Video.VideoColumns.DURATION};
Cursor cursor = null;
boolean success = false;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor.moveToFirst()) {
String resolution = cursor.getString(0);
if(!StringUtils.isEmpty(resolution)) {
int index = resolution.indexOf('x');
result[0] = Integer.parseInt(resolution.substring(0, index));
result[1] = Integer.parseInt(resolution.substring(index + 1));
if(result[0] != 0 && result[1] != 0) {
success = true;
}
if(result[0] > result[1]) {
swap(result, 0, 1);
}
}
result[2] = cursor.getLong(1);
if(result[2] >= 0 && success) {
success = true;
} else {
success = false;
}
}
if (null != cursor) {
cursor.close();
}
}
catch (Exception e) {
// do nothing
} finally {
try {
if (null != cursor) {
cursor.close();
}
} catch (Exception e2) {
// do nothing
}
}
if (!success) {
try {
ContentResolver contentResolver = context.getContentResolver();
String selection = MediaStore.Images.Media._ID + "= ?";
String id = uri.getLastPathSegment();
String[] selectionArgs = new String[]{ id };
cursor = contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, null);
if (cursor.moveToFirst()) {
String resolution = cursor.getString(0);
if(!StringUtils.isEmpty(resolution)) {
int index = resolution.indexOf('x');
result[0] = Integer.parseInt(resolution.substring(0, index));
result[1] = Integer.parseInt(resolution.substring(index + 1));
if(result[0] > result[1]) {
swap(result, 0, 1);
}
}
result[2] = cursor.getLong(1);
}
if (null != cursor) {
cursor.close();
}
} catch (Exception e) {
// do nothing
} finally {
try {
if (cursor != null) {
cursor.close();
}
} catch (Exception e) {
// do nothing
}
}
}
if(result[0] <= 0) {
result[0] = DEFAULT_VIDEO_FRAME_WIDTH;
}
if(result[1] <= 0) {
result[1] = DEFAULT_VIDEO_FRAME_HEIGHT;
}
return result;
}
As I see in your code you are requesting duration in your projection
String[] projection = new String[] {MediaStore.Video.Media.RESOLUTION, MediaStore.Video.VideoColumns.DURATION};
now you just need to retrieve it from the cursor like shown below:
long timeInMs = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION));
get help from MediaPlayer :
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(context, Uri.parse(uri));
} catch (IOException e) {
Log.d("-MS-","Cannot parse url");
e.printStackTrace();
}
int duration= mp.getDuration();
String[] projection = new String[] {MediaStore.Video.Media.RESOLUTION,duration};
I always get Duration by MediaPlayer.
I am trying to read all the images in the SDCARD with the Directory in which its present. e.g: if there is a file TEST.jpg in /mnt/sdcard/album1 and TEST2.jpg in /mnt/sdcard/album1/album2 i should be able to get the directory name album1 and album2.
I have written a code which does this in recursive manner, This works when the no of folders are less but when the number of directories increases the loop just come out of it.
public void getImageFoldes(String filepath){
String albumpath;
File file = new File(filepath);
File[] files = file.listFiles();
for (int fileInList = 0; fileInList < files.length; fileInList++)
{
File filename;
filename =files[fileInList];
if(filename.isHidden()|| filename.toString().startsWith("."))
return;
if (filename.isDirectory()){
albumpath = filename.toString();
String[] split;
String title;
split= albumpath.split("/");
title=split[split.length-1];
result = new thumbnailResults();
result.setTitle(title);
result.setPath(albumpath);
result.setIsLocal(true);
//result.setCreated("05-06-2011");
getImageFoldes(filename.toString());
}
else{
if (files.length !=0)
{
//if File is the image file then store the album name
if ((files[fileInList].toString()).contains(".png")||
(files[fileInList].toString()).contains(".jpg")||
(files[fileInList].toString()).contains(".jpeg")){
if (!results.contains(result)){
result.setUri(Uri.parse(files[fileInList].getPath()));
results.add(result);
myadapter.notifyDataSetChanged();
}
}
}
}
}
}
Use the following code.
to get the path of all images and directories from sdcard.
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;
// 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;
}
To get all the image files from the Sdcard, it may work.
public class ReadallImagesActivity extends Activity {
ArrayList<String> arlist = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File ff = Environment.getExternalStorageDirectory();
loadImagepaths(ff);
setContentView(R.layout.main);
Toast.makeText(ReadallImagesActivity.this, "Array size == " +arlist.size(), Toast.LENGTH_LONG).show();
}
public void loadImagepaths(File file) {
for (File f : file.listFiles()) {
if (f.isDirectory()) {
if (f.getAbsolutePath().endsWith(".android_secure")) {
break;
}
if (f.getAbsolutePath().endsWith("DCIM")) {
continue;
}
loadImagepaths(f);
} else {
if (f.getAbsolutePath().endsWith(".png") ||
f.getAbsolutePath().endsWith(".gif") ||
f.getAbsolutePath().endsWith(".jpg"))
{
arlist.add(f.getAbsolutePath());
}
}
}
}
}