/** Reload the queue after we remove a track */
 private void reloadQueueCursor() {
   if (mPlaylistId == PLAYLIST_QUEUE) {
     String[] cols =
         new String[] {
           BaseColumns._ID,
           MediaColumns.TITLE,
           MediaColumns.DATA,
           AudioColumns.ALBUM,
           AudioColumns.ARTIST,
           AudioColumns.ARTIST_ID
         };
     StringBuilder selection = new StringBuilder();
     selection.append(AudioColumns.IS_MUSIC + "=1");
     selection.append(" AND " + MediaColumns.TITLE + " != ''");
     Uri uri = Audio.Media.EXTERNAL_CONTENT_URI;
     long[] mNowPlaying = MusicUtils.getQueue();
     if (mNowPlaying.length == 0) {}
     selection = new StringBuilder();
     selection.append(BaseColumns._ID + " IN (");
     for (int i = 0; i < mNowPlaying.length; i++) {
       selection.append(mNowPlaying[i]);
       if (i < mNowPlaying.length - 1) {
         selection.append(",");
       }
     }
     selection.append(")");
     mCursor = MusicUtils.query(getActivity(), uri, cols, selection.toString(), null, null);
     mTrackAdapter.changeCursor(mCursor);
   }
 }
 @Override
 public boolean onContextItemSelected(MenuItem item) {
   switch (item.getItemId()) {
     case PLAY_SELECTION:
       int position = mSelectedPosition;
       MusicUtils.playAll(getActivity(), mCursor, position);
       break;
     case ADD_TO_PLAYLIST:
       {
         Intent intent = new Intent(INTENT_ADD_TO_PLAYLIST);
         long[] list = new long[] {mSelectedId};
         intent.putExtra(INTENT_PLAYLIST_LIST, list);
         getActivity().startActivity(intent);
         break;
       }
     case USE_AS_RINGTONE:
       MusicUtils.setRingtone(getActivity(), mSelectedId);
       break;
     case REMOVE:
       {
         removePlaylistItem(mSelectedPosition);
         break;
       }
     case SEARCH:
       {
         MusicUtils.doSearch(getActivity(), mCursor, mTitleIndex);
         break;
       }
     default:
       break;
   }
   return super.onContextItemSelected(item);
 }
 @Override
 public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
   if (mCursor instanceof NowPlayingCursor) {
     if (MusicUtils.mService != null) {
       MusicUtils.setQueuePosition(position);
       return;
     }
   }
   MusicUtils.playAll(getActivity(), mCursor, position);
 }
 /** Shuffle all the tracks */
 public void shuffleAll() {
   Uri uri = Audio.Media.EXTERNAL_CONTENT_URI;
   String[] projection = new String[] {BaseColumns._ID};
   String selection = AudioColumns.IS_MUSIC + "=1";
   String sortOrder = Audio.Media.DEFAULT_SORT_ORDER;
   Cursor cursor = MusicUtils.query(this, uri, projection, selection, null, sortOrder);
   if (cursor != null) {
     MusicUtils.shuffleAll(this, cursor);
     cursor.close();
     cursor = null;
   }
 }
 @Override
 public boolean onContextItemSelected(MenuItem item) {
   switch (item.getItemId()) {
     case PLAY_SELECTION:
       long[] list =
           MusicUtils.getSongListForGenre(getActivity(), Long.parseLong(mCurrentGenreId));
       MusicUtils.playAll(getActivity(), list, 0);
       break;
     default:
       break;
   }
   return super.onContextItemSelected(item);
 }
  /** @param which */
  private void removePlaylistItem(int which) {

    mCursor.moveToPosition(which);
    long id = mCursor.getLong(mMediaIdIndex);
    if (mPlaylistId >= 0) {
      Uri uri = Playlists.Members.getContentUri(EXTERNAL, mPlaylistId);
      getActivity().getContentResolver().delete(uri, Playlists.Members.AUDIO_ID + "=" + id, null);
    } else if (mPlaylistId == PLAYLIST_QUEUE) {
      MusicUtils.removeTrack(id);
      reloadQueueCursor();
    } else if (mPlaylistId == PLAYLIST_FAVORITES) {
      MusicUtils.removeFromFavorites(getActivity(), id);
    }
    mListView.invalidateViews();
  }
  /** @return current time */
  private long refreshNow() {
    if (MusicUtils.mService == null) return 500;
    try {
      long pos = mPosOverride < 0 ? MusicUtils.mService.position() : mPosOverride;
      long remaining = 1000 - (pos % 1000);
      if ((pos >= 0) && (mDuration > 0)) {
        mCurrentTime.setText(MusicUtils.makeTimeString(getActivity(), pos / 1000));

        if (MusicUtils.mService.isPlaying()) {
          mCurrentTime.setVisibility(View.VISIBLE);
          mCurrentTime.setTextColor(getResources().getColor(R.color.transparent_black));
        } else {
          // blink the counter
          int col = mCurrentTime.getCurrentTextColor();
          mCurrentTime.setTextColor(
              col == getResources().getColor(R.color.transparent_black)
                  ? getResources().getColor(R.color.holo_blue_dark)
                  : getResources().getColor(R.color.transparent_black));
          remaining = 500;
        }

        mProgress.setProgress((int) (1000 * pos / mDuration));
      } else {
        mCurrentTime.setText("--:--");
        mProgress.setProgress(1000);
      }
      return remaining;
    } catch (RemoteException ex) {
      ex.printStackTrace();
    }
    return 500;
  }
  /** Respond to clicks on actionbar options */
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.action_search:
        onSearchRequested();
        break;

      case R.id.action_settings:
        startActivityForResult(new Intent(this, SettingsHolder.class), 0);
        break;

      case R.id.action_eqalizer:
        Intent i = new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL);
        i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, MusicUtils.getCurrentAudioId());
        startActivityForResult(i, 0);
        break;

      case R.id.action_shuffle_all:
        shuffleAll();
        break;

      default:
        return super.onOptionsItemSelected(item);
    }
    return true;
  }
  @Override
  protected void onStop() {
    // Unbind
    if (MusicUtils.mService != null) MusicUtils.unbindFromService(mToken);

    // TODO: clear image cache

    super.onStop();
  }
  @Override
  protected void onStart() {

    // Bind to Service
    mToken = MusicUtils.bindToService(this, this);

    IntentFilter filter = new IntentFilter();
    filter.addAction(ApolloService.META_CHANGED);
    super.onStart();
  }
  /** Update what's playing */
  private void updateMusicInfo() {
    if (MusicUtils.mService == null) {
      return;
    }

    String artistName = MusicUtils.getArtistName();
    String albumName = MusicUtils.getAlbumName();
    String albumId = String.valueOf(MusicUtils.getCurrentAlbumId());
    mDuration = MusicUtils.getDuration();
    mTotalTime.setText(MusicUtils.makeTimeString(getActivity(), mDuration / 1000));

    ImageInfo mInfo = new ImageInfo();
    mInfo.type = TYPE_ALBUM;
    mInfo.size = SIZE_NORMAL;
    mInfo.source = SRC_FIRST_AVAILABLE;
    mInfo.data = new String[] {albumId, artistName, albumName};

    AlbumArtFragment cur =
        (AlbumArtFragment) mPagerAdapter.getItem(mAlbumArtPager.getCurrentItem());
    ImageProvider.getInstance(getActivity()).loadImage(cur.albumArt, mInfo);
  }
  @Override
  public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String[] projection =
        new String[] {BaseColumns._ID, MediaColumns.TITLE, AudioColumns.ALBUM, AudioColumns.ARTIST};
    StringBuilder where = new StringBuilder();
    String sortOrder = Audio.Media.DEFAULT_SORT_ORDER;
    where.append(AudioColumns.IS_MUSIC + "=1").append(" AND " + MediaColumns.TITLE + " != ''");
    Uri uri = Audio.Media.EXTERNAL_CONTENT_URI;
    if (getArguments() != null) {
      mPlaylistId = getArguments().getLong(BaseColumns._ID);
      String mimeType = getArguments().getString(MIME_TYPE);
      if (Audio.Playlists.CONTENT_TYPE.equals(mimeType)) {
        where = new StringBuilder();
        where.append(AudioColumns.IS_MUSIC + "=1");
        where.append(" AND " + MediaColumns.TITLE + " != ''");
        switch ((int) mPlaylistId) {
          case (int) PLAYLIST_QUEUE:
            uri = Audio.Media.EXTERNAL_CONTENT_URI;
            long[] mNowPlaying = MusicUtils.getQueue();
            if (mNowPlaying.length == 0) return null;
            where = new StringBuilder();
            where.append(BaseColumns._ID + " IN (");
            if (mNowPlaying == null || mNowPlaying.length <= 0) return null;
            for (long queue_id : mNowPlaying) {
              where.append(queue_id + ",");
            }
            where.deleteCharAt(where.length() - 1);
            where.append(")");
            break;
          case (int) PLAYLIST_FAVORITES:
            long favorites_id = MusicUtils.getFavoritesId(getActivity());
            projection =
                new String[] {
                  Playlists.Members._ID,
                  Playlists.Members.AUDIO_ID,
                  MediaColumns.TITLE,
                  AudioColumns.ALBUM,
                  AudioColumns.ARTIST
                };
            uri = Playlists.Members.getContentUri(EXTERNAL, favorites_id);
            sortOrder = Playlists.Members.DEFAULT_SORT_ORDER;
            break;
          default:
            if (id < 0) return null;
            projection =
                new String[] {
                  Playlists.Members._ID,
                  Playlists.Members.AUDIO_ID,
                  MediaColumns.TITLE,
                  AudioColumns.ALBUM,
                  AudioColumns.ARTIST,
                  AudioColumns.DURATION
                };

            uri = Playlists.Members.getContentUri(EXTERNAL, mPlaylistId);
            sortOrder = Playlists.Members.DEFAULT_SORT_ORDER;
            break;
        }
      } else if (Audio.Genres.CONTENT_TYPE.equals(mimeType)) {
        long genreId = getArguments().getLong(BaseColumns._ID);
        uri = Genres.Members.getContentUri(EXTERNAL, genreId);
        projection =
            new String[] {
              BaseColumns._ID, MediaColumns.TITLE, AudioColumns.ALBUM, AudioColumns.ARTIST
            };
        where = new StringBuilder();
        where.append(AudioColumns.IS_MUSIC + "=1").append(" AND " + MediaColumns.TITLE + " != ''");
        sortOrder = Genres.Members.DEFAULT_SORT_ORDER;
      } else {
        if (Audio.Albums.CONTENT_TYPE.equals(mimeType)) {
          long albumId = getArguments().getLong(BaseColumns._ID);
          where.append(" AND " + AudioColumns.ALBUM_ID + "=" + albumId);
          sortOrder = Audio.Media.TRACK + ", " + sortOrder;
        } else if (Audio.Artists.CONTENT_TYPE.equals(mimeType)) {
          sortOrder = MediaColumns.TITLE;
          long artist_id = getArguments().getLong(BaseColumns._ID);
          where.append(" AND " + AudioColumns.ARTIST_ID + "=" + artist_id);
        }
      }
    }
    return new CursorLoader(getActivity(), uri, projection, where.toString(), null, sortOrder);
  }