Example usage for java.lang CharSequence charAt

List of usage examples for java.lang CharSequence charAt

Introduction

In this page you can find the example usage for java.lang CharSequence charAt.

Prototype

char charAt(int index);

Source Link

Document

Returns the char value at the specified index.

Usage

From source file:eu.stratosphere.types.StringValue.java

/**
 * Finds any occurrence of the <code>str</code> character sequence in this StringValue.
 * The search starts at position <code>start</code>.
 * /*from   w  w w.j a  v  a 2s.c  o  m*/
 * @return The position of the first occurrence of the search string in the string value, or <code>-1</code>, if
 *         the character sequence was not found.
 */
public int find(CharSequence str, int start) {
    final int pLen = this.len;
    final int sLen = str.length();

    if (sLen == 0) {
        throw new IllegalArgumentException("Cannot find empty string.");
    }

    int pPos = start;

    final char first = str.charAt(0);

    while (pPos < pLen) {
        if (first == this.value[pPos++]) {
            // matching first character
            final int fallBackPosition = pPos;
            int sPos = 1;
            boolean found = true;

            while (sPos < sLen) {
                if (pPos >= pLen) {
                    // no more characters in string value
                    pPos = fallBackPosition;
                    found = false;
                    break;
                }

                if (str.charAt(sPos++) != this.value[pPos++]) {
                    pPos = fallBackPosition;
                    found = false;
                    break;
                }
            }
            if (found) {
                return fallBackPosition - 1;
            }
        }
    }
    return -1;
}

From source file:com.snt.bt.recon.activities.MainActivity.java

public void writeTextFile(String data) {
    mDebugText.append(data);/*  w  ww  .  j av a2 s .  co m*/
    // Erase excessive lines
    int excessLineNumber = mDebugText.getLineCount() - MAX_LINE;
    if (excessLineNumber > 0) {
        int eolIndex = -1;
        CharSequence charSequence = mDebugText.getText();
        for (int i = 0; i < excessLineNumber; i++) {
            do {
                eolIndex++;
            } while (eolIndex < charSequence.length() && charSequence.charAt(eolIndex) != '\n');
        }
        if (eolIndex < charSequence.length()) {
            mDebugText.getEditableText().delete(0, eolIndex + 1);
        } else {
            mDebugText.setText("");
        }
    }
}

From source file:com.jecelyin.editor.v2.core.text.TextUtils.java

/**
 * Returns true if a and b are equal, including if they are both null.
 * <p><i>Note: In platform versions 1.1 and earlier, this method only worked well if
 * both the arguments were instances of String.</i></p>
 * @param a first CharSequence to check/*w w w. j a  v a  2 s.c o m*/
 * @param b second CharSequence to check
 * @return true if a and b are equal
 */
public static boolean equals(CharSequence a, CharSequence b) {
    if (a == b)
        return true;
    int length;
    if (a != null && b != null && (length = a.length()) == b.length()) {
        if (a instanceof String && b instanceof String) {
            return a.equals(b);
        } else {
            for (int i = 0; i < length; i++) {
                if (a.charAt(i) != b.charAt(i))
                    return false;
            }
            return true;
        }
    }
    return false;
}

From source file:net.opacapp.multilinecollapsingtoolbar.CollapsingTextHelper.java

private void calculateUsingTextSize(final float textSize) {
    if (mText == null)
        return;//from   w w  w  . j  a  v a 2  s  .  c o m
    final float availableWidth;
    final float newTextSize;
    boolean updateDrawText = false;
    // BEGIN MODIFICATION: Add maxLines variable
    int maxLines;
    // END MODIFICATION
    if (isClose(textSize, mCollapsedTextSize)) {
        availableWidth = mCollapsedBounds.width();
        newTextSize = mCollapsedTextSize;
        mScale = 1f;
        if (mCurrentTypeface != mCollapsedTypeface) {
            mCurrentTypeface = mCollapsedTypeface;
            updateDrawText = true;
        }
        // BEGIN MODIFICATION: Set maxLines variable
        maxLines = 1;
        // END MODIFICATION
    } else {
        availableWidth = mExpandedBounds.width();
        newTextSize = mExpandedTextSize;
        if (mCurrentTypeface != mExpandedTypeface) {
            mCurrentTypeface = mExpandedTypeface;
            updateDrawText = true;
        }
        if (isClose(textSize, mExpandedTextSize)) {
            // If we're close to the expanded text size, snap to it and use a scale of 1
            mScale = 1f;
        } else {
            // Else, we'll scale down from the expanded text size
            mScale = textSize / mExpandedTextSize;
        }
        // BEGIN MODIFICATION: Set maxLines variable
        maxLines = this.maxLines;
        // END MODIFICATION
    }
    if (availableWidth > 0) {
        updateDrawText = (mCurrentTextSize != newTextSize) || mBoundsChanged || updateDrawText;
        mCurrentTextSize = newTextSize;
        mBoundsChanged = false;
    }
    if (mTextToDraw == null || updateDrawText) {
        mTextPaint.setTextSize(mCurrentTextSize);
        mTextPaint.setTypeface(mCurrentTypeface);

        // BEGIN MODIFICATION: Text layout creation and text truncation
        StaticLayout layout = new StaticLayout(mText, mTextPaint, (int) availableWidth,
                Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
        CharSequence truncatedText;
        if (layout.getLineCount() > maxLines) {
            int lastLine = maxLines - 1;
            CharSequence textBefore = lastLine > 0 ? mText.subSequence(0, layout.getLineEnd(lastLine - 1)) : "";
            CharSequence lineText = mText.subSequence(layout.getLineStart(lastLine),
                    layout.getLineEnd(lastLine));
            // if last char in line is space, move it behind the ellipsis
            CharSequence lineEnd = "";
            if (lineText.charAt(lineText.length() - 1) == ' ') {
                lineEnd = lineText.subSequence(lineText.length() - 1, lineText.length());
                lineText = lineText.subSequence(0, lineText.length() - 1);
            }
            // insert ellipsis character
            lineText = TextUtils.concat(lineText, "\u2026", lineEnd);
            // if the text is too long, truncate it
            CharSequence truncatedLineText = TextUtils.ellipsize(lineText, mTextPaint, availableWidth,
                    TextUtils.TruncateAt.END);
            truncatedText = TextUtils.concat(textBefore, truncatedLineText);

        } else {
            truncatedText = mText;
        }
        if (!TextUtils.equals(truncatedText, mTextToDraw)) {
            mTextToDraw = truncatedText;
            mIsRtl = calculateIsRtl(mTextToDraw);
        }

        final Layout.Alignment alignment;

        // Don't rectify gravity for RTL languages, Layout.Alignment does it already.
        switch (mExpandedTextGravity & GravityCompat.RELATIVE_HORIZONTAL_GRAVITY_MASK) {
        case Gravity.CENTER_HORIZONTAL:
            alignment = Layout.Alignment.ALIGN_CENTER;
            break;
        case Gravity.RIGHT:
        case Gravity.END:
            alignment = Layout.Alignment.ALIGN_OPPOSITE;
            break;
        case Gravity.LEFT:
        case Gravity.START:
        default:
            alignment = Layout.Alignment.ALIGN_NORMAL;
            break;
        }

        mTextLayout = new StaticLayout(mTextToDraw, mTextPaint, (int) availableWidth, alignment, 1, 0, false);
        // END MODIFICATION
    }
}

From source file:eu.stratosphere.types.StringValue.java

/**
 * Checks whether the substring, starting at the specified index, starts with the given prefix string.
 * /*from  w  ww  . j  av  a 2s  .c o  m*/
 * @param prefix The prefix character sequence.
 * @param startIndex The position to start checking for the prefix.
 * 
 * @return True, if this StringValue substring, starting at position <code>startIndex</code> has </code>prefix</code>
 *         as its prefix.
 */
public boolean startsWith(CharSequence prefix, int startIndex) {
    final char[] thisChars = this.value;
    final int pLen = this.len;
    final int sLen = prefix.length();

    if ((startIndex < 0) || (startIndex > pLen - sLen)) {
        return false;
    }

    int sPos = 0;
    while (sPos < sLen) {
        if (thisChars[startIndex++] != prefix.charAt(sPos++)) {
            return false;
        }
    }
    return true;
}

From source file:eu.stratosphere.types.StringValue.java

/**
 * Sets the value of the StringValue to a substring of the given string.
 * //from  w  w  w. j a  va 2  s.  c o m
 * @param value The new string value.
 * @param offset The position to start the substring.
 * @param len The length of the substring.
 */
public void setValue(CharSequence value, int offset, int len) {
    Validate.notNull(value);
    if (offset < 0 || len < 0 || offset > value.length() - len) {
        throw new IndexOutOfBoundsException("offset: " + offset + " len: " + len + " value.len: " + len);
    }

    ensureSize(len);
    this.len = len;
    for (int i = 0; i < len; i++) {
        this.value[i] = value.charAt(offset + i);
    }
    this.len = len;
    this.hashCode = 0;
}

From source file:org.apache.noggit.JSONParser.java

public static void writeStringPart(CharSequence chars, int start, int end, CharArr out) {
        for (int i = start; i < end; i++) {
            char ch = chars.charAt(i);
            switch (ch) {
            case '"':
            case '\\':
                out.write('\\');
                out.write(ch);/*from www.jav  a  2s  .co  m*/
                break;
            case '\r':
                out.write('\\');
                out.write('r');
                break;
            case '\n':
                out.write('\\');
                out.write('n');
                break;
            case '\t':
                out.write('\\');
                out.write('t');
                break;
            case '\b':
                out.write('\\');
                out.write('b');
                break;
            case '\f':
                out.write('\\');
                out.write('f');
                break;
            // case '/':
            default:
                if (ch <= 0x1F) {
                    unicodeEscape(ch, out);
                } else {
                    out.write(ch);
                }
            }
        }
    }

From source file:it.unimi.dsi.util.ImmutableExternalPrefixMap.java

/** map external map.
 * /*from  w w  w . j a  va  2 s  .  c  om*/
 * <P>This constructor does not assume that strings returned by <code>terms.iterator()</code>
 * will be distinct. Thus, it can be safely used with {@link FileLinesCollection}.
 * 
 * @param terms an iterable whose iterator will enumerate in lexicographical order the terms for the map.
 * @param blockSizeInBytes the block size (in bytes).
 * @param dumpStreamFilename the name of the dump stream, or <code>null</code> for a map
 * with an automatic dump stream.
 */

public ImmutableExternalPrefixMap(final Iterable<? extends CharSequence> terms, final int blockSizeInBytes,
        final CharSequence dumpStreamFilename) throws IOException {
    this.blockSize = blockSizeInBytes * 8;
    this.selfContained = dumpStreamFilename == null;
    // First of all, we gather frequencies for all Unicode characters
    int[] frequency = new int[Character.MAX_VALUE + 1];
    int maxWordLength = 0;
    CharSequence s;
    int count = 0;

    final MutableString prevTerm = new MutableString();

    for (Iterator<? extends CharSequence> i = terms.iterator(); i.hasNext();) {
        s = i.next();
        maxWordLength = Math.max(s.length(), maxWordLength);
        for (int j = s.length(); j-- != 0;)
            frequency[s.charAt(j)]++;
        if (count > 0 && prevTerm.compareTo(s) >= 0)
            throw new IllegalArgumentException(
                    "The provided term collection is not sorted, or contains duplicates [" + prevTerm + ", " + s
                            + "]");
        count++;
        prevTerm.replace(s);
    }

    size = count;

    // Then, we compute the number of actually used characters
    count = 0;
    for (int i = frequency.length; i-- != 0;)
        if (frequency[i] != 0)
            count++;

    /* Now we remap used characters in f, building at the same time maps from 
     * symbol to characters and from characters to symbols. */

    int[] packedFrequency = new int[count];
    symbol2char = new char[count];
    char2symbol = new Char2IntOpenHashMap(count);
    char2symbol.defaultReturnValue(-1);

    for (int i = frequency.length, k = count; i-- != 0;) {
        if (frequency[i] != 0) {
            packedFrequency[--k] = frequency[i];
            symbol2char[k] = (char) i;
            char2symbol.put((char) i, k);
        }
    }

    char2symbol.trim();

    // We now build the coder used to code the strings

    final PrefixCoder prefixCoder;
    final PrefixCodec codec;
    final BitVector[] codeWord;

    if (packedFrequency.length != 0) {
        codec = new HuTuckerCodec(packedFrequency);
        prefixCoder = codec.coder();
        decoder = codec.decoder();
        codeWord = prefixCoder.codeWords();
    } else {
        // This handles the case of a collection without words
        codec = null;
        prefixCoder = null;
        decoder = null;
        codeWord = null;
    }

    packedFrequency = frequency = null;

    // We now compress all strings using the given codec mixed with front coding
    final OutputBitStream output;
    if (selfContained) {
        final File temp = File.createTempFile(this.getClass().getName(), ".dump");
        temp.deleteOnExit();
        tempDumpStreamFilename = temp.toString();
        output = new OutputBitStream(temp, blockSizeInBytes);
    } else
        output = new OutputBitStream(tempDumpStreamFilename = dumpStreamFilename.toString(), blockSizeInBytes);

    // This array will contain the delimiting words (the ones at the start of each block)
    boolean isDelimiter;

    int length, prevTermLength = 0, bits;
    int prefixLength = 0, termCount = 0;
    int currBuffer = 0;

    final IntArrayList blockStarts = new IntArrayList();
    final IntArrayList blockOffsets = new IntArrayList();
    final ObjectArrayList<MutableString> delimiters = new ObjectArrayList<MutableString>();
    prevTerm.length(0);

    for (Iterator<?> i = terms.iterator(); i.hasNext();) {
        s = (CharSequence) i.next();
        length = s.length();

        isDelimiter = false;

        // We compute the common prefix and the number of bits that are necessary to code the next term.
        bits = 0;
        for (prefixLength = 0; prefixLength < length && prefixLength < prevTermLength
                && prevTerm.charAt(prefixLength) == s.charAt(prefixLength); prefixLength++)
            ;
        for (int j = prefixLength; j < length; j++)
            bits += codeWord[char2symbol.get(s.charAt(j))].size();

        //if ( bits + length + 1 > blockSize ) throw new IllegalArgumentException( "The string \"" + s + "\" is too long to be encoded with block size " + blockSizeInBytes );

        // If the next term would overflow the block, and we are not at the start of a block, we align.
        if (output.writtenBits() % blockSize != 0 && output.writtenBits() / blockSize != (output.writtenBits()
                + (length - prefixLength + 1) + (prefixLength + 1) + bits - 1) / blockSize) {
            // We align by writing 0es.
            if (DEBUG)
                System.err.println(
                        "Aligning away " + (blockSize - output.writtenBits() % blockSize) + " bits...");
            for (int j = (int) (blockSize - output.writtenBits() % blockSize); j-- != 0;)
                output.writeBit(0);
            if (ASSERTS)
                assert output.writtenBits() % blockSize == 0;
        }

        if (output.writtenBits() % blockSize == 0) {
            isDelimiter = true;
            prefixLength = 0;
            blockOffsets.add((int) (output.writtenBits() / blockSize));
        }

        // Note that delimiters do not get the prefix length, as it's 0.
        if (!isDelimiter)
            output.writeUnary(prefixLength);
        output.writeUnary(length - prefixLength);

        // Write the next coded suffix on output.
        for (int j = prefixLength; j < length; j++) {
            BitVector c = codeWord[char2symbol.get(s.charAt(j))];
            for (int k = 0; k < c.size(); k++)
                output.writeBit(c.getBoolean(k));
        }

        if (isDelimiter) {
            if (DEBUG)
                System.err.println(
                        "First string of block " + blockStarts.size() + ": " + termCount + " (" + s + ")");
            // The current word starts a new block
            blockStarts.add(termCount);
            // We do not want to rely on s being immutable.
            delimiters.add(new MutableString(s));
        }

        currBuffer = 1 - currBuffer;
        prevTerm.replace(s);
        prevTermLength = length;
        termCount++;
    }

    output.align();
    dumpStreamLength = output.writtenBits() / 8;
    output.close();

    intervalApproximator = prefixCoder == null ? null
            : new ImmutableBinaryTrie<CharSequence>(delimiters,
                    new PrefixCoderTransformationStrategy(prefixCoder, char2symbol, false));

    blockStarts.add(size);
    blockStart = blockStarts.toIntArray();
    blockOffset = blockOffsets.toIntArray();

    // We use a buffer of the same size of a block, hoping in fast I/O. */
    dumpStream = new InputBitStream(tempDumpStreamFilename, blockSizeInBytes);
}

From source file:com.jecelyin.editor.v2.core.text.TextUtils.java

/**
 * Determine what caps mode should be in effect at the current offset in
 * the text.  Only the mode bits set in <var>reqModes</var> will be
 * checked.  Note that the caps mode flags here are explicitly defined
 * to match those in {@link android.text.InputType}.
 *
 * @param cs The text that should be checked for caps modes.
 * @param off Location in the text at which to check.
 * @param reqModes The modes to be checked: may be any combination of
 * {@link #CAP_MODE_CHARACTERS}, {@link #CAP_MODE_WORDS}, and
 * {@link #CAP_MODE_SENTENCES}.// w  w  w .  ja  v  a2s. c  o  m
 *
 * @return Returns the actual capitalization modes that can be in effect
 * at the current position, which is any combination of
 * {@link #CAP_MODE_CHARACTERS}, {@link #CAP_MODE_WORDS}, and
 * {@link #CAP_MODE_SENTENCES}.
 */
public static int getCapsMode(CharSequence cs, int off, int reqModes) {
    if (off < 0) {
        return 0;
    }

    int i;
    char c;
    int mode = 0;

    if ((reqModes & CAP_MODE_CHARACTERS) != 0) {
        mode |= CAP_MODE_CHARACTERS;
    }
    if ((reqModes & (CAP_MODE_WORDS | CAP_MODE_SENTENCES)) == 0) {
        return mode;
    }

    // Back over allowed opening punctuation.

    for (i = off; i > 0; i--) {
        c = cs.charAt(i - 1);

        if (c != '"' && c != '\'' && Character.getType(c) != Character.START_PUNCTUATION) {
            break;
        }
    }

    // Start of paragraph, with optional whitespace.

    int j = i;
    while (j > 0 && ((c = cs.charAt(j - 1)) == ' ' || c == '\t')) {
        j--;
    }
    if (j == 0 || cs.charAt(j - 1) == '\n') {
        return mode | CAP_MODE_WORDS;
    }

    // Or start of word if we are that style.

    if ((reqModes & CAP_MODE_SENTENCES) == 0) {
        if (i != j)
            mode |= CAP_MODE_WORDS;
        return mode;
    }

    // There must be a space if not the start of paragraph.

    if (i == j) {
        return mode;
    }

    // Back over allowed closing punctuation.

    for (; j > 0; j--) {
        c = cs.charAt(j - 1);

        if (c != '"' && c != '\'' && Character.getType(c) != Character.END_PUNCTUATION) {
            break;
        }
    }

    if (j > 0) {
        c = cs.charAt(j - 1);

        if (c == '.' || c == '?' || c == '!') {
            // Do not capitalize if the word ends with a period but
            // also contains a period, in which case it is an abbreviation.

            if (c == '.') {
                for (int k = j - 2; k >= 0; k--) {
                    c = cs.charAt(k);

                    if (c == '.') {
                        return mode;
                    }

                    if (!Character.isLetter(c)) {
                        break;
                    }
                }
            }

            return mode | CAP_MODE_SENTENCES;
        }
    }

    return mode;
}

From source file:org.akvo.rsr.up.UpdateEditorActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mUser = SettingsUtil.getAuthUser(this);
    nextLocalId = SettingsUtil.ReadInt(this, ConstantUtil.LOCAL_ID_KEY, -1);

    // find which update we are editing
    // null means create a new one
    Bundle extras = getIntent().getExtras();
    projectId = extras != null ? extras.getString(ConstantUtil.PROJECT_ID_KEY) : null;
    if (projectId == null) {
        DialogUtil.errorAlert(this, R.string.noproj_dialog_title, R.string.noproj_dialog_msg);
    }/*w ww . jav  a  2  s . c  om*/
    updateId = extras != null ? extras.getString(ConstantUtil.UPDATE_ID_KEY) : null;
    if (updateId == null) {
        updateId = savedInstanceState != null ? savedInstanceState.getString(ConstantUtil.UPDATE_ID_KEY) : null;
    }

    //Limit what we can write 
    InputFilter postFilter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            boolean keepOriginal = true;
            StringBuilder sb = new StringBuilder(end - start);
            for (int i = start; i < end; i++) {
                char c = source.charAt(i);
                if (isCharAllowed(c)) // put your condition here
                    sb.append(c);
                else
                    keepOriginal = false;
            }
            if (keepOriginal)
                return null;
            else {
                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(sb);
                    TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                    return sp;
                } else {
                    return sb;
                }
            }
        }

        private boolean isCharAllowed(char c) {
            //                    return !Character.isSurrogate(c); //From API 19
            return !(c >= 0xD800 && c <= 0xDFFF);
        }
    };

    // get the look
    setContentView(R.layout.activity_update_editor);
    // find the fields
    progressGroup = findViewById(R.id.sendprogress_group);
    uploadProgress = (ProgressBar) findViewById(R.id.sendProgressBar);
    projTitleLabel = (TextView) findViewById(R.id.projupd_edit_proj_title);
    projupdTitleCount = (TextView) findViewById(R.id.projupd_edit_titlecount);
    projupdTitleCount.setText(Integer.toString(TITLE_LENGTH));
    projupdTitleText = (EditText) findViewById(R.id.projupd_edit_title);
    projupdTitleText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(TITLE_LENGTH), postFilter });
    projupdTitleText.addTextChangedListener(new TextWatcher() {
        //Show count of remaining characters
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            projupdTitleCount.setText(String.valueOf(TITLE_LENGTH - s.length()));
        }

        public void afterTextChanged(Editable s) {
        }
    });
    projupdDescriptionText = (EditText) findViewById(R.id.projupd_edit_description);
    projupdDescriptionText.setFilters(new InputFilter[] { postFilter });
    projupdImage = (ImageView) findViewById(R.id.image_update_detail);
    photoAndToolsGroup = findViewById(R.id.image_with_tools);
    photoAddGroup = findViewById(R.id.photo_buttons);
    photoCaptionText = (EditText) findViewById(R.id.projupd_edit_photo_caption);
    photoCaptionText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(75), postFilter });
    photoCreditText = (EditText) findViewById(R.id.projupd_edit_photo_credit);
    photoCreditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(25), postFilter });

    positionGroup = findViewById(R.id.position_group);
    latField = (TextView) findViewById(R.id.latitude);
    lonField = (TextView) findViewById(R.id.longitude);
    eleField = (TextView) findViewById(R.id.elevation);
    accuracyField = (TextView) findViewById(R.id.gps_accuracy);
    searchingIndicator = (TextView) findViewById(R.id.gps_searching);
    gpsProgress = (ProgressBar) findViewById(R.id.progress_gps);

    // Activate buttons
    btnSubmit = (Button) findViewById(R.id.btn_send_update);
    btnSubmit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            sendUpdate();
        }
    });

    btnDraft = (Button) findViewById(R.id.btn_save_draft);
    btnDraft.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            saveAsDraft(true);
        }
    });

    btnTakePhoto = (Button) findViewById(R.id.btn_take_photo);
    btnTakePhoto.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // generate unique filename
            captureFilename = FileUtil.getExternalPhotoDir(UpdateEditorActivity.this) + File.separator
                    + "capture" + System.nanoTime() + ".jpg";
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(captureFilename)));
            startActivityForResult(takePictureIntent, photoRequest);
        }
    });

    btnAttachPhoto = (Button) findViewById(R.id.btn_attach_photo);
    btnAttachPhoto.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, photoPick);
        }
    });

    btnDelPhoto = (Button) findViewById(R.id.btn_delete_photo);
    btnDelPhoto.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            // Forget image
            update.setThumbnailFilename(null);
            // TODO: delete image file if it was taken through this app?
            // Hide photo w tools
            showPhoto(false);
        }
    });

    btnRotRightPhoto = (Button) findViewById(R.id.btn_rotate_photo_r);
    btnRotRightPhoto.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            // Rotate image right
            rotatePhoto(true);
        }
    });

    btnGpsGeo = (Button) findViewById(R.id.btn_gps_position);
    btnGpsGeo.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onGetGPSClick(view);
        }
    });

    btnPhotoGeo = (Button) findViewById(R.id.btn_photo_position);
    btnPhotoGeo.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onGetPhotoLocationClick(view);
        }
    });

    dba = new RsrDbAdapter(this);
    dba.open();

    Project project = dba.findProject(projectId);
    projTitleLabel.setText(project.getTitle());

    if (updateId == null) { // create new
        update = new Update();
        update.setUuid(UUID.randomUUID().toString()); // should do sth
                                                      // better, especially
                                                      // if MAC address is
                                                      // avaliable
                                                      /*
                                                       * WifiManager wifiManager = (WifiManager)
                                                       * getSystemService(Context.WIFI_SERVICE); WifiInfo wInfo =
                                                       * wifiManager.getConnectionInfo(); String macAddress =
                                                       * wInfo.getMacAddress(); if (macAddress == null) txt_View.append(
                                                       * "MAC Address : " + macAddress + "\n" ); else txt_View.append(
                                                       * "MAC Address : " + macAddress + "\n" ); }
                                                       */
        update.setUserId(mUser.getId());
        update.setDate(new Date());
        editable = true;
    } else {
        update = dba.findUpdate(updateId);
        if (update == null) {
            DialogUtil.errorAlert(this, R.string.noupd_dialog_title, R.string.noupd2_dialog_msg);
        } else {
            // populate fields
            editable = update.getDraft(); // This should always be true with
                                          // the current UI flow - we go to
                                          // UpdateDetailActivity if it is sent
            if (update.getTitle().equals(TITLE_PLACEHOLDER)) {
                projupdTitleText.setText(""); //placeholder is just to satisfy db
            } else {
                projupdTitleText.setText(update.getTitle());
            }
            projupdDescriptionText.setText(update.getText());
            photoCaptionText.setText(update.getPhotoCaption());
            photoCreditText.setText(update.getPhotoCredit());
            latField.setText(update.getLatitude());
            lonField.setText(update.getLongitude());
            eleField.setText(update.getElevation());
            if (update.validLatLon()) {
                positionGroup.setVisibility(View.VISIBLE);
            }
            // show preexisting image
            if (update.getThumbnailFilename() != null) {
                // btnTakePhoto.setText(R.string.btncaption_rephoto);
                ThumbnailUtil.setPhotoFile(projupdImage, update.getThumbnailUrl(),
                        update.getThumbnailFilename(), null, null, false);
                photoLocation = FileUtil.exifLocation(update.getThumbnailFilename());
                showPhoto(true);
            }
        }
    }

    // register a listener for a completion and progress intents
    broadRec = new ResponseReceiver();
    IntentFilter f = new IntentFilter(ConstantUtil.UPDATES_SENT_ACTION);
    f.addAction(ConstantUtil.UPDATES_SENDPROGRESS_ACTION);
    LocalBroadcastManager.getInstance(this).registerReceiver(broadRec, f);

    enableChanges(editable);
    btnDraft.setVisibility(editable ? View.VISIBLE : View.GONE);
    btnSubmit.setVisibility(editable ? View.VISIBLE : View.GONE);
    // btnTakePhoto.setVisibility(editable?View.VISIBLE:View.GONE);

    // Show the Up button in the action bar.
    // setupActionBar();
}