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:org.apache.fop.layoutmgr.inline.TextLayoutManager.java

/**
 * Given a mapped character sequence MCS, obtain glyph position adjustments
 * from the font's kerning data./*  w w w .jav a2 s  .  com*/
 * @param mcs mapped character sequence
 * @param font applicable font
 * @return glyph position adjustments (or null if no kerning)
 */
private int[][] getKerningAdjustments(CharSequence mcs, final Font font) {
    int nc = mcs.length();
    // extract kerning array
    int[] ka = new int[nc]; // kerning array
    for (int i = 0, n = nc, cPrev = -1; i < n; i++) {
        int c = mcs.charAt(i);
        // TODO !BMP
        if (cPrev >= 0) {
            ka[i] = font.getKernValue(cPrev, c);
        }
        cPrev = c;
    }
    // was there a non-zero kerning?
    boolean hasKerning = false;
    for (int i = 0, n = nc; i < n; i++) {
        if (ka[i] != 0) {
            hasKerning = true;
            break;
        }
    }
    // if non-zero kerning, then create and return glyph position adjustment array
    if (hasKerning) {
        int[][] gpa = new int[nc][4];
        for (int i = 0, n = nc; i < n; i++) {
            if (i > 0) {
                gpa[i - 1][GlyphPositioningTable.Value.IDX_X_ADVANCE] = ka[i];
            }
        }
        return gpa;
    } else {
        return null;
    }
}

From source file:com.xperia64.timidityae.TimidityActivity.java

public void dynExport() {
    localfinished = false;/*from w ww.j av a  2  s.c om*/
    if (Globals.isMidi(currSongName) && Globals.isPlaying == 0) {

        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle(getResources().getString(R.string.dynex_alert1));
        alert.setMessage(getResources().getString(R.string.dynex_alert1_msg));
        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                    int dend) {
                for (int i = start; i < end; i++) {
                    String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*";
                    if (IC.contains("*" + source.charAt(i) + "*")) {
                        return "";
                    }
                }
                return null;
            }
        };
        final EditText input = new EditText(this);
        input.setFilters(new InputFilter[] { filter });
        alert.setView(input);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String value = input.getText().toString();
                if (!value.toLowerCase(Locale.US).endsWith(".wav"))
                    value += ".wav";
                String parent = currSongName.substring(0, currSongName.lastIndexOf('/') + 1);
                boolean alreadyExists = new File(parent + value).exists();
                boolean aWrite = true;
                String needRename = null;
                String probablyTheRoot = "";
                String probablyTheDirectory = "";
                try {
                    new FileOutputStream(parent + value, true).close();
                } catch (FileNotFoundException e) {
                    aWrite = false;
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (aWrite && !alreadyExists)
                    new File(parent + value).delete();

                if (aWrite && new File(parent).canWrite()) {
                    value = parent + value;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) {
                    String[] tmp = Globals.getDocFilePaths(TimidityActivity.this, parent);
                    probablyTheDirectory = tmp[0];
                    probablyTheRoot = tmp[1];
                    if (probablyTheDirectory.length() > 1) {
                        needRename = parent
                                .substring(parent.indexOf(probablyTheRoot) + probablyTheRoot.length()) + value;
                        value = probablyTheDirectory + '/' + value;
                    } else {
                        value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value;
                    }
                } else {
                    value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value;
                }
                final String finalval = value;
                final boolean canWrite = aWrite;
                final String needToRename = needRename;
                final String probRoot = probablyTheRoot;
                if (new File(finalval).exists()
                        || (new File(probRoot + needRename).exists() && needToRename != null)) {
                    AlertDialog dialog2 = new AlertDialog.Builder(TimidityActivity.this).create();
                    dialog2.setTitle(getResources().getString(R.string.warning));
                    dialog2.setMessage(getResources().getString(R.string.dynex_alert2_msg));
                    dialog2.setCancelable(false);
                    dialog2.setButton(DialogInterface.BUTTON_POSITIVE,
                            getResources().getString(android.R.string.yes),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int buttonId) {
                                    if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        if (needToRename != null) {
                                            Globals.tryToDeleteFile(TimidityActivity.this,
                                                    probRoot + needToRename);
                                            Globals.tryToDeleteFile(TimidityActivity.this, finalval);
                                        } else {
                                            Globals.tryToDeleteFile(TimidityActivity.this, finalval);
                                        }
                                    } else {
                                        new File(finalval).delete();
                                    }
                                    saveWavPart2(finalval, needToRename);
                                }
                            });
                    dialog2.setButton(DialogInterface.BUTTON_NEGATIVE,
                            getResources().getString(android.R.string.no),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int buttonId) {

                                }
                            });
                    dialog2.show();
                } else {
                    saveWavPart2(finalval, needToRename);
                }

            }
        });

        alert.setNegativeButton(getResources().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                    }
                });

        alerty = alert.show();

    }
}

From source file:com.xperia64.timidityae.TimidityActivity.java

public void saveCfg() {
    localfinished = false;//from  www  .  j av a  2 s.  co m
    if (Globals.isMidi(currSongName) && Globals.isPlaying == 0) {

        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("Save Cfg");
        alert.setMessage("Save a MIDI configuration file");
        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                    int dend) {
                for (int i = start; i < end; i++) {
                    String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*";
                    if (IC.contains("*" + source.charAt(i) + "*")) {
                        return "";
                    }
                }
                return null;
            }
        };
        // Set an EditText view to get user input 
        final EditText input = new EditText(this);
        input.setFilters(new InputFilter[] { filter });
        alert.setView(input);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String value = input.getText().toString();
                if (!value.toLowerCase(Locale.US).endsWith(Globals.compressCfg ? ".tzf" : ".tcf"))
                    value += (Globals.compressCfg ? ".tzf" : ".tcf");
                String parent = currSongName.substring(0, currSongName.lastIndexOf('/') + 1);
                boolean aWrite = true;
                boolean alreadyExists = new File(parent + value).exists();
                String needRename = null;
                String probablyTheRoot = "";
                String probablyTheDirectory = "";
                try {
                    new FileOutputStream(parent + value, true).close();
                } catch (FileNotFoundException e) {
                    aWrite = false;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (!alreadyExists && aWrite)
                    new File(parent + value).delete();
                if (aWrite && new File(parent).canWrite()) {
                    value = parent + value;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) {
                    //TODO
                    // Write the file to getExternalFilesDir, then move it with the Uri
                    // We need to tell JNIHandler that movement is needed.

                    String[] tmp = Globals.getDocFilePaths(TimidityActivity.this, parent);
                    probablyTheDirectory = tmp[0];
                    probablyTheRoot = tmp[1];
                    if (probablyTheDirectory.length() > 1) {
                        needRename = parent
                                .substring(parent.indexOf(probablyTheRoot) + probablyTheRoot.length()) + value;
                        value = probablyTheDirectory + '/' + value;
                    } else {
                        value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value;
                        return;
                    }
                } else {
                    value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value;
                }
                final String finalval = value;
                final boolean canWrite = aWrite;
                final String needToRename = needRename;
                final String probRoot = probablyTheRoot;
                if (new File(finalval).exists()
                        || (new File(probRoot + needRename).exists() && needToRename != null)) {
                    AlertDialog dialog2 = new AlertDialog.Builder(TimidityActivity.this).create();
                    dialog2.setTitle("Warning");
                    dialog2.setMessage("Overwrite config file?");
                    dialog2.setCancelable(false);
                    dialog2.setButton(DialogInterface.BUTTON_POSITIVE,
                            getResources().getString(android.R.string.yes),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int buttonId) {
                                    if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        if (needToRename != null) {
                                            Globals.tryToDeleteFile(TimidityActivity.this,
                                                    probRoot + needToRename);
                                            Globals.tryToDeleteFile(TimidityActivity.this, finalval);
                                        } else {
                                            Globals.tryToDeleteFile(TimidityActivity.this, finalval);
                                        }
                                    } else {
                                        new File(finalval).delete();
                                    }
                                    saveCfgPart2(finalval, needToRename);
                                }
                            });
                    dialog2.setButton(DialogInterface.BUTTON_NEGATIVE,
                            getResources().getString(android.R.string.no),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int buttonId) {

                                }
                            });
                    dialog2.show();
                } else {
                    saveCfgPart2(finalval, needToRename);
                }
            }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                // Canceled.
            }
        });

        alerty = alert.show();
    }
}

From source file:net.sf.xfd.provider.ProviderBase.java

@NonNull
public String getTypeFastest(int dirFd, CharSequence name, Stat stat) {
    if (stat.type != null) {
        switch (stat.type) {
        case DIRECTORY:
            return MIME_TYPE_DIR;
        case CHAR_DEV:
            return CHAR_DEV_MIME;
        }//from   www  .j  a  va  2 s  . c o m
    }

    final OS os = getOS();
    if (os == null) {
        return DEFAULT_MIME;
    }

    // Do we have an option to open the file? Does it even make sense?
    // It is a bad idea to open sockets, special files and, especially, pipes
    // (this can cause block, take some time or have other unwelcome side-effects).
    // Trying to content-sniff ordinary zero-sized files also does not make sense
    // Unless they are on some special filesystem (such as procfs), that incorrectly
    // reports zero sizes to stat().

    boolean canSniffContent = stat.type == FsType.FILE;

    int fd = Fd.NIL;

    try {
        final boolean isLink = stat.type == FsType.LINK;

        if (isLink) {
            // we must exclude the possibility that this is a symlink to directory

            if (!os.faccessat(dirFd, name, OS.F_OK)) {
                // the link is broken or target is inaccessible, bail
                return LINK_MIME;
            }

            try {
                os.fstatat(dirFd, name, stat, 0);

                switch (stat.type) {
                case DIRECTORY:
                    return MIME_TYPE_DIR;
                case CHAR_DEV:
                    return CHAR_DEV_MIME;
                }
            } catch (IOException ioe) {
                LogUtil.logCautiously("Unable to stat target of " + name, ioe);
            }
        } else {
            try {
                if (canSniffContent) {
                    fd = os.openat(dirFd, name, OS.O_RDONLY, 0);

                    os.fstat(fd, stat);
                } else {
                    os.fstatat(dirFd, name, stat, 0);
                }
            } catch (IOException ioe) {
                LogUtil.logCautiously("Unable to directly stat " + name, ioe);
            }
        }

        final String extension = getExtensionFast(name);

        final MimeTypeMap mimeMap = MimeTypeMap.getSingleton();

        final String foundMime = mimeMap.getMimeTypeFromExtension(extension);
        if (foundMime != null) {
            return foundMime;
        }

        canSniffContent = canSniffContent && (stat.st_size != 0 || isPossiblySpecial(stat));

        if (isLink) {
            // check if link target has a usable extension
            CharSequence resolved = null;

            // Some filesystem (procfs, you!!) do export files as symlinks, but don't allow them
            // to be open via these symlinks. Gotta be careful here.
            if (canSniffContent) {
                try {
                    fd = os.openat(dirFd, name, OS.O_RDONLY, 0);

                    resolved = os.readlinkat(DirFd.NIL, fdPath(fd));
                } catch (IOException ioe) {
                    LogUtil.logCautiously("Unable to open target of " + name, ioe);
                }
            }

            if (resolved == null) {
                try {
                    resolved = os.readlinkat(dirFd, name);

                    if (resolved.charAt(0) == '/') {
                        resolved = canonString(resolved);
                    }
                } catch (IOException linkErr) {
                    return LINK_MIME;
                }
            }

            final String linkTargetExtension = getExtensionFromPath(resolved);

            if (linkTargetExtension != null && !linkTargetExtension.equals(extension)) {
                final String sortaFastMime = mimeMap.getMimeTypeFromExtension(linkTargetExtension);
                if (sortaFastMime != null) {
                    return sortaFastMime;
                }
            }

            // let's try to open by resolved name too, see above
            name = resolved;
        }

        if (canSniffContent) {
            if (fd < 0) {
                fd = os.openat(dirFd, name, OS.O_RDONLY, 0);
            }

            final String contentInfo = magic.guessMime(fd);

            if (contentInfo != null) {
                return contentInfo;
            }
        }
    } catch (IOException ioe) {
        LogUtil.logCautiously("Failed to guess type of " + name, ioe);
    } finally {
        if (fd > 0) {
            os.dispose(fd);
        }
    }

    if (stat.type == null) {
        return DEFAULT_MIME;
    }

    switch (stat.type) {
    case LINK:
        return LINK_MIME;
    case DOMAIN_SOCKET:
        return SOCK_MIME;
    case NAMED_PIPE:
        return FIFO_MIME;
    case FILE:
        if (stat.st_size == 0) {
            return EMPTY_MIME;
        }
    default:
        return DEFAULT_MIME;
    }
}

From source file:com.hichinaschool.flashcards.anki.CardEditor.java

@Override
protected Dialog onCreateDialog(int id) {
    StyledDialog dialog = null;/*from  w ww .j  av  a 2 s  .  com*/
    Resources res = getResources();
    StyledDialog.Builder builder = new StyledDialog.Builder(this);

    switch (id) {
    case DIALOG_TAGS_SELECT:
        builder.setTitle(R.string.card_details_tags);
        builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mAddNote) {
                    try {
                        JSONArray ja = new JSONArray();
                        for (String t : selectedTags) {
                            ja.put(t);
                        }
                        mCol.getModels().current().put("tags", ja);
                        mCol.getModels().setChanged();
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                    mEditorNote.setTags(selectedTags);
                }
                mCurrentTags = selectedTags;
                updateTags();
            }
        });
        builder.setNegativeButton(res.getString(R.string.cancel), null);

        mNewTagEditText = (EditText) new EditText(this);
        mNewTagEditText.setHint(R.string.add_new_tag);

        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                    int dend) {
                for (int i = start; i < end; i++) {
                    if (source.charAt(i) == ' ' || source.charAt(i) == ',') {
                        return "";
                    }
                }
                return null;
            }
        };
        mNewTagEditText.setFilters(new InputFilter[] { filter });

        ImageView mAddTextButton = new ImageView(this);
        mAddTextButton.setImageResource(R.drawable.ic_addtag);
        mAddTextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tag = mNewTagEditText.getText().toString();
                if (tag.length() != 0) {
                    if (mEditorNote.hasTag(tag)) {
                        mNewTagEditText.setText("");
                        return;
                    }
                    selectedTags.add(tag);
                    actualizeTagDialog(mTagsDialog);
                    mNewTagEditText.setText("");
                }
            }
        });

        FrameLayout frame = new FrameLayout(this);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        params.rightMargin = 10;
        mAddTextButton.setLayoutParams(params);
        frame.addView(mNewTagEditText);
        frame.addView(mAddTextButton);

        builder.setView(frame, false, true);
        dialog = builder.create();
        mTagsDialog = dialog;
        break;

    case DIALOG_DECK_SELECT:
        ArrayList<CharSequence> dialogDeckItems = new ArrayList<CharSequence>();
        // Use this array to know which ID is associated with each
        // Item(name)
        final ArrayList<Long> dialogDeckIds = new ArrayList<Long>();

        ArrayList<JSONObject> decks = mCol.getDecks().all();
        Collections.sort(decks, new JSONNameComparator());
        builder.setTitle(R.string.deck);
        for (JSONObject d : decks) {
            try {
                if (d.getInt("dyn") == 0) {
                    dialogDeckItems.add(d.getString("name"));
                    dialogDeckIds.add(d.getLong("id"));
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
        // Convert to Array
        String[] items = new String[dialogDeckItems.size()];
        dialogDeckItems.toArray(items);

        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                long newId = dialogDeckIds.get(item);
                if (mCurrentDid != newId) {
                    if (mAddNote) {
                        try {
                            // TODO: mEditorNote.setDid(newId);
                            mEditorNote.model().put("did", newId);
                            mCol.getModels().setChanged();
                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    mCurrentDid = newId;
                    updateDeck();
                }
            }
        });

        dialog = builder.create();
        mDeckSelectDialog = dialog;
        break;

    case DIALOG_MODEL_SELECT:
        ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>();
        // Use this array to know which ID is associated with each
        // Item(name)
        final ArrayList<Long> dialogIds = new ArrayList<Long>();

        ArrayList<JSONObject> models = mCol.getModels().all();
        Collections.sort(models, new JSONNameComparator());
        builder.setTitle(R.string.note_type);
        for (JSONObject m : models) {
            try {
                dialogItems.add(m.getString("name"));
                dialogIds.add(m.getLong("id"));
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
        // Convert to Array
        String[] items2 = new String[dialogItems.size()];
        dialogItems.toArray(items2);

        builder.setItems(items2, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                long oldModelId;
                try {
                    oldModelId = mCol.getModels().current().getLong("id");
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                long newId = dialogIds.get(item);
                if (oldModelId != newId) {
                    mCol.getModels().setCurrent(mCol.getModels().get(newId));
                    JSONObject cdeck = mCol.getDecks().current();
                    try {
                        cdeck.put("mid", newId);
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                    mCol.getDecks().save(cdeck);
                    int size = mEditFields.size();
                    String[] oldValues = new String[size];
                    for (int i = 0; i < size; i++) {
                        oldValues[i] = mEditFields.get(i).getText().toString();
                    }
                    setNote();
                    resetEditFields(oldValues);
                    mTimerHandler.removeCallbacks(checkDuplicatesRunnable);
                    duplicateCheck(false);
                }
            }
        });
        dialog = builder.create();
        break;

    case DIALOG_RESET_CARD:
        builder.setTitle(res.getString(R.string.reset_card_dialog_title));
        builder.setMessage(res.getString(R.string.reset_card_dialog_message));
        builder.setPositiveButton(res.getString(R.string.yes), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // for (long cardId :
                // mDeck.getCardsFromFactId(mEditorNote.getId())) {
                // mDeck.cardFromId(cardId).resetCard();
                // }
                // mDeck.reset();
                // setResult(Reviewer.RESULT_EDIT_CARD_RESET);
                // mCardReset = true;
                // Themes.showThemedToast(CardEditor.this,
                // getResources().getString(
                // R.string.reset_card_dialog_confirmation), true);
            }
        });
        builder.setNegativeButton(res.getString(R.string.no), null);
        builder.setCancelable(true);
        dialog = builder.create();
        break;

    case DIALOG_INTENT_INFORMATION:
        dialog = createDialogIntentInformation(builder, res);
    }

    return dialog;
}

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

public static int indexOfNewLineChar(CharSequence s, int start, int end) {
    Class<? extends CharSequence> c = s.getClass();

    if (s instanceof GetChars || c == StringBuffer.class || c == StringBuilder.class || c == String.class) {
        final int INDEX_INCREMENT = 500;
        char[] temp = obtain(INDEX_INCREMENT);

        while (start < end) {
            int segend = start + INDEX_INCREMENT;
            if (segend > end)
                segend = end;/*from   ww  w . ja v  a2s  . c  om*/

            getChars(s, start, segend, temp, 0);

            int count = segend - start;
            for (int i = 0; i < count; i++) {
                if (temp[i] == '\r' || temp[i] == '\n') {
                    recycle(temp);
                    if (temp[i] == '\r' && i + 1 < count && temp[i + 1] == '\n') {
                        i++;
                    }
                    return i + start;
                }
            }

            start = segend;
        }

        recycle(temp);
        return -1;
    }

    for (int i = start; i < end; i++)
        if (s.charAt(i) == '\r' || s.charAt(i) == '\n') {
            if (s.charAt(i) == '\r' && i + 1 < end && s.charAt(i + 1) == '\n') {
                i++;
            }
            return i;
        }

    return -1;
}

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

public static int lastIndexOf(CharSequence s, char ch, int start, int last) {
    if (last < 0)
        return -1;
    if (last >= s.length())
        last = s.length() - 1;//from w w  w .  ja v a 2 s  .c  om

    int end = last + 1;

    Class<? extends CharSequence> c = s.getClass();

    if (s instanceof GetChars || c == StringBuffer.class || c == StringBuilder.class || c == String.class) {
        final int INDEX_INCREMENT = 500;
        char[] temp = obtain(INDEX_INCREMENT);

        while (start < end) {
            int segstart = end - INDEX_INCREMENT;
            if (segstart < start)
                segstart = start;

            getChars(s, segstart, end, temp, 0);

            int count = end - segstart;
            for (int i = count - 1; i >= 0; i--) {
                if (temp[i] == ch) {
                    recycle(temp);
                    return i + segstart;
                }
            }

            end = segstart;
        }

        recycle(temp);
        return -1;
    }

    for (int i = end - 1; i >= start; i--)
        if (s.charAt(i) == ch)
            return i;

    return -1;
}

From source file:com.servoy.j2db.util.Utils.java

/**
 * Converts a String to multiline HTML markup by replacing newlines with line break entities (&lt;br/&gt;) and multiple occurrences of newline with
 * paragraph break entities (&lt;p&gt;).
 *
 * @param s String to transform/*from  w w w. j av  a2  s  .c o  m*/
 * @return String with all single occurrences of newline replaced with &lt;br/&gt; and all multiple occurrences of newline replaced with &lt;p&gt;.
 */
public static CharSequence toMultilineMarkup(final CharSequence s) {
    if (s == null) {
        return null;
    }

    final StringBuilder buffer = new StringBuilder();
    int newlineCount = 0;

    buffer.append("<p>"); //$NON-NLS-1$
    for (int i = 0; i < s.length(); i++) {
        final char c = s.charAt(i);

        switch (c) {
        case '\n':
            newlineCount++;
            break;

        case '\r':
            break;

        default:
            if (newlineCount == 1) {
                buffer.append("<br/>"); //$NON-NLS-1$
            } else if (newlineCount > 1) {
                buffer.append("</p><p>"); //$NON-NLS-1$
            }

            buffer.append(c);
            newlineCount = 0;
            break;
        }
    }
    if (newlineCount == 1) {
        buffer.append("<br/>"); //$NON-NLS-1$
    } else if (newlineCount > 1) {
        buffer.append("</p><p>"); //$NON-NLS-1$
    }
    buffer.append("</p>"); //$NON-NLS-1$
    return buffer;
}

From source file:com.df.dfcarchecker.CarCheck.CarCheckBasicInfoFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //        Random r=new Random();
    //        int uniqueNumber =(r.nextInt(999) + 100);
    //        uniqueId = Integer.toString(uniqueNumber);

    // ?uniqueId// w w w  . j a  v  a 2s.  c o  m
    UUID uuid = UUID.randomUUID();
    uniqueId = uuid.toString();

    this.inflater = inflater;
    rootView = inflater.inflate(R.layout.fragment_car_check_basic_info, container, false);

    // <editor-fold defaultstate="collapsed" desc="??View?">
    tableLayout = (TableLayout) rootView.findViewById(R.id.bi_content_table);

    contentLayout = (LinearLayout) rootView.findViewById(R.id.brand_input);

    Button vinButton = (Button) rootView.findViewById(R.id.bi_vin_button);
    vinButton.setOnClickListener(this);

    brandOkButton = (Button) rootView.findViewById(R.id.bi_brand_ok_button);
    brandOkButton.setEnabled(false);
    brandOkButton.setOnClickListener(this);

    brandSelectButton = (Button) rootView.findViewById(R.id.bi_brand_select_button);
    brandSelectButton.setEnabled(false);
    brandSelectButton.setOnClickListener(this);

    // ??
    sketchPhotoEntities = new ArrayList<PhotoEntity>();

    // 
    Button matchButton = (Button) rootView.findViewById(R.id.ct_licencePhotoMatch_button);
    matchButton.setOnClickListener(this);

    // vin???
    InputFilter alphaNumericFilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence arg0, int arg1, int arg2, Spanned arg3, int arg4, int arg5) {
            for (int k = arg1; k < arg2; k++) {
                if (!Character.isLetterOrDigit(arg0.charAt(k))) {
                    return "";
                }
            }
            return null;
        }
    };
    vin_edit = (EditText) rootView.findViewById(R.id.bi_vin_edit);
    vin_edit.setFilters(new InputFilter[] { alphaNumericFilter, new InputFilter.AllCaps() });

    brandEdit = (EditText) rootView.findViewById(R.id.bi_brand_edit);
    displacementEdit = (EditText) rootView.findViewById(R.id.csi_displacement_edit);
    transmissionEdit = (EditText) rootView.findViewById(R.id.csi_transmission_edit);
    runEdit = (EditText) rootView.findViewById(R.id.bi_mileage_edit);
    //
    //        transmissionSpinner = (Spinner)rootView.findViewById(R.id.csi_transmission_spinner);
    //        transmissionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    //            @Override
    //            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
    //                transmissionEdit.setText(adapterView.getSelectedItem().toString());
    //            }
    //
    //            @Override
    //            public void onNothingSelected(AdapterView<?> adapterView) {
    //
    //            }
    //        });

    // ??????
    ScrollView view = (ScrollView) rootView.findViewById(R.id.root);
    view.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
    view.setFocusable(true);
    view.setFocusableInTouchMode(true);
    view.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            v.requestFocusFromTouch();
            return false;
        }
    });

    // ????????2?
    runEdit.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable edt) {
            String temp = edt.toString();

            if (temp.contains(".")) {
                int posDot = temp.indexOf(".");
                if (posDot <= 0)
                    return;
                if (temp.length() - posDot - 1 > 2) {
                    edt.delete(posDot + 3, posDot + 4);
                }
            } else {
                if (temp.length() > 2) {
                    edt.clear();
                    edt.append(temp.substring(0, 2));
                }
            }
        }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }
    });

    licencePhotoMatchEdit = (EditText) rootView.findViewById(R.id.ct_licencePhotoMatch_edit);
    licencePhotoMatchEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            licencePhotoMatchEdit.setError(null);
        }

        @Override
        public void afterTextChanged(Editable editable) {
            licencePhotoMatchEdit.setError(null);
        }
    });

    // ??
    carNumberEdit = (EditText) rootView.findViewById(R.id.ci_plateNumber_edit);
    carNumberEdit.setFilters(new InputFilter[] { new InputFilter.AllCaps(), new InputFilter.LengthFilter(10) });

    // ?
    portedProcedureRow = (TableRow) rootView.findViewById(R.id.ct_ported_procedure);

    // ?Spinner
    setRegLocationSpinner();
    setCarColorSpinner();
    setFirstLogTimeSpinner();
    setManufactureTimeSpinner();
    setTransferCountSpinner();
    setLastTransferTimeSpinner();
    setYearlyCheckAvailableDateSpinner();
    setAvailableDateYearSpinner();
    setBusinessInsuranceAvailableDateYearSpinner();
    setOtherSpinners();
    // </editor-fold>

    mCarSettings = new CarSettings();

    // ??xml
    if (vehicleModel == null) {
        mProgressDialog = ProgressDialog.show(rootView.getContext(), null, "?..", false, false);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ParseXml();

                    // jsonData??
                    if (!jsonData.equals("")) {
                        modifyMode = true;
                        letsEnterModifyMode();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();
    }

    return rootView;
}

From source file:com.tsp.clipsy.audio.RingdroidEditActivity.java

private String makeRingtoneFilename(CharSequence title, String extension) {
    String parentdir = "/sdcard/media/audio/clipsy";

    // Create the parent directory
    File parentDirFile = new File(parentdir);
    parentDirFile.mkdirs();/*from w w w  .j  ava 2s. com*/

    // If we can't write to that special path, try just writing
    // directly to the sdcard
    if (!parentDirFile.isDirectory()) {
        parentdir = "/sdcard";
    }

    // Turn the title into a filename
    String filename = "";
    for (int i = 0; i < title.length(); i++) {
        if (Character.isLetterOrDigit(title.charAt(i))) {
            filename += title.charAt(i);
        }
    }

    // Try to make the filename unique
    String path = null;
    for (int i = 0; i < 100; i++) {
        String testPath;
        if (i > 0)
            testPath = parentdir + "/" + filename + i + extension;
        else
            testPath = parentdir + "/" + filename + extension;

        try {
            RandomAccessFile f = new RandomAccessFile(new File(testPath), "r");
        } catch (Exception e) {
            // Good, the file didn't exist
            path = testPath;
            break;
        }
    }

    return path;
}