@Override
 public void onDestroy() {
   super.onDestroy();
   Log.d(TAG, " onDestroy ");
   libraryCursor.close();
   dbutils.close();
 }
  private void showTitleDescriptionDialog() {
    // Launch Title/Description Edit View
    LayoutInflater inflater =
        (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final View title_descr = inflater.inflate(R.layout.title_and_desc, null);
    // preload any existing title and description
    String[] strs = dbutils.getTitleAndDescriptionFromID(new String[] {Long.toString(sdrecord_id)});
    final EditText title_edittext = (EditText) title_descr.findViewById(R.id.EditTextTitle);
    final EditText desc_edittext = (EditText) title_descr.findViewById(R.id.EditTextDescr);

    title_edittext.setText(strs[0]);
    desc_edittext.setText(strs[1]);

    final Dialog d = new Dialog(this);
    Window w = d.getWindow();
    w.setFlags(
        WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
    d.setTitle(R.string.rename_video);
    // the edit layout defined in an xml file (in res/layout)
    d.setContentView(title_descr);
    // Cancel
    Button cbutton = (Button) d.findViewById(R.id.button2Cancel);
    cbutton.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            d.dismiss();
          }
        });
    // Edit
    Button ebutton = (Button) d.findViewById(R.id.button1Edit);
    ebutton.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            // save title and description to DB.
            String title_str = title_edittext.getText().toString();
            String desc_str = desc_edittext.getText().toString();
            String[] ids = new String[] {Long.toString(sdrecord_id)};

            Log.d(TAG, "New title and description is " + title_str + ":" + desc_str);

            dbutils.updateTitleAndDescription(title_str, desc_str, ids);

            reloadList();

            d.dismiss();
          }
        });
    d.show();
  }
  public boolean onContextItemSelected(MenuItem item) {

    AdapterView.AdapterContextMenuInfo info =
        (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    Log.d(TAG, " got " + item.getItemId() + " at position " + info.position);

    if (!videos_available) {
      return true;
    }

    movieurl = video_absolutepath[info.position];
    sdrecord_id = video_ids[info.position];
    moviefilename = video_filename[info.position];
    hosted_url = hosted_urls[info.position];
    Log.d(
        TAG,
        " operation on "
            + movieurl
            + " id "
            + sdrecord_id
            + " filename "
            + moviefilename
            + " hosted url "
            + hosted_url);

    switch (item.getItemId()) {
      case MENU_ITEM_1:
        // play
        pu.launchVideoPlayer(this, movieurl);
        break;

      case MENU_ITEM_2:
        // delete

        // ask if sure they want to delete ?
        AlertDialog delete_dialog =
            new AlertDialog.Builder(this)
                .setMessage(R.string.really_delete_video)
                .setPositiveButton(
                    R.string.yes,
                    new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int whichButton) {

                        // deleting files,
                        if (!pu.deleteVideo(movieurl)) {
                          Log.w(TAG, "Cant delete file " + movieurl);
                        }
                        // and removing DB records!
                        if (dbutils.deleteSDFileRecord(sdrecord_id) == -1) {
                          Log.w(TAG, "Cant delete record " + sdrecord_id);
                        }

                        reloadList();
                      }
                    })
                .setNegativeButton(
                    R.string.cancel,
                    new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int whichButton) {}
                    })
                .show();

        break;

      case MENU_ITEM_3:
        // publish to video bin
        String[] strs_vb =
            dbutils.getTitleAndDescriptionFromID(new String[] {Long.toString(sdrecord_id)});
        // grab thread
        thread_vb =
            pu.videoUploadToVideoBin(
                this,
                handler,
                movieurl,
                strs_vb[0],
                strs_vb[1] + "\n" + getString(R.string.uploaded_by_),
                emailPreference,
                sdrecord_id);
        break;

      case MENU_ITEM_4:
        // email
        pu.launchEmailIntentWithCurrentVideo(this, movieurl);
        break;

      case MENU_ITEM_6:
        // FTP server upload
        thread_ftp =
            pu.videoUploadToFTPserver(
                this, handler, moviefilename, movieurl, emailPreference, sdrecord_id);

        break;

      case MENU_ITEM_7:
        // youtube

        String possibleEmail = null;
        // We need a linked google account for youtube.
        Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");

        /*
        for (Account account : accounts) {
        	// TODO: Check possibleEmail against an email regex or treat
        	// account.name as an email address only for certain
        	// account.type values.
        	possibleEmail = account.name;
        	Log.d(TAG, "Could use : " + possibleEmail);
        }*/

        possibleEmail = accounts[0].name;

        if (possibleEmail != null) {
          Log.d(TAG, "Using account name for youtube upload .. " + possibleEmail);
          // This launches the youtube upload process
          pu.getYouTubeAuthTokenWithPermissionAndUpload(
              this, possibleEmail, movieurl, handler, emailPreference, sdrecord_id);
        } else {

          // throw up dialog
          AlertDialog no_email =
              new AlertDialog.Builder(this)
                  .setMessage(R.string.no_email_account_for_youtube)
                  .setPositiveButton(
                      R.string.yes,
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {}
                      })
                  .show();
        }
        break;

      case MENU_ITEM_8:
        // Title and Description of Video

        showTitleDescriptionDialog();

        break;

      case MENU_ITEM_9:
        // Email the HOSTED URL field of the currently selected video

        if (hosted_url != null && hosted_url.length() > 0) {
          Intent i = new Intent(Intent.ACTION_SEND);
          i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          i.setType("message/rfc822");
          i.putExtra(Intent.EXTRA_TEXT, hosted_url);
          this.startActivity(i);
        } else {
          Toast.makeText(
                  this,
                  R.string.video_is_not_uploaded_yet_no_hosted_url_available_,
                  Toast.LENGTH_LONG)
              .show();
        }

        break;

      case MENU_ITEM_12:
        // View the HOSTED URL field of the currently selected video in a
        // web browser.

        if (hosted_url != null && hosted_url.length() > 0) {
          Intent i2 = new Intent(Intent.ACTION_VIEW);
          i2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          i2.setData(Uri.parse(hosted_url));
          this.startActivity(i2);
        } else {
          Toast.makeText(
                  this,
                  R.string.video_is_not_uploaded_yet_no_hosted_url_available_,
                  Toast.LENGTH_LONG)
              .show();
        }
        break;
    }

    return true;
  }
  private void makeCursorAndAdapter() {
    dbutils.genericWriteOpen();

    // This query is for videofiles only, no joins.

    // libraryCursor = dbutils.generic_write_db.query(
    // DatabaseHelper.SDFILERECORD_TABLE_NAME, null, null, null, null,
    // null, DatabaseHelper.SDFileRecord.DEFAULT_SORT_ORDER);

    // SELECT
    /*
    		String join_sql = " SELECT a.filename as filename , a.filepath as filepath, a.length_secs as length_secs , a.created_datetime as created_datetime, a._id as _id, a.title as title, a.description as description, "
    				+ " b.host_uri as host_uri , b.host_video_url as host_video_url FROM "
    				+ " videofiles a LEFT OUTER JOIN hosts b ON "
    				+ " a._id = b.sdrecord_id "
    				+ " ORDER BY a.created_datetime DESC ";
    */
    String join_sql =
        " SELECT a.filename as filename , a.filepath as filepath, a.created_datetime as created_datetime, a._id as _id,"
            + " b.host_uri as host_uri , b.host_video_url as host_video_url FROM "
            + " videofiles a LEFT OUTER JOIN hosts b ON "
            + " a._id = b.sdrecord_id "
            + " ORDER BY a.created_datetime DESC ";

    libraryCursor = dbutils.generic_write_db.rawQuery(join_sql, null);

    if (libraryCursor.moveToFirst()) {
      ArrayList<Integer> video_ids_al = new ArrayList<Integer>();
      ArrayList<String> video_paths_al = new ArrayList<String>();
      ArrayList<String> video_filenames_al = new ArrayList<String>();
      ArrayList<String> hosted_urls_al = new ArrayList<String>();

      do {
        long video_id =
            libraryCursor.getLong(
                libraryCursor.getColumnIndexOrThrow(DatabaseHelper.SDFileRecord._ID));
        video_ids_al.add((int) video_id);

        String video_path =
            libraryCursor.getString(
                libraryCursor.getColumnIndexOrThrow(DatabaseHelper.SDFileRecord.FILEPATH));
        video_paths_al.add(video_path);

        String video_filename =
            libraryCursor.getString(
                libraryCursor.getColumnIndexOrThrow(DatabaseHelper.SDFileRecord.FILENAME));
        video_filenames_al.add(video_filename);

        String hosted_url =
            libraryCursor.getString(
                libraryCursor.getColumnIndexOrThrow(DatabaseHelper.HostDetails.HOST_VIDEO_URL));
        hosted_urls_al.add(hosted_url);

      } while (libraryCursor.moveToNext());

      video_ids = video_ids_al.toArray(new Integer[video_ids_al.size()]);
      video_absolutepath = video_paths_al.toArray(new String[video_paths_al.size()]);
      video_filename = video_filenames_al.toArray(new String[video_filenames_al.size()]);
      hosted_urls = hosted_urls_al.toArray(new String[hosted_urls_al.size()]);

      videos_available = true;

    } else {

      videos_available = false;
    }

    // Make Cursor Adapter

    String[] from =
        new String[] {
          DatabaseHelper.SDFileRecord.FILENAME,
          //	DatabaseHelper.SDFileRecord.LENGTH_SECS,
          DatabaseHelper.SDFileRecord.CREATED_DATETIME,

          // Linked HOSTs details
          DatabaseHelper.HostDetails.HOST_VIDEO_URL,

          //				DatabaseHelper.SDFileRecord.TITLE,
          //				DatabaseHelper.SDFileRecord.DESCRIPTION,
          DatabaseHelper.SDFileRecord.FILEPATH,
        };

    int[] to =
        new int[] {
          android.R.id.text1,
          // android.R.id.text2,
          R.id.text3,
          R.id.text4,
          // , R.id.text5, R.id.text6,
          R.id.videoThumbnailimageView
        };

    listAdapter =
        new VideoFilesSimpleCursorAdapter(
            this, R.layout.library_list_item, libraryCursor, from, to);

    listAdapter.setViewBinder(
        new SimpleCursorAdapter.ViewBinder() {
          public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            // Transform the text4 specifically, from a blank entry
            // repr. into a string saying "not uploaded yet"
            if (columnIndex
                == cursor.getColumnIndexOrThrow(DatabaseHelper.HostDetails.HOST_VIDEO_URL)) {
              String url =
                  cursor.getString(
                      cursor.getColumnIndexOrThrow(DatabaseHelper.HostDetails.HOST_VIDEO_URL));
              TextView host_details = (TextView) view.findViewById(R.id.text4);

              if ("".equals(url) || url == null || url.length() <= 0) {
                url = "Not uploaded yet.";
              }
              host_details.setText(url);

              return true;
            }

            // Transform the text3 specifically, from time in millis to text
            // repr.
            if (columnIndex
                == cursor.getColumnIndexOrThrow(DatabaseHelper.SDFileRecord.CREATED_DATETIME)) {
              long time_in_mills =
                  cursor.getLong(
                      cursor.getColumnIndexOrThrow(DatabaseHelper.SDFileRecord.CREATED_DATETIME));
              TextView datetime = (TextView) view.findViewById(R.id.text3);
              datetime.setText(PublishingUtils.showDate(time_in_mills));
              return true;
            }
            return false;
          }
        });

    setListAdapter(listAdapter);

    dbutils.close();
  }