@Override
  public void onDestroyView() {
    super.onDestroyView();

    if (mLibrary != null) {
      mLibrary.closeDatabase();
      mAdapters.clear();
    }
  }
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          MyLibraryItem item = mAdapters.getLast().getItem(position);

          switch (item.getLevel()) {
            case MyLibrary.LVL_ARTIST:
              LibraryAdapter album =
                  new LibraryAdapter(
                      getActivity(),
                      mLibrary.getAlbums(item.getArtist()),
                      mLibrary,
                      MyLibrary.LVL_ALBUM);
              mAdapters.add(album);
              showList();
              break;
            case MyLibrary.LVL_ALBUM:
              LibraryAdapter title =
                  new LibraryAdapter(
                      getActivity(),
                      mLibrary.getTitles(item.getArtist(), item.getAlbum()),
                      mLibrary,
                      MyLibrary.LVL_TITLE);
              mAdapters.add(title);
              showList();
              break;
            case MyLibrary.LVL_TITLE:
              Message msg = Message.obtain();
              LinkedList<String> urls = new LinkedList<String>();
              urls.add(item.getUrl());
              msg.obj =
                  ClementineMessageFactory.buildInsertUrl(
                      App.mClementine.getPlaylistManager().getActivePlaylistId(), urls);
              App.mClementineConnection.mHandler.sendMessage(msg);

              Toast.makeText(
                      getActivity(),
                      String.format(getString(R.string.library_songs_added), 1),
                      Toast.LENGTH_SHORT)
                  .show();
              break;
            default:
              break;
          }
        }
        @Override
        public void OnLibraryDownloadFinished(DownloaderResult result) {
          mProgressDialog.dismiss();
          App.libraryDownloader = null;

          if (result.getResult() == DownloadResult.SUCCESSFUL) {
            if (mLibrary != null) {
              mLibrary.closeDatabase();
            }
            mLibrary = new MyLibrary(getActivity());
            mLibrary.openDatabase();
            LibraryAdapter a =
                new LibraryAdapter(
                    getActivity(), mLibrary.getArtists(), mLibrary, MyLibrary.LVL_ARTIST);
            mAdapters.add(a);
            showList();
          } else {
            Utilities.ShowMessageDialog(
                getActivity(), R.string.library_download_error, result.getMessageId());
          }
        }
 private boolean addSongsToPlaylist(MyLibraryItem libraryItem) {
   switch (libraryItem.getLevel()) {
     case MyLibrary.LVL_ARTIST:
       MyLibrary addArtist = new MyLibrary(getActivity());
       addArtist.addOnLibrarySelectFinishedListener(LibraryFragment.this);
       addArtist.getAllTitlesFromArtistAsync(libraryItem.getArtist());
       return true;
     case MyLibrary.LVL_ALBUM:
       MyLibrary addAlbums = new MyLibrary(getActivity());
       addAlbums.addOnLibrarySelectFinishedListener(LibraryFragment.this);
       addAlbums.getTitlesAsync(libraryItem.getArtist(), libraryItem.getAlbum());
       return true;
     case MyLibrary.LVL_TITLE:
       Message msg = Message.obtain();
       LinkedList<String> urls = new LinkedList<String>();
       urls.add(libraryItem.getUrl());
       msg.obj =
           ClementineMessageFactory.buildInsertUrl(
               App.mClementine.getPlaylistManager().getActivePlaylistId(), urls);
       App.mClementineConnection.mHandler.sendMessage(msg);
       return false;
     default:
       return false;
   }
 }
  @SuppressLint({"InlinedApi", "NewApi"})
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.library_fragment, container, false);

    Log.d(TAG, "onCreateView");

    mLibraryPath = (TextView) view.findViewById(R.id.library_path);
    mList = (ListView) view.findViewById(R.id.library);
    mEmptyLibrary = view.findViewById(R.id.library_empty);

    mLibraryEmptyText = (TextView) mEmptyLibrary.findViewById(R.id.library_empty_txt);

    mList.setOnItemClickListener(oiclLibraryClick);
    mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    mList.setMultiChoiceModeListener(
        new MultiChoiceModeListener() {
          @Override
          public boolean onActionItemClicked(ActionMode mode, android.view.MenuItem item) {
            SparseBooleanArray checkedPositions = mList.getCheckedItemPositions();

            switch (item.getItemId()) {
              case R.id.library_context_add:
                for (int i = 0; i < checkedPositions.size(); ++i) {
                  int position = checkedPositions.keyAt(i);
                  if (checkedPositions.valueAt(i)) {
                    MyLibraryItem libraryItem = mAdapters.getLast().getItem(position);
                    addSongsToPlaylist(libraryItem);
                  }
                }
                mode.finish();
                return true;
              default:
                return false;
            }
          }

          @Override
          public boolean onCreateActionMode(ActionMode mode, android.view.Menu menu) {
            android.view.MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.library_context_menu, menu);
            return true;
          }

          @Override
          public boolean onPrepareActionMode(ActionMode mode, android.view.Menu menu) {
            return false;
          }

          @Override
          public void onDestroyActionMode(ActionMode mode) {}

          @Override
          public void onItemCheckedStateChanged(
              ActionMode mode, int position, long id, boolean checked) {}
        });

    // Create the adapter
    mLibrary = new MyLibrary(getActivity());
    mLibrary.removeDatabaseIfFromOtherClementine();
    if (App.libraryDownloader == null && mLibrary.databaseExists()) {
      mLibrary.openDatabase();
      LibraryAdapter a =
          new LibraryAdapter(getActivity(), mLibrary.getArtists(), mLibrary, MyLibrary.LVL_ARTIST);
      mAdapters.add(a);
    }

    showList();

    mActionBar.setTitle("");
    mActionBar.setSubtitle("");

    setHasOptionsMenu(true);

    return view;
  }
  /** Start the Download */
  private DownloaderResult startDownloading(ClementineMessage clementineMessage) {
    boolean downloadFinished = false;
    DownloaderResult result = new DownloaderResult(DownloadResult.SUCCESSFUL);
    File f = null;
    FileOutputStream fo = null;

    publishProgress(0);

    // Now request the songs
    mClient.sendRequest(clementineMessage);

    while (!downloadFinished) {
      // Check if the user canceled the process
      if (isCancelled()) {
        // Close the stream and delete the incomplete file
        try {
          if (fo != null) {
            fo.flush();
            fo.close();
          }
          if (f != null) {
            f.delete();
          }
        } catch (IOException e) {
        }
        Log.d(TAG, "isCancelled");
        break;
      }

      // Get the raw protocol buffer
      ClementineMessage message = mClient.getProtoc();

      if (message.isErrorMessage()) {
        result = new DownloaderResult(DownloadResult.CONNECTION_ERROR);
        break;
      }

      // Is the download forbidden?
      if (message.getMessageType() == MsgType.DISCONNECT) {
        result = new DownloaderResult(DownloadResult.FOBIDDEN);
        break;
      }

      // Ignore other elements!
      if (message.getMessageType() != MsgType.LIBRARY_CHUNK) {
        continue;
      }

      ResponseLibraryChunk chunk = message.getMessage().getResponseLibraryChunk();

      try {
        // Check if we need to create a new file
        if (f == null) {
          // Check if we have enougth free space
          // size times 2, because we optimise the table later and
          // need space for that too!
          if ((chunk.getSize() * 2) > Utilities.getFreeSpaceExternal()) {
            result = new DownloaderResult(DownloadResult.INSUFFIANT_SPACE);
            break;
          }
          f = mLibrary.getLibraryDb();

          // User wants to override files, so delete it here!
          // The check was already done in processSongOffer()
          if (f.exists()) {
            f.delete();
          }

          f.createNewFile();
          fo = new FileOutputStream(f);
        }

        // Write chunk to sdcard
        fo.write(chunk.getData().toByteArray());

        // Have we downloaded all chunks?
        if (chunk.getChunkCount() == chunk.getChunkNumber()) {
          fo.flush();
          fo.close();
          f = null;
          downloadFinished = true;
        }

        // Update notification
        updateProgress(chunk);
      } catch (IOException e) {
        result = new DownloaderResult(DownloaderResult.DownloadResult.NOT_MOUNTED);
        break;
      }
    }

    // Disconnect at the end
    mClient.disconnect(ClementineMessage.getMessage(MsgType.DISCONNECT));

    // Optimize library table
    if (mLibrary.getLibraryDb().exists()) {
      mLibrary.optimizeTable();
    }

    return result;
  }