I want to prevent my music player app from scanning the directories for audio files everytime the app launches. How can I do that?
I have been using the following code to scan the audio files.
public void getSongList() {
ContentResolver contentResolver=getContentResolver();
Uri musicUri=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = contentResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()) {
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
int albumIDColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
long thisAlbumID=musicCursor.getLong(albumIDColumn);
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Bitmap albumArtBitMap=null;
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, thisAlbumID);
try {
albumArtBitMap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), albumArtUri);
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, albumArtBitMap.getWidth(), albumArtBitMap.getHeight()), new RectF(0, 0, 300, 300), Matrix.ScaleToFit.CENTER);
albumArtBitMap = Bitmap.createBitmap(albumArtBitMap, 0, 0, albumArtBitMap.getWidth(), albumArtBitMap.getHeight(), m, true);
} catch (IOException e) {
e.printStackTrace();
}
songList.add(new Song(thisId, thisTitle, thisArtist,albumArtBitMap));
}
while (musicCursor.moveToNext());
}
}
I want the app to only scan when there are new files. Because If I scan the whole SD card every time then it'll take too much time for starting the app. Please Help me with that
No need to keep all the songs in local app list.
To show the mp3list you can use content provider cursor list adapter query with limit (on scroll query page by page )
To search use directly the contentprovider query method.
Only keep a playslist on you local database pointing to mp3 uri.
this link might helps you :
How to update listview whose data was queried from database through SimpleCursorAdapter?
Every time you start the app see how much space you have on your device.
File path = Environment.getDataDirectory();
megaBytesAvailable(path)
public static float megaBytesAvailable(File file) {
StatFs stat = new StatFs(file.getPath());
long bytesAvailable = (long)stat.getBlockSizeLong() * (long)stat.getAvailableBlocksLong();
return bytesAvailable / (1024.f * 1024.f);
}
Save it to your app's cache as a variable and compare it every time you start the app, if it's greater then you know you need to scan.
if(comparedVariable < megaBytesAvailable(music_directory_path)){
getSongList();
//Save it again to compare next time if more storage is used
comparedVariable = megaBytesAvailable(music_directory_path);
//Save it to SharedPrefs for next boot up comparison
}
I think #royrok answer can help you, where #royrok checking the playlist in mediastore instead rescan the sdcard. Below I include #royrok answer.
Rather than rescan the card, the app iterates through all the playlists in MediaStore and checks the length of the _data field. I discovered that for all the lists with no associated M3U file, this field was always empty. Then it was just a case of finding the source code for the original android music app, finding the delete method and using that to delete any playlists with a length of 0. I've renamed the app PlaylistPurge (since it doesn't 'rescan' anymore) and am posting the code below:
package com.roryok.PlaylistPurge;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
public class PlaylistPurge extends ListActivity {
private List<String> list = new ArrayList<String>();
private final String [] STAR= {"*"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListAdapter adapter = createAdapter();
setListAdapter(adapter);
}
/**
* Creates and returns a list adapter for the current list activity
* #return
*/
protected ListAdapter createAdapter()
{
// return play-lists
Uri playlist_uri= MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;
Cursor cursor= managedQuery(playlist_uri, STAR, null,null,null);
cursor.moveToFirst();
for(int r= 0; r<cursor.getCount(); r++, cursor.moveToNext()){
int i = cursor.getInt(0);
int l = cursor.getString(1).length();
if(l>0){
// keep any playlists with a valid data field, and let me know
list.add("Keeping : " + cursor.getString(2) + " : id(" + i + ")");
}else{
// delete any play-lists with a data length of '0'
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, i);
getContentResolver().delete(uri, null, null);
list.add("Deleted : " + cursor.getString(2) + " : id(" + i + ")");
}
}
cursor.close();
// publish list of retained / deleted playlists
ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
return adapter;
}
}
Here's a link to a post on my blog about the app http://roryok.com/blog/index.php/2010/07/23/clearing-out-deleted-playlists-in-android/
UPDATE
I've found an article about Querying And Removing Media From The Android MediaStore, I included the content below.
.
.
.
Android provides a way to register different type of media, such as audio, video, and images, for consumption by any app. This is convenient if your app is, say, a music player or an image editor. Android's MediaStore is the provider for this meta data, and includes information about the media such as title, artist, size, and location.
If your application does any sort of media content creation, such as image editing or downloading audio from an external website, then you generally want to make that content accessible from any other apps that can consume it. When you create a file you can use the MediaScannerConnection to add the file and its metadata to the MediaStore.
If you delete the file from the file system, the metadata remains in the MediaStore until Android scans the system for new media, which typically happens when the system first boots up or can be called explicitly called in such a way:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory() )));
While this method works, it is time and resource consuming, as basically the entire file system must be re-scanned. An alternative is to explicitly delete the file from the MediaStore. We're going to discuss two ways to do this. The first is to query to MediaStore for the content, based on some predicate, and delete based on the unique ID the MediaStore identifies it by. The second, and easier, way to do it is to just specify the predicate in the delete statement. In this example, I'm going to be deleting an audio file based on its file name and path, but you can easily use this to delete any type of media based on any known information (such as video duration, or image dimensions).
In querying the MediaStore, you should think of it as an SQL database. You need to form your query by specifying the table (the MediaStore's external content table), the columns you need (the content’s ID), and the where clause (how to identify the content). To perform the actual query, we’re going to use the ContentResolver's query() method.
String[] retCol = { MediaStore.Audio.Media._ID };
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
retCol,
MediaStore.MediaColumns.DATA + "='" + filePath + "'", null, null);
if (cur.getCount() == 0) {
return;
}
cur.moveToFirst();
int id = cur.getInt(cur.getColumnIndex(MediaStore.MediaColumns._ID));
cur.close();
The first argument to query() specifies the columns we want to be returned, which in this case is only "_ID". The second argument specifies that we want to look at the media stored on the external SD card (which would be internal storage on devices with no SD card). The third argument is the predicate which specifies what content we're looking for. In this case, I'm identifying the file by its path in the file system (which is what is stored in the MediaColumns.DATA column). The fourth and fifth columns are the predicate's arguments and the ordering, respectively. I'm including my predicate's arguments in the predicate itself so that's not necessary, and if your only looking for one piece of content and your predicate is specific enough to just return one row then the ordering doesn't matter.
It is very important to make the predicate specific enough so that you're guaranteed to get the exact ID you're looking for. In my case, I know that there can be only one file at a particular location, but you could use a combination of any columns (such as title, artist, and album) to find the content. Check out the MediaColumns for all the possibilities.
Once you perform the actual query, you'll want to check to see whether the MediaStore actually contains the content you're trying to delete. If you don't handle this in some way your app will crash while trying to iterate through the cursor. Once you confirm that the query returned some data, grab the ID by moving the cursor to its first position, reading the “_ID” column, and closing the cursor. It's very important that you remember to close the cursor once you've finished using it. Your app won't crash, but you'll get memory leaks and complaints in LogCat.
Now that we have the ID that the MediaStore associated with our content, we can call ContentResolver's delete() method similar to how we called its query() method.
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id);
context.getContentResolver().delete(uri, null, null);
The delete() method takes 3 arguments: the Uri to be deleted, the predicate, and the predicate arguments. We form the Uri by appending the ID we discovered by querying the MediaStore to the Uri of the audio files on external storage. Since we know exactly which row we want to delete, we don't need to specify the predicate or the predicate's arguments.
The second method to delete the content from the MediaStore takes advantage of the fact that querying and deleting from it are performed almost identically.
context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
MediaStore.MediaColumns.DATA + "='" + path + "'", null);
We can use the predicate of the delete() method to specify exactly what we want to delete, rather than having to query for it beforehand. While this method is more efficient (no extra query, no cursors to deal with), it has some pitfalls. You have no way of explicitly confirming what you're deleting. You're also not able to do advanced queries with this method, such as if you wanted to delete the most recently added content (which you could do by ordering the query based on the DATE_ADDED column). However, both ways give you a way to confirm what you've deleted since the delete() method returns the number of rows that it deleted as an integer.
I'm trying to build a feature to load the latest saved image from the device into an app.
Currently I'm using this path DCIM/Camera/ but it only stores camera taken images. Is there a folder that stores all images? (screenshots, images saved from the web or camera roll)
Instead of searching in in folders for the images, you can let the system take care of that for you.
Android indexes most media-data (images, music, etc) on it's own and offers Content Providers to query these databases.
For your purposes, you can use the MediaStore.Images.Media-provider.
public List<String> getImagePaths(Context context) {
// The list of columns we're interested in:
String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED};
final Cursor cursor = context.getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, // Specify the provider
columns, // The columns we're interested in
null, // A WHERE-filter query
null, // The arguments for the filter-query
MediaStore.Images.Media.DATE_ADDED + " DESC" // Order the results, newest first
);
List<String> result = new ArrayList<String>(cursor.getCount());
if (cursor.moveToFirst()) {
final int image_path_col = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
do {
result.add(cursor.getString(image_path_col));
} while (cursor.moveToNext());
}
cursor.close();
return result;
}
The method will return a list of the image-paths of all images that are currently indexed by the MediaStore with the latest first. You'll need the android.permission.READ_EXTERNAL_STORAGE-permission for this to work!
I have videoplayer app with filebrowser listing all videos on SD card
Code inspired by i want get audio files in sd card
Using ContentResolver, works as expected, but it does not update if the files on card change. I do not mean automatically, but after view/app restart. Not even reinstalling the application helped, still shows the same files. The deleted video file is not visible via PC nor it is possible to play it (This video cannot be played (translation)).
I dumped the data and the problem is not in view caching or elsewhere. I do not implement any caching of my own and failed to find anything on the matter. Thank you
Code:
// acquisition
String[] projection = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.DATA
};
ContentResolver resolver = getActivity().getContentResolver();
Cursor videoCursor = resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
null
);
// extraction
while(cursor.moveToNext()) {
cursorIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
filepath = cursor.getString(cursorIndex);
cursorIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
filename = cursor.getString(cursorIndex);
cursorIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
duration = cursor.getString(cursorIndex);
result[ index++ ] = new VideoFileMetadata(filename, duration, filepath);
}
Edit 1 [14-03-2013]:
I tried adding number + " = " + number to ORDER or WHERE clause to act as a potential query caching buster, but it had no effect (although it's possible it was removed by an optimizer as a useless clause). This time I had reinstalled the application from a different machine using different certificate, but the query result remained the same, listing currently non-existing files.
You should first call cursor.moveToFirst() .
So, your cursor iteration loop should look like
if (cursor.moveToFirst()) {
do {
// cursorIndex = cursor.getColumnIndexOrThrow, etc...
} while (cursor.moveToNext());
}
I have a small FileExplorer in my app and i want him to start in the folder, which is currently used by the defautl camera. Is there a way to get this path?
I tryed:
Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_PICTURES).getAbsolutePath());
But this do not returns "/mnt/sdcard/Pictures" and my Camera is storing in "mnt/sdcard/ext_sd/DCIM/100MEDIA/"
PS:
I do know how to start the camera with a specific folder for storing the pictures, that's not what i'm searching for,
String[] projection = new String[]{MediaStore.Images.ImageColumns._ID,MediaStore.Images.ImageColumns.DATA,MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,MediaStore.Images.ImageColumns.DATE_TAKEN,MediaStore.Images.ImageColumns.MIME_TYPE};
final Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,projection, null, null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
if(cursor != null){
cursor.moveToFirst();
// you will find the last taken picture here
// according to Bojan Radivojevic Bomber comment do not close the cursor (he is right ^^)
//cursor.close();
}
This question should be a starting point to all of us who want to manipulate contacts in Android.
First things first
As I am aware, since API level 5 the Contacts API has changed, so in order to make the application work correct I need to check what android os is on the phone and if prior 5 use one content provider or else use the newer one. The only annoyance in this case is the warnings of deprecated I get. The application is build against Android 2.3.3 but needs to work from 1.5+
1. Querying contacts
This is the easiest part to do. Usually querying means getting data like Contact name, phones, picture, email and displaying it on a listview. For instance here is how I've done it in API prior 5
String[] projectionPeople = new String[] {People._ID, People.NAME,};
String[] projectionPhone = new String[] {Phones.NUMBER};
try {
// Get the base URI for People table in Contacts content provider.
// which is: content://contacts/people/
Uri contactUri = People.CONTENT_URI;
ContentResolver resolver = getContentResolver();
Cursor phonesCursor = null;
Cursor peopleCursor = resolver.query (contactUri,
projectionPeople, //Which columns to return.
"People.NAME is not null", // WHERE clause--we won't specify.
null, // Selection Args??
People.DEFAULT_SORT_ORDER); // Order-by name
if (peopleCursor != null && peopleCursor.getCount() >0)
{
// go to the beginning of the list
peopleCursor.moveToFirst();
do
{
//do something with current contact info
phoneUri= Uri.withAppendedPath(personUri, Contacts.People.Phones.CONTENT_DIRECTORY);
phonesCursor = resolver.query(phoneUri,
projectionPhone,
null,
null,
Phones.DEFAULT_SORT_ORDER);
if (phonesCursor!=null && phonesCursor.getCount()>0)
{
phonesCursor.moveToFirst();
lstPhones = new ArrayList<String>();
do
{
//add phone numbers to a List<String> for instance
} while (phonesCursor.moveToNext());
if (phonesCursor != null && !phonesCursor.isClosed())
phonesCursor.close();
} while (peopleCursor.moveToNext());
if (peopleCursor != null && !peopleCursor.isClosed())
peopleCursor.close();
}
}
catch (Exception ex)
{
}
}
Haven't tried it yet on the new api but the cursor should be like
final String[] projection = new String[] {
RawContacts.CONTACT_ID, // the contact id column
RawContacts.DELETED // column if this contact is deleted
};
final Cursor rawContacts = managedQuery(RawContacts.CONTENT_URI, // the URI for raw contact provider
projection
null, // selection = null, retrieve all entries
null, // selection is without parameters
null); // do not order
Sure, this needs to be elaborated a bit more, but it should provide the basics of simple query against Contacts content provider
2. Backup
My first thought on this was: if I know the Id of a Contact, I create tables in a sqlite database exactly how the cursor columns are and insert all the data into my tables. This is not an easy task as it requires a lot of codding not to mention that different apis have different table structures. What would be the best solution to backup one contact or multiple contacts ?
3. Delete
This should work on all apis using content providers, but data is spread on many packages and uris and I'm not sure from where to delete
4. Insert
After a contact is backed up, I may need to restore/insert it again. As in case of deletion, on which uris do I need to insert ?
Please, let's try to elaborate this issues so in the futures, who needs to use Contacts in Android apps could take this question as a solid starting point. Thank you stackoverflow community.
Here is a good starting point
http://developer.android.com/resources/samples/BusinessCard/index.html