2 * Copyright (C) 2012 Andrew Neal Licensed under the Apache License, Version 2.0
3 * (the "License"); you may not use this file except in compliance with the
4 * License. You may obtain a copy of the License at
5 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
6 * or agreed to in writing, software distributed under the License is
7 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8 * KIND, either express or implied. See the License for the specific language
9 * governing permissions and limitations under the License.
12 package com.cyngn.eleven.loaders;
14 import android.content.Context;
15 import android.database.Cursor;
16 import android.provider.BaseColumns;
17 import android.provider.MediaStore;
18 import android.provider.MediaStore.Audio.AudioColumns;
20 import com.cyngn.eleven.model.Song;
21 import com.cyngn.eleven.utils.Lists;
23 import java.util.ArrayList;
24 import java.util.List;
27 * Used to query {@link MediaStore.Audio.Media.EXTERNAL_CONTENT_URI} and return
28 * the Song the user added over the past four of weeks.
30 * @author Andrew Neal (andrewdneal@gmail.com)
32 public class LastAddedLoader extends WrappedAsyncTaskLoader<List<Song>> {
37 private final ArrayList<Song> mSongList = Lists.newArrayList();
40 * The {@link Cursor} used to run the query.
42 private Cursor mCursor;
45 * Constructor of <code>LastAddedHandler</code>
47 * @param context The {@link Context} to use.
49 public LastAddedLoader(final Context context) {
57 public List<Song> loadInBackground() {
59 mCursor = makeLastAddedCursor(getContext());
61 if (mCursor != null && mCursor.moveToFirst()) {
64 final long id = mCursor.getLong(0);
67 final String songName = mCursor.getString(1);
69 // Copy the artist name
70 final String artist = mCursor.getString(2);
72 // Copy the album name
73 final String album = mCursor.getString(3);
76 final long duration = mCursor.getLong(4);
78 // Convert the duration into seconds
79 final int durationInSecs = (int) duration / 1000;
82 final Song song = new Song(id, songName, artist, album, durationInSecs);
86 } while (mCursor.moveToNext());
89 if (mCursor != null) {
97 * @param context The {@link Context} to use.
98 * @return The {@link Cursor} used to run the song query.
100 public static final Cursor makeLastAddedCursor(final Context context) {
101 final int fourWeeks = 4 * 3600 * 24 * 7;
102 final StringBuilder selection = new StringBuilder();
103 selection.append(AudioColumns.IS_MUSIC + "=1");
104 selection.append(" AND " + AudioColumns.TITLE + " != ''"); //$NON-NLS-2$
105 selection.append(" AND " + MediaStore.Audio.Media.DATE_ADDED + ">"); //$NON-NLS-2$
106 selection.append(System.currentTimeMillis() / 1000 - fourWeeks);
107 return context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
118 AudioColumns.DURATION
119 }, selection.toString(), null, MediaStore.Audio.Media.DATE_ADDED + " DESC");