@Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   switch (requestCode) {
     case REQUEST_ENABLE_BLUETOOTH:
       if (resultCode == BluetoothService.BLUETOOTH_DISCOVERABLE_DURATION) {
         bService.bluetoothDiscoverable();
       } else {
         // User did not enable Bluetooth or an error occured
       }
       break;
   }
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // open up the DbAdaptor
    db.open();

    // gives us more screen space
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    // need to do this because the camera doesn't do portrait mode
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    // initialize all our views.
    LayoutInflater inflater = getLayoutInflater();
    viewCaptureNote = inflater.inflate(R.layout.view_capture_note, null);
    viewNote = inflater.inflate(R.layout.view_note, null);
    viewTagList = inflater.inflate(R.layout.view_tag_list, null);
    viewNoteGallery = inflater.inflate(R.layout.view_note_gallery, null);

    // set the content view initially to save notes
    setContentView(viewCaptureNote);

    // set up the click listeners for the camera preview screen
    CameraPreview cameraPreview = (CameraPreview) findViewById(R.id.surface);
    findViewById(R.id.discard).setOnClickListener(cameraPreview);
    findViewById(R.id.take).setOnClickListener(cameraPreview);
    findViewById(R.id.save_untagged).setOnClickListener(cameraPreview);
    findViewById(R.id.save_and_tag).setOnClickListener(cameraPreview);

    // set up the 'view untagged' option in the list menu
    View someView = viewTagList.findViewById(R.id.tag_list_untagged);
    someView.findViewById(R.id.tag_subtags).setVisibility(View.GONE);
    ((TextView) someView.findViewById(R.id.tag_name)).setText("Click to view untagged notes");
    someView.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            Gallery g = (Gallery) viewNoteGallery.findViewById(R.id.note_gallery);
            g.setAdapter(new NoteGalleryImageAdaptor(SBActivity.this, db.getUntaggedNotes()));
            setContentView(viewNoteGallery);
          }
        });

    // set the list adaptor for our tag list
    final ListView lv = (ListView) viewTagList.findViewById(R.id.item_list);
    lv.setAdapter(new TagViewListAdaptor(this, db.getTagList()));
    registerForContextMenu(lv);
    lv.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            TextView v = (TextView) view.findViewById(R.id.tag_subtags);
            v.setVisibility(v.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
            long tagId = (Long) view.findViewById(R.id.tag_name).getTag();
            if (v.getVisibility() == View.VISIBLE) {
              int subtagCount = 0;
              StringBuilder subTags = new StringBuilder("Sub-tags: ");
              Cursor c = db.getSubTags(tagId);
              while (c.moveToNext()) {
                subTags.append(c.getString(1) + " ");
                subtagCount++;
              }
              if (subtagCount > 0) v.setText(subTags);
              else v.setText("No sub-tags.");
            }
          }
        });
    lv.setOnCreateContextMenuListener(
        new View.OnCreateContextMenuListener() {
          public void onCreateContextMenu(
              ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            menu.setHeaderIcon(android.R.drawable.ic_menu_info_details);
            ListView lv = (ListView) viewTagList.findViewById(R.id.item_list);
            Cursor listItem =
                (Cursor)
                    lv.getItemAtPosition(((AdapterView.AdapterContextMenuInfo) menuInfo).position);
            String tagName = listItem.getString(1);
            menu.setHeaderTitle("Tag '" + tagName + "'");
            menu.add(0, CONTEXT_VIEW_NOTES, 0, "View notes tagged with '" + tagName + "'");
            menu.add(0, CONTEXT_DELETE_TAG, 0, "Delete tag");
          }
        });

    // set up click listeners for add tag
    viewTagList
        .findViewById(R.id.save_tag)
        .setOnClickListener(
            new View.OnClickListener() {
              public void onClick(View view) {
                EditText editText = (EditText) viewTagList.findViewById(R.id.tag_id);
                if (editText.getText().length() == 0) return;
                db.addNewTag(editText.getText());
                ((TagViewListAdaptor) lv.getAdapter()).refreshData();
                Toast.makeText(
                        SBActivity.this,
                        "Tag '" + editText.getText() + "' added.",
                        Toast.LENGTH_SHORT)
                    .show();
                editText.setText("");
              }
            });
    viewTagList.setOnFocusChangeListener(
        new View.OnFocusChangeListener() {
          @Override
          public void onFocusChange(View view, boolean b) {
            Log.i(TAG, "Focus changed innit: " + b);
            if (b) ((TagViewListAdaptor) lv.getAdapter()).refreshData();
          }
        });

    // set up our note viewing gallery
    final Gallery g = (Gallery) viewNoteGallery.findViewById(R.id.note_gallery);
    g.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            // set the note number i.e. 1/3
            ((TextView) viewNoteGallery.findViewById(R.id.gallery_note_number))
                .setText((i + 1) + " / " + g.getCount());

            // set the date field
            Date d = new Date(((Note) view.getTag()).getSaveTime());
            ((TextView) viewNoteGallery.findViewById(R.id.gallery_note_date))
                .setText(DateFormat.getDateTimeInstance().format(d));

            // set the tag field
            Cursor c = db.getTagListForImg(l);
            StringBuilder sb = new StringBuilder();
            while (c.moveToNext()) {
              if (c.getInt(2) == 0) continue;
              sb.append(c.getString(1));
              sb.append(", ");
            }
            // delete the last 2 chars: ", "
            if (sb.length() > 0) sb.delete(sb.length() - 2, sb.length());
            else sb.append("none");
            ((TextView) viewNoteGallery.findViewById(R.id.gallery_note_tags))
                .setText(sb.toString());
          }

          @Override
          public void onNothingSelected(AdapterView<?> adapterView) {}
        });
    g.setOnItemLongClickListener(
        new AdapterView.OnItemLongClickListener() {
          @Override
          public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

            return true;
          }
        });
    viewNoteGallery
        .findViewById(R.id.note_gallery_examine)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                Note n = (Note) ((View) g.getSelectedView()).getTag();
                setViewSingleNote(n.getFileName());
              }
            });

    Handler btProgressHandler =
        new Handler() {
          public void handleMessage(Message msg) {
            if (btProgressDialog == null) return;
            switch (msg.what) {
              case BluetoothService.MSG_CONNECTED:
                btProgressDialog.setMessage("Bluetooth connected! Sending updates...");
                break;
              case BluetoothService.MSG_RECEIVING:
                btProgressDialog.setMessage("Receiving updates from computer..");
                break;
              case BluetoothService.MSG_PROGRESS:
                int cur = msg.arg1;
                int max = msg.arg2;
                btProgressDialog.setProgress(cur);
                btProgressDialog.setMax(max);
                break;
              case BluetoothService.MSG_DONE:
                btProgressDialog.dismiss();
                break;
            }
          }
        };
    bService.setProgressHandler(btProgressHandler);
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_view_tags:
        // little hack to refresh the data in our tag list view when we open it
        ListView lv = (ListView) viewTagList.findViewById(R.id.item_list);
        ((TagViewListAdaptor) lv.getAdapter()).refreshData();
        setContentView(viewTagList);
        return true;
      case R.id.menu_delete_note:
        Note n = ((NoteView) viewNote).getNote();
        db.deleteTag(n.getId());
        Toast.makeText(SBActivity.this, "Note " + n.getId() + " deleted.", Toast.LENGTH_SHORT)
            .show();
        goBack();
        return true;
      case R.id.menu_save_note:
        setContentView(viewCaptureNote);
        return true;
      case R.id.menu_tag_note:
        final Note curNote = ((NoteView) viewNote).getNote();
        final Cursor c = db.getTagListForImg(curNote.getId());
        CharSequence[] items = new CharSequence[c.getCount()];
        for (int i = 0; i < items.length; i++) {
          c.moveToNext();
          items[i] = c.getString(1);
        }

        final boolean[] checked = new boolean[c.getCount()];
        c.moveToFirst();
        for (int i = 0; i < items.length; i++) {
          checked[i] = c.getInt(2) == 1;
          c.moveToNext();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder
            .setTitle("Set tags for note " + curNote.getId())
            .setIcon(android.R.drawable.ic_menu_edit)
            .setMultiChoiceItems(
                items,
                checked,
                new DialogInterface.OnMultiChoiceClickListener() {
                  @Override
                  public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                    c.moveToPosition(i);
                    db.setTagForNote(curNote.getId(), c.getLong(0), b);
                  }
                });
        builder.show();
        return true;
      case R.id.menu_bluetooth_sync:
        Cursor c1 = getDbAdaptor().getUpdateList(null);
        int idxId = c1.getColumnIndex("_id");
        int idxTable = c1.getColumnIndex("table_name");
        int idxTarget = c1.getColumnIndex("target_id");
        int idxTarget2 = c1.getColumnIndex("target2_id");
        int idxType = c1.getColumnIndex("update_type");
        int idxTime = c1.getColumnIndex("update_time");
        Log.i(getClass().getName(), "Update list:");
        while (c1.moveToNext()) {
          Log.i(
              getClass().getName(),
              " [_id="
                  + c1.getInt(idxId)
                  + "] "
                  + (c1.getInt(idxType) == DbAdaptor.UPDATE_TYPE_ADD ? "Added" : "Deleted")
                  + " "
                  + "id "
                  + c1.getInt(idxTarget)
                  + (!c1.isNull(idxTarget2) ? " (id2 " + c1.getInt(idxTarget2) + ")" : "")
                  + " in table "
                  + c1.getString(idxTable)
                  + " (@ "
                  + new Date(c1.getInt(idxTime))
                  + ")");
        }

        if (bService.requestEnableBluetooth()) bService.bluetoothDiscoverable();
        return true;
    }
    return false;
  }
 @Override
 public void onDestroy() {
   super.onDestroy();
   bService.cancel();
   db.close();
 }