Example usage for android.text Html fromHtml

List of usage examples for android.text Html fromHtml

Introduction

In this page you can find the example usage for android.text Html fromHtml.

Prototype

@Deprecated
public static Spanned fromHtml(String source) 

Source Link

Document

Returns displayable styled text from the provided HTML string with the legacy flags #FROM_HTML_MODE_LEGACY .

Usage

From source file:co.dilaver.quoter.fragments.QODFragment.java

private void parseQodResponse(JSONObject response) throws JSONException {
    JSONObject parse = response.getJSONObject("parse");
    JSONObject text = parse.getJSONObject("text");
    String content = text.getString("*");

    Document doc = Jsoup.parse(content);
    Elements table = doc.select("table[style=\"text-align:center; width:100%\"]");
    Elements rows = table.select("tr");
    Elements qod = rows.get(0).select("td");
    Elements author = rows.get(1).select("td");
    Whitelist whitelist = Whitelist.none();

    String newQuote = Html.fromHtml(Jsoup.clean(qod.toString(), whitelist)).toString();
    String newAuthor = Html.fromHtml(Jsoup.clean(author.toString(), whitelist).replace("~", "")).toString();

    if (!qodString.equals("") && !authorString.equals("")) {
        if (!qodString.equals(newQuote) || !authorString.equals(newAuthor)) {
            Snackbar.make(rootLayout, getString(R.string.str_Refreshing), Snackbar.LENGTH_SHORT).show();
        }//from  w w  w .  ja va  2  s. c  om
    }

    qodString = newQuote;
    authorString = newAuthor;

    sharedPrefStorage.setQodText(qodString);
    sharedPrefStorage.setQodAuthor(authorString);

    Log.e(TAG, "quote: " + qodString);
    Log.e(TAG, "author: " + authorString);

    qodText.setText(getString(R.string.str_WithinQuotation, qodString));
    qodAuthor.setText(authorString);
}

From source file:com.liato.bankdroid.banking.banks.Vasttrafik.java

@Override
public void update() throws BankException, LoginException, BankChoiceException {
    super.update();
    if (username == null || password == null || username.length() == 0 || password.length() == 0) {
        throw new LoginException(res.getText(R.string.invalid_username_password).toString());
    }//from www  .j a v  a 2  s  .  com
    urlopen = login();
    try {
        response = urlopen.open("https://www.vasttrafik.se/mina-sidor-inloggad/mina-kort/");
        Matcher matcher;
        Matcher matcher_b;

        matcher = reAccounts.matcher(response);
        while (matcher.find()) {
            /*
             * Capture groups:
             * GROUP                EXAMPLE DATA
             * 1: Card number       1111111111
             * 2: Name              Nytt
             * 3: Balance information
             */

            if ("".equals(matcher.group(1))) {
                continue;
            }

            matcher_b = reBalance.matcher(matcher.group(3));
            if (matcher_b.find()) {
                /*
                 * Capture groups:
                 * GROUP                EXAMPLE DATA
                 * 1: Type              Kontoladdning
                 * 2: Amount            592,80 kr
                 */

                String balanceString = matcher_b.group(2).replaceAll("\\<a[^>]*>", "")
                        .replaceAll("\\<[^>]*>", "").trim();

                accounts.add(new Account(Html.fromHtml(matcher.group(2)).toString().trim(),
                        Helpers.parseBalance(balanceString), matcher.group(1)));
                balance = balance.add(Helpers.parseBalance(balanceString));
            }
        }

        if (accounts.isEmpty()) {
            throw new BankException(res.getText(R.string.no_accounts_found).toString());
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        super.updateComplete();
    }
}

From source file:com.viettel.view.MainHome.SelectEventPlace.java

/**
*  Mo ta chuc nang cua ham/*from  w  w  w.  java2 s.  com*/
*  @author: HocTB
*  @return: void
*  @throws: 
*/
private void bindComponents() {
    ActionBar actionBar = (ActionBar) app.findViewById(R.id.actionbar);
    actionBar.setTitle(getResources().getString(R.string.SELECT_PLACE));

    txt_place = (EditText) app.findViewById(R.id.txt_place);
    btnSearchPlace = (ImageButton) app.findViewById(R.id.btnSearchPlace);
    //listview
    listViewPlace = (ListView) app.findViewById(R.id.listViewPlace);
    listViewPlace.setDividerHeight(0);

    btnDefaultPlace = (Button) app.findViewById(R.id.btnDefaultPlace);
    btnDefaultPlace.setText(Html.fromHtml(getResources().getString(R.string.PLACE_NOT_FOUND) + "<br/>"
            + getResources().getString(R.string.USE_ADDRESS) + "<b>\""
            + getResources().getString(R.string.PLACE_DEFAULT) + "\"</b>"));
    btnDefaultPlace.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

        }
    });
}

From source file:com.blogspot.marioboehmer.thingibrowse.fragments.ThingDetailsFragment.java

private void updateView(Thing thing) {
    ImageTag tag = imageTagFactory.build(thing.getThingImageUrl());
    thingImageButton.setTag(tag);//ww w  .  j  a  v  a 2 s . c  o m
    imageLoader.load(thingImageButton);

    thingTitle.setText(Html.fromHtml(thing.getThingTitle()));
    thingCreatedBy.setText(thing.getThingCreatedBy());
    thingCreationDate.setText(thing.getThingDate());

    showDescription(thing.getThingDescription());
    showInstructions(thing.getThingInstructions());
    showFiles(thing.getThingFiles());

    hideProgressBar();
}

From source file:org.sirimangalo.meditationplus.AdapterCommit.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.list_item_commit, parent, false);

    final View shell = rowView.findViewById(R.id.detail_shell);

    rowView.setOnClickListener(new View.OnClickListener() {
        @Override/*from  ww  w  .j a v  a 2  s . com*/
        public void onClick(View view) {
            boolean visible = shell.getVisibility() == View.VISIBLE;

            shell.setVisibility(visible ? View.GONE : View.VISIBLE);

            context.setCommitVisible(position, !visible);

        }
    });

    final JSONObject p = values.get(position);

    TextView title = (TextView) rowView.findViewById(R.id.title);
    TextView descV = (TextView) rowView.findViewById(R.id.desc);
    TextView defV = (TextView) rowView.findViewById(R.id.def);
    TextView usersV = (TextView) rowView.findViewById(R.id.users);
    TextView youV = (TextView) rowView.findViewById(R.id.you);

    try {

        if (p.getBoolean("open"))
            shell.setVisibility(View.VISIBLE);

        title.setText(p.getString("title"));
        descV.setText(p.getString("description"));

        String length = p.getString("length");
        String time = p.getString("time");
        final String cid = p.getString("cid");

        String def = "";

        boolean repeat = false;

        if (length.indexOf(":") > 0) {
            repeat = true;
            String[] lengtha = length.split(":");
            def += lengtha[0] + " minutes walking and " + lengtha[1] + " minutes sitting";
        } else
            def += length + " minutes total meditation";

        String period = p.getString("period");

        String day = p.getString("day");

        if (period.equals("daily")) {
            if (repeat)
                def += " every day";
            else
                def += " per day";
        } else if (period.equals("weekly")) {
            if (repeat)
                def += " every " + dow[Integer.parseInt(day)];
            else
                def += " per week";
        } else if (period.equals("monthly")) {
            if (repeat)
                def += " on the " + day
                        + (day.substring(day.length() - 1).equals("1") ? "st"
                                : (day.substring(day.length() - 1).equals("2") ? "nd"
                                        : (day.substring(day.length() - 1).equals("3") ? "rd" : "th")))
                        + " day of the month";
            else
                def += " per month";
        } else if (period.equals("yearly")) {
            if (repeat)
                def += " on the " + day
                        + (day.substring(day.length() - 1).equals("1") ? "st"
                                : (day.substring(day.length() - 1).equals("2") ? "nd"
                                        : (day.substring(day.length() - 1).equals("3") ? "rd" : "th")))
                        + " day of the year";
            else
                def += " per year";
        }

        if (!time.equals("any")) {
            Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            utc.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.split(":")[0]));
            utc.set(Calendar.MINUTE, Integer.parseInt(time.split(":")[1]));

            Calendar here = Calendar.getInstance();
            here.setTimeInMillis(utc.getTimeInMillis());

            int hours = here.get(Calendar.HOUR_OF_DAY);
            int minutes = here.get(Calendar.MINUTE);

            def += " at " + (time.length() == 4 ? "0" : "") + time.replace(":", "") + "h UTC <i>("
                    + (hours > 12 ? hours - 12 : hours) + ":" + ((minutes < 10 ? "0" : "") + minutes) + " "
                    + (hours > 11 && hours < 24 ? "PM" : "AM") + " your time)</i>";
        }

        defV.setText(Html.fromHtml(def));

        JSONObject usersJ = p.getJSONObject("users");

        ArrayList<String> committedArray = new ArrayList<String>();

        // collect into array

        for (int i = 0; i < usersJ.names().length(); i++) {
            try {
                String j = usersJ.names().getString(i);
                String k = j;
                //                    if(j.equals(p.getString("creator")))
                //                        k = "["+j+"]";
                committedArray.add(k);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        String text = context.getString(R.string.committed) + " ";

        // add spans

        int committed = -1;

        int pos = text.length(); // start after "Committed: "

        text += TextUtils.join(", ", committedArray);
        Spannable span = new SpannableString(text);

        span.setSpan(new StyleSpan(Typeface.BOLD), 0, pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // bold the "Online: "

        for (int i = 0; i < committedArray.size(); i++) {
            try {

                final String oneCom = committedArray.get(i);
                String userCom = usersJ.getString(oneCom);
                //String userCom = usersJ.getString(oneCom.replace("[", "").replace("]", ""));

                //if(oneCom.replace("[","").replace("]","").equals(loggedUser))
                if (oneCom.equals(loggedUser))
                    committed = Integer.parseInt(userCom);

                int end = pos + oneCom.length();

                ClickableSpan clickable = new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        context.showProfile(oneCom);
                    }

                };
                span.setSpan(clickable, pos, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                span.setSpan(new UnderlineSpan() {
                    public void updateDrawState(TextPaint tp) {
                        tp.setUnderlineText(false);
                    }
                }, pos, end, 0);

                String color = Utils.makeRedGreen(Integer.parseInt(userCom), true);

                span.setSpan(new ForegroundColorSpan(Color.parseColor("#FF" + color)), pos, end,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                pos += oneCom.length() + 2;

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

        usersV.setText(span);
        usersV.setMovementMethod(new LinkMovementMethod());

        if (loggedUser != null && loggedUser.length() > 0) {
            LinearLayout bl = (LinearLayout) rowView.findViewById(R.id.commit_buttons);
            if (!usersJ.has(loggedUser)) {
                Button commitB = new Button(context);
                commitB.setId(R.id.commit_button);
                commitB.setText(R.string.commit);
                commitB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("commitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB);
            } else {
                Button commitB = new Button(context);
                commitB.setId(R.id.uncommit_button);
                commitB.setText(R.string.uncommit);
                commitB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("uncommitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB);
            }

            if (loggedUser.equals(p.getString("creator")) || context.isAdmin) {
                Button commitB2 = new Button(context);
                commitB2.setId(R.id.edit_commit_button);
                commitB2.setText(R.string.edit);
                commitB2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = new Intent(context, ActivityCommit.class);
                        i.putExtra("commitment", p.toString());
                        context.startActivity(i);
                    }
                });
                bl.addView(commitB2);

                Button commitB3 = new Button(context);
                commitB3.setId(R.id.uncommit_button);
                commitB3.setText(R.string.delete);
                commitB3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("delcommitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB3);
            }

        }

        if (committed > -1) {
            int color = Color.parseColor("#FF" + Utils.makeRedGreen(committed, false));
            rowView.setBackgroundColor(color);
        }

        if (committed != -1) {
            youV.setText(String.format(context.getString(R.string.you_commit_x), committed));
            youV.setVisibility(View.VISIBLE);
        }

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

From source file:com.eTilbudsavis.etasdk.model.Typeahead.java

/**
 * This method inserts a set of custom tags to highlight the parts of the subject that
 * was matched by the API, to a given query. The {@link #getSubject() subject} is then returned
 * as a {@link Spanned} object. This type of object can directly be used in a TextView to create
 * the desired effect./*from   ww  w  .  jav a 2s  . com*/
 * 
 * @return A {@link Spanned} containing the subject, or {@code null} if
 *          subject id null
 */
public Spanned getHtml(String startTag, String endTag) {

    if (mSubject == null) {
        return null;
    }

    if ((mOffset == 0 && mLength == 0) || mOffset > mSubject.length()
            || ((mOffset + mLength) > mSubject.length())) {

        // no really good reason to prepend the string with both tags
        return Html.fromHtml(mSubject);

    } else {

        try {

            StringBuilder sb = new StringBuilder();

            int start = mOffset;
            int end = mOffset + mLength;

            if (mOffset > 0) {
                sb.append(mSubject.substring(0, start));
            }
            sb.append(startTag);
            sb.append(mSubject.substring(start, end));
            sb.append(endTag);
            if (end < mSubject.length()) {
                sb.append(mSubject.substring(end));
            }
            String html = sb.toString();
            return Html.fromHtml(html);

        } catch (StringIndexOutOfBoundsException e) {
            EtaLog.e(TAG, "", e);
        }

        return Html.fromHtml(mSubject);

    }

}

From source file:com.liato.bankdroid.banking.banks.FirstCard.java

@Override
public void updateTransactions(Account account, Urllib urlopen) throws LoginException, BankException {
    super.updateTransactions(account, urlopen);
    Matcher matcher;//from   www  .  j  a  v  a2  s .c om
    try {
        response = urlopen.open("https://www.firstcard.se/mkol/translist.jsp?p=a&cardID=" + account.getId());
        matcher = reTransactions.matcher(response);
        ArrayList<Transaction> transactions = new ArrayList<Transaction>();
        while (matcher.find()) {
            /*
             * Capture groups:
             * GROUP                  EXAMPLE DATA
             * 1: date                  101006
             * 2: specification            GOOGLE *RealArcade
             * 3: currency               USD
             * 4: amount               3,49
             * 5: amount in local currency   24,08
             * 
             */
            String strDate = Html.fromHtml(matcher.group(1)).toString().trim();
            strDate = "20" + strDate.charAt(0) + strDate.charAt(1) + "-" + strDate.charAt(2) + strDate.charAt(3)
                    + "-" + strDate.charAt(4) + strDate.charAt(5);
            transactions.add(new Transaction(strDate, Html.fromHtml(matcher.group(2)).toString().trim(),
                    Helpers.parseBalance(matcher.group(5)).negate()));
        }
        account.setTransactions(transactions);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:id.nci.stm_9.HkpKeyServer.java

@Override
public ArrayList<KeyInfo> search(String query) throws QueryException, TooManyResponses, InsufficientQuery {
    ArrayList<KeyInfo> results = new ArrayList<KeyInfo>();

    if (query.length() < 3) {
        throw new InsufficientQuery();
    }//from  w  w w  .  ja  v  a2 s  . c om

    String encodedQuery;
    try {
        encodedQuery = URLEncoder.encode(query, "utf8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
    String request = "/pks/lookup?op=index&search=" + encodedQuery;

    String data = null;
    try {
        data = query(request);
    } catch (HttpError e) {
        if (e.getCode() == 404) {
            return results;
        } else {
            if (e.getData().toLowerCase().contains("no keys found")) {
                return results;
            } else if (e.getData().toLowerCase().contains("too many")) {
                throw new TooManyResponses();
            } else if (e.getData().toLowerCase().contains("insufficient")) {
                throw new InsufficientQuery();
            }
        }
        throw new QueryException("querying server(s) for '" + mHost + "' failed");
    }

    Matcher matcher = PUB_KEY_LINE.matcher(data);
    while (matcher.find()) {
        KeyInfo info = new KeyInfo();
        info.size = Integer.parseInt(matcher.group(1));
        info.algorithm = matcher.group(2);
        info.keyId = PgpKeyHelper.convertHexToKeyId(matcher.group(3));
        info.fingerPrint = PgpKeyHelper.convertKeyIdToHex(info.keyId);
        String chunks[] = matcher.group(4).split("-");
        info.date = new GregorianCalendar(Integer.parseInt(chunks[0]), Integer.parseInt(chunks[1]),
                Integer.parseInt(chunks[2])).getTime();
        info.userIds = new ArrayList<String>();
        if (matcher.group(5).startsWith("*** KEY")) {
            info.revoked = matcher.group(5);
        } else {
            String tmp = matcher.group(5).replaceAll("<.*?>", "");
            tmp = Html.fromHtml(tmp).toString();
            info.userIds.add(tmp);
        }
        if (matcher.group(6).length() > 0) {
            Matcher matcher2 = USER_ID_LINE.matcher(matcher.group(6));
            while (matcher2.find()) {
                String tmp = matcher2.group(1).replaceAll("<.*?>", "");
                tmp = Html.fromHtml(tmp).toString();
                info.userIds.add(tmp);
            }
        }
        results.add(info);
    }

    return results;
}

From source file:com.liato.bankdroid.banking.banks.sebkort.SEBKortBase.java

@Override
public Urllib login() throws LoginException, BankException {
    try {/*w  ww.  j  a  va2 s. com*/
        LoginPackage lp = preLogin();
        urlopen.addHeader("Origin", String.format("https://%s", mApiBase));
        urlopen.addHeader("Referer",
                String.format("https://%s/nis/m/%s/external/t/login/index", mApiBase, mProviderPart));
        urlopen.addHeader("X-Requested-With", "XMLHttpRequest");
        List<NameValuePair> postData = lp.getPostData();
        postData.remove(mParamsTarget);
        postData.remove(mParamsErrorTarget);
        postData.add(
                new BasicNameValuePair("target", String.format("/nis/m/%s/login/loginSuccess", mProviderPart)));
        postData.add(new BasicNameValuePair("errorTarget",
                String.format("/nis/m/%s/external/login/loginError", mProviderPart)));

        LoginResponse r = mObjectMapper.readValue(urlopen.openStream(lp.getLoginTarget(), postData, true),
                LoginResponse.class);
        if ("Failure".equalsIgnoreCase(r.getReturnCode())) {
            throw new LoginException(
                    !TextUtils.isEmpty(r.getMessage()) ? Html.fromHtml(r.getMessage()).toString()
                            : res.getText(R.string.invalid_username_password).toString());
        }
    } catch (ClientProtocolException e) {
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    }
    return urlopen;
}

From source file:fr.simon.marquis.secretcodes.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    getSupportActionBar().setTitle(Utils.applyCustomTypeFace(getString(R.string.app_name), this));
    setContentView(R.layout.activity_main);
    mEmptyView = findViewById(R.id.emptyView);
    mGridView = (GridView) findViewById(R.id.gridView);
    mGridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
    mGridView.setAdapter(new SecretCodeAdapter(this, Utils.getSecretCodes(this)));
    mGridView.setEmptyView(mEmptyView);/*w ww .  j av a  2s. co m*/
    mEmptyView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mEmptyView.setEnabled(false);
            mEmptyView.animate().alpha(0)
                    .setDuration(getResources().getInteger(android.R.integer.config_longAnimTime));
            startService(new Intent(MainActivity.this, CrawlerService.class));
        }
    });
    mGridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            String code = ((SecretCode) arg0.getItemAtPosition(arg2)).getCode();
            Toast.makeText(MainActivity.this, getString(R.string.execute_code, code), Toast.LENGTH_SHORT)
                    .show();
            try {
                sendBroadcast(new Intent("android.provider.Telephony.SECRET_CODE",
                        Uri.parse("android_secret_code://" + code)));
            } catch (java.lang.SecurityException se) {
                Toast.makeText(MainActivity.this, R.string.security_exception, Toast.LENGTH_LONG).show();
            }
        }
    });

    mGridView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            ((SecretCodeAdapter) mGridView.getAdapter()).itemCheckedStateChanged(position, checked);
            mode.setTitle(Html.fromHtml("<b>" + mGridView.getCheckedItemCount() + "</b>"));
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.action_delete:
                ((SecretCodeAdapter) mGridView.getAdapter()).deleteSelection(getApplicationContext());
                mode.finish();
                return true;
            case R.id.action_select_all:
                boolean check = mGridView.getCheckedItemCount() != mGridView.getCount();
                for (int i = 0; i < mGridView.getCount(); i++) {
                    mGridView.setItemChecked(i, check);
                }
                return true;
            default:
                return false;
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater inflater = mode.getMenuInflater();
            if (inflater != null) {
                inflater.inflate(R.menu.cab, menu);
            }
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            ((SecretCodeAdapter) mGridView.getAdapter()).resetSelection();
            supportInvalidateOptionsMenu();
        }

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

    });

    supportInvalidateOptionsMenu();
}