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:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java

public static String makeRequest(String tableName, String json)
        throws ClientProtocolException, IOException, JSONException, Exception {
    if (isCanceled) {
        return FLOWZR_MSG_NET_ERROR;
    }/*from   www .  j  av a2 s .c  om*/

    String uri = FLOWZR_API_URL + nsString + "/" + tableName + "/";
    String strResponse;

    HttpPost httpPost = new HttpPost(uri);

    httpPost.setEntity(new StringEntity(json, HTTP.UTF_8));
    httpPost.addHeader("Cookie", "dev_appserver_login=test@example.com:False:18580476422013912411");

    HttpResponse response = http_client.execute(httpPost);
    HttpEntity entity = response.getEntity();
    int code = response.getStatusLine().getStatusCode();
    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
    strResponse = reader.readLine();
    if (!tableName.equals("currency_exchange_rate")) {
        JSONArray arr = new JSONArray();
        arr = new JSONArray(strResponse);
        for (int i = 0; i < arr.length(); i++) {
            JSONObject o = arr.getJSONObject(i);
            String key = o.getString("key");
            int id = o.getInt("id");
            ContentValues args = new ContentValues();
            args.put("remote_key", key);

            try {
                db.update(tableName, args, String.format("%s = ?", "_id"), new String[] { String.valueOf(id) });
            } catch (Exception e) {
                Log.e("flowzr", "error updating rate ...");
                e.printStackTrace();
            }
        }
    }
    entity.consumeContent();
    if (code != 200) {
        throw new Exception(Html.fromHtml(strResponse).toString());
    }
    return strResponse;
}

From source file:com.bt.heliniumstudentapp.DayActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() != R.id.i_hwfloating_md)
        return super.onOptionsItemSelected(item);

    final ScheduleFragment.week.day day_data = schedule.day_get(schedule.day_get_index(lastPosition) + 2);

    if (day_data.floatings_get() == 0) {
        Toast.makeText(this, getString(R.string.homework_floating_no), Toast.LENGTH_SHORT).show();
        return true;
    }// ww  w.j a  va 2  s . co  m

    final AlertDialog.Builder hwf_dialog_builder = new AlertDialog.Builder(
            new ContextThemeWrapper(this, MainActivity.themeDialog));
    AlertDialog hwf_dialog;
    StringBuilder s;
    int i;

    hwf_dialog_builder.setTitle(getString(R.string.homework_floating));

    hwf_dialog_builder.setPositiveButton(android.R.string.ok, null);

    s = new StringBuilder();
    for (i = 0; i < day_data.floatings_get(); i++) {
        s.append(day_data.floating_get(i).course);
        s.append("\n");
        s.append(Html.fromHtml(day_data.floating_get(i).text));
    }

    hwf_dialog_builder.setMessage(s.toString());

    hwf_dialog = hwf_dialog_builder.create();

    hwf_dialog.setCanceledOnTouchOutside(true);
    hwf_dialog.show();

    hwf_dialog.getButton(AlertDialog.BUTTON_POSITIVE)
            .setTextColor(ContextCompat.getColor(this, MainActivity.accentSecondaryColor));

    return true;
}

From source file:com.irccloud.android.Notifications.java

@SuppressLint("NewApi")
private android.app.Notification buildNotification(String ticker, int bid, long[] eids, String title,
        String text, Spanned big_text, int count, Intent replyIntent, Spanned wear_text, String network,
        String auto_messages[]) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());

    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            IRCCloudApplication.getInstance().getApplicationContext())
                    .setContentTitle(title + ((network != null) ? (" (" + network + ")") : ""))
                    .setContentText(Html.fromHtml(text)).setAutoCancel(true).setTicker(ticker)
                    .setWhen(eids[0] / 1000).setSmallIcon(R.drawable.ic_stat_notify)
                    .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources()
                            .getColor(R.color.dark_blue))
                    .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setPriority(NotificationCompat.PRIORITY_HIGH).setOnlyAlertOnce(false);

    if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 10000) {
        if (prefs.getBoolean("notify_vibrate", true))
            builder.setDefaults(android.app.Notification.DEFAULT_VIBRATE);
        String ringtone = prefs.getString("notify_ringtone", "content://settings/system/notification_sound");
        if (ringtone != null && ringtone.length() > 0)
            builder.setSound(Uri.parse(ringtone));
    }//from  www  . j ava2  s .co m

    int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1"));
    if (led_color == 1) {
        if (prefs.getBoolean("notify_vibrate", true))
            builder.setDefaults(
                    android.app.Notification.DEFAULT_LIGHTS | android.app.Notification.DEFAULT_VIBRATE);
        else
            builder.setDefaults(android.app.Notification.DEFAULT_LIGHTS);
    } else if (led_color == 2) {
        builder.setLights(0xFF0000FF, 500, 500);
    }

    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong("lastNotificationTime", System.currentTimeMillis());
    editor.commit();

    Intent i = new Intent();
    i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
            "com.irccloud.android.MainActivity"));
    i.putExtra("bid", bid);
    i.setData(Uri.parse("bid://" + bid));
    Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources()
            .getString(R.string.DISMISS_NOTIFICATION));
    dismiss.setData(Uri.parse("irccloud-dismiss://" + bid));
    dismiss.putExtra("bid", bid);
    dismiss.putExtra("eids", eids);

    PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(
            IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(
            PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT));
    builder.setDeleteIntent(dismissPendingIntent);

    if (replyIntent != null) {
        WearableExtender extender = new WearableExtender();
        PendingIntent replyPendingIntent = PendingIntent.getService(
                IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
        extender.addAction(
                new NotificationCompat.Action.Builder(R.drawable.ic_reply, "Reply", replyPendingIntent)
                        .addRemoteInput(
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build())
                        .build());

        if (count > 1 && wear_text != null)
            extender.addPage(
                    new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
                            .setContentText(wear_text).extend(new WearableExtender().setStartScrollBottom(true))
                            .build());

        NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder(
                title + ((network != null) ? (" (" + network + ")") : ""))
                        .setReadPendingIntent(dismissPendingIntent).setReplyAction(replyPendingIntent,
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build());

        if (auto_messages != null) {
            for (String m : auto_messages) {
                if (m != null && m.length() > 0) {
                    unreadConvBuilder.addMessage(m);
                }
            }
        } else {
            unreadConvBuilder.addMessage(text);
        }
        unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000);

        builder.extend(extender)
                .extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build()));
    }

    if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
        i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
        i.setData(Uri.parse("irccloud-bid://" + bid));
        i.putExtras(replyIntent);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent quickReplyIntent = PendingIntent.getActivity(
                IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.addAction(R.drawable.ic_action_reply, "Quick Reply", quickReplyIntent);
    }

    android.app.Notification notification = builder.build();

    RemoteViews contentView = new RemoteViews(
            IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification);
    contentView.setTextViewText(R.id.title, title + " (" + network + ")");
    contentView.setTextViewText(R.id.text,
            (count == 1) ? Html.fromHtml(text) : (count + " unread highlights."));
    contentView.setLong(R.id.time, "setTime", eids[0] / 1000);
    notification.contentView = contentView;

    if (Build.VERSION.SDK_INT >= 16 && big_text != null) {
        RemoteViews bigContentView = new RemoteViews(
                IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
                R.layout.notification_expanded);
        bigContentView.setTextViewText(R.id.title,
                title + (!title.equals(network) ? (" (" + network + ")") : ""));
        bigContentView.setTextViewText(R.id.text, big_text);
        bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000);
        if (count > 3) {
            bigContentView.setViewVisibility(R.id.more, View.VISIBLE);
            bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more");
        } else {
            bigContentView.setViewVisibility(R.id.more, View.GONE);
        }
        if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
            bigContentView.setViewVisibility(R.id.actions, View.VISIBLE);
            bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE);
            i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
            i.setData(Uri.parse("irccloud-bid://" + bid));
            i.putExtras(replyIntent);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent quickReplyIntent = PendingIntent.getActivity(
                    IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent);
        }
        notification.bigContentView = bigContentView;
    }

    return notification;
}

From source file:gr.scify.newsum.ui.SearchViewActivity.java

private void Sendsms() {
    TextView title = (TextView) findViewById(R.id.title);
    String sTitle = title.getText().toString();
    String smstext = "" + Html.fromHtml("<h2>" + "NewSum app : " + sTitle + "</h2><br>" + sText);

    // track the sendSms Action
    if (getAnalyticsPref()) {
        EasyTracker.getTracker().sendEvent(SHARING_ACTION, "Send SMS", title.getText().toString(), 0l);
    }// w  w  w  .  j  a v a 2  s.co  m
    Intent sendIntent = new Intent(Intent.ACTION_VIEW);
    sendIntent.setData(Uri.parse("sms:"));
    sendIntent.putExtra("sms_body", smstext);
    startActivity(sendIntent);

}

From source file:com.brodev.socialapp.fragment.EventDetailFragment.java

/**
 * Function create feed adapter// w  w  w  . j a va2  s.  c om
 * 
 * @return feed Adapter
 */
public FeedAdapter getFeedAdapter(FeedAdapter fadapter, String resString) {
    if (resString != null) {
        try {
            // init feed adapter

            JSONObject mainJSON = new JSONObject(resString);
            JSONArray outJson = mainJSON.getJSONArray("output");

            // if output json is null
            if (outJson.length() == 0 && page == 1) {
                Feed _feed = new Feed();
                _feed.setNo_share(true);
                _feed.setNotice(phraseManager.getPhrase(getActivity().getApplicationContext(),
                        "feed.there_are_no_new_feeds_to_view_at_this_time"));
                fadapter.add(_feed);
            }

            JSONObject pagesObj = null;

            for (int i = 0; i < outJson.length(); i++) {
                pagesObj = outJson.getJSONObject(i);

                Feed objFeed = new Feed();
                objFeed.setFeedId(pagesObj.getString("feed_id"));
                if (pagesObj.has("item_id")) {
                    objFeed.setItemId(pagesObj.getString("item_id"));
                }

                objFeed.setFullName(pagesObj.getString(FULLNAME));
                objFeed.setUserId(pagesObj.getString("user_id"));
                objFeed.setTime(pagesObj.getString(TIME));
                objFeed.setIcon(pagesObj.getString(ICON));
                if (pagesObj.has(TITLE)) {
                    objFeed.setTitle(pagesObj.getString(TITLE));
                }

                objFeed.setUserImage(pagesObj.getString(USERIMAGE));

                if (pagesObj.has("no_share")) {
                    objFeed.setNo_share(pagesObj.getBoolean("no_share"));
                } else {
                    objFeed.setNo_share(false);
                }

                if (pagesObj.has("feed_title")) {
                    objFeed.setTitleFeed(Html.fromHtml(pagesObj.getString("feed_title")).toString());
                }

                objFeed.setFeedLink(pagesObj.getString("feed_link"));
                if (pagesObj.has("parent_module_id") && !pagesObj.isNull("parent_module_id")) {
                    objFeed.setModule(pagesObj.getString("parent_module_id"));
                }

                if (pagesObj.has("enable_like")) {
                    if (!pagesObj.isNull("feed_is_liked") && pagesObj.getString("feed_is_liked") != "false") {
                        objFeed.setFeedIsLiked("feed_is_liked");
                    }
                    objFeed.setEnableLike(pagesObj.getBoolean("enable_like"));
                } else {
                    objFeed.setEnableLike(false);
                }

                if (pagesObj.has("can_post_comment")) {
                    objFeed.setCanPostComment(pagesObj.getBoolean("can_post_comment"));
                } else {
                    objFeed.setCanPostComment(false);
                }

                if (pagesObj.has("comment_type_id")) {
                    objFeed.setComment_type_id(pagesObj.getString("comment_type_id"));
                }

                if (pagesObj.has("total_comment")) {
                    objFeed.setTotalComment(pagesObj.getString("total_comment"));
                }

                if (pagesObj.has("profile_page_id")) {
                    objFeed.setProfile_page_id(pagesObj.getString("profile_page_id"));
                }

                if (pagesObj.has("feed_total_like")) {
                    objFeed.setHasLike(pagesObj.getString("feed_total_like"));
                    objFeed.setTotalLike(Integer.parseInt(pagesObj.getString("feed_total_like")));
                }

                if (pagesObj.has("feed_status")) {
                    objFeed.setStatus(pagesObj.getString("feed_status"));
                }

                if (pagesObj.has("feed_status_html")) {
                    objFeed.setStatus(pagesObj.getString("feed_status_html"));
                }

                // get more info for link...

                if (pagesObj.has("feed_title_extra")) {
                    objFeed.setFeedTitleExtra(Html.fromHtml(pagesObj.getString("feed_title_extra")).toString());
                }

                if (pagesObj.has("feed_content")) {
                    objFeed.setFeedContent(Html.fromHtml(pagesObj.getString("feed_content")).toString());
                }

                objFeed.setType(pagesObj.getJSONObject("social_app").getString("type_id"));

                if (pagesObj.has("can_share_item_on_feed")) {
                    objFeed.setCan_share_item_on_feed(pagesObj.getBoolean("can_share_item_on_feed"));
                }

                if (pagesObj.has("like_type_id")) {
                    objFeed.setLikeTypeId(pagesObj.getString("like_type_id"));
                }

                if (pagesObj.has("like_item_id")) {
                    objFeed.setLikeItemId(pagesObj.getString("like_item_id"));
                }

                if (pagesObj.has("feed_link_share") && !pagesObj.isNull("feed_link_share"))
                    objFeed.setShareFeedLink(Html.fromHtml(pagesObj.getString("feed_link_share")).toString());

                if (pagesObj.has("feed_link_share_url") && !pagesObj.isNull("feed_link_share_url"))
                    objFeed.setShareFeedLinkUrl(
                            Html.fromHtml(pagesObj.getString("feed_link_share_url")).toString());

                if (pagesObj.has("custom_data_cache")) {
                    if (pagesObj.getJSONObject("custom_data_cache").has("thread_id")
                            && !pagesObj.getJSONObject("custom_data_cache").isNull("thread_id"))
                        objFeed.setDataCacheId(
                                pagesObj.getJSONObject("custom_data_cache").getString("thread_id"));
                }

                if (pagesObj.has("social_app")) {
                    JSONObject socialObj = pagesObj.getJSONObject("social_app");
                    Object intervention = socialObj.get("link");

                    if (intervention instanceof JSONObject) {
                        JSONObject requestObj = socialObj.getJSONObject("link").getJSONObject("request");

                        if (requestObj.has("page_id")) {
                            objFeed.setPage_id_request(requestObj.getString("page_id"));
                        } else if (requestObj.has("user_id")) {
                            objFeed.setUser_id_request(requestObj.getString("user_id"));
                        } else if (requestObj.has("photo_id")) {
                            objFeed.setPhoto_id_request(requestObj.getString("photo_id"));
                        }
                    }
                }

                if (!pagesObj.isNull(IMAGE)) {

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

                    for (int m = 0; m < pagesObj.getJSONArray(IMAGE).length(); m++) {
                        Images_feed.add(pagesObj.getJSONArray(IMAGE).getString(m));
                        if (m == 0) {
                            objFeed.setImage1(pagesObj.getJSONArray(IMAGE).getString(m));
                        } else if (m == 1) {
                            objFeed.setImage2(pagesObj.getJSONArray(IMAGE).getString(m));
                        } else if (m == 2) {
                            objFeed.setImage3(pagesObj.getJSONArray(IMAGE).getString(m));
                        } else if (m == 3) {
                            objFeed.setImage4(pagesObj.getJSONArray(IMAGE).getString(m));
                        }
                        objFeed.setFeed_Image(Images_feed);
                    }
                }

                if (pagesObj.has("photos_id") && !pagesObj.isNull("photos_id")) {

                    ArrayList<String> Images_id = new ArrayList<String>();
                    for (int s = 0; s < pagesObj.getJSONArray("photos_id").length(); s++) {
                        Images_id.add(pagesObj.getJSONArray("photos_id").getString(s));
                        if (s == 0) {
                            objFeed.setImage_id_1(pagesObj.getJSONArray("photos_id").getString(s));
                        } else if (s == 1) {
                            objFeed.setImage_id_2(pagesObj.getJSONArray("photos_id").getString(s));
                        } else if (s == 2) {
                            objFeed.setImage_id_3(pagesObj.getJSONArray("photos_id").getString(s));
                        } else if (s == 3) {
                            objFeed.setImage_id_4(pagesObj.getJSONArray("photos_id").getString(s));
                        }
                    }
                    objFeed.setImagesId(Images_id);
                }

                // if have share feed
                if (pagesObj.has("share_feed")) {
                    Object intervention = pagesObj.get("share_feed");

                    if (intervention instanceof JSONObject) {
                        JSONObject shareObj = (JSONObject) intervention;
                        FeedMini feedMini = new FeedMini();

                        if (shareObj.has("full_name")) {
                            feedMini.setFullname(shareObj.getString("full_name"));
                        }

                        if (shareObj.has("feed_info")) {
                            feedMini.setFeedInfo(shareObj.getString("feed_info"));
                        }

                        if (shareObj.has("feed_status") && !shareObj.isNull("feed_status")
                                && !"".equals(shareObj.getString("feed_status"))) {
                            feedMini.setFeedStatus(shareObj.getString("feed_status"));
                        }

                        if (shareObj.has("feed_title") && !shareObj.isNull("feed_title")
                                && !"".equals(shareObj.getString("feed_title"))) {
                            feedMini.setFeedTitle(shareObj.getString("feed_title"));
                        }

                        if (shareObj.has("feed_image") && !shareObj.isNull("feed_image")
                                && !"".equals(shareObj.getString("feed_image"))) {
                            feedMini.setFeedImage(shareObj.getString("feed_image"));
                        }
                        feedMini.setModule(pagesObj.getString("parent_module_id"));
                        objFeed.setFeedMini(feedMini);

                    }
                }

                fadapter.add(objFeed);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    return fadapter;

}

From source file:com.bravo.ecm.service.ScannedFile.java

public Spanned getAuthor(boolean page) {
    Spanned txt = null;// w  w  w  . ja  va2s. co m
    if (page && current_page > 0 && total_pages > 0) {
        txt = Html.fromHtml(
                getAuthor() + "," + " on " + "<b>page " + current_page + " of " + total_pages + "</b>");
    } else {
        txt = Html.fromHtml(getAuthor());
    }
    return txt;
}

From source file:busradar.madison.StopDialog.java

@Override
public void show() {
    new Thread() {
        @Override//from   w  w  w . j  a  va 2  s .c om
        public void run() {

            for (final RouteURL r : routes) {
                G.activity.runOnUiThread(new Runnable() {
                    public void run() {
                        cur_loading_text
                                .setText(String.format("Loading route %s...", G.route_points[r.route].name));
                    }
                });

                final ArrayList<RouteTime> curtimes = new ArrayList<RouteTime>();
                try {
                    System.err.printf("BusRadar URL %s\n", TRANSITTRACKER_URL + r.url);
                    URL url = new URL(TRANSITTRACKER_URL + r.url);
                    URLConnection url_conn = url.openConnection();
                    if (url_conn instanceof HttpsURLConnection) {
                        ((HttpsURLConnection) url_conn).setHostnameVerifier(new HostnameVerifier() {

                            public boolean verify(String hostname, SSLSession session) {
                                return true;
                            }
                        });
                    }
                    InputStream is = url_conn.getInputStream();
                    Scanner scan = new Scanner(is, "UTF-8");

                    //String outstr_cur = "Route " + r.route + "\n";

                    if (scan.findWithinHorizon(num_vehicles_re, 0) != null) {

                        while (scan.findWithinHorizon(time_re, 0) != null) {
                            RouteTime time = new RouteTime();
                            time.route = r.route;
                            time.time = scan.match().group(1).replace(".", "");
                            time.dir = scan.match().group(2);
                            //time.date = DateFormat.getTimeInstance(DateFormat.SHORT).parse(time.time);

                            SimpleDateFormat f = new SimpleDateFormat("h:mm aa", Locale.US);
                            time.date = f.parse(time.time);
                            r.status = RouteURL.DONE;

                            //outstr_cur += String.format("%s to %s\n", time.time, time.dir);
                            curtimes.add(time);
                        }

                        while (scan.findWithinHorizon(time_re_backup, 0) != null) {
                            RouteTime time = new RouteTime();
                            time.route = r.route;
                            time.time = scan.match().group(1).replace(".", "");
                            //time.dir = scan.match().group(2);
                            //time.date = DateFormat.getTimeInstance(DateFormat.SHORT).parse(time.time);

                            SimpleDateFormat f = new SimpleDateFormat("h:mm aa", Locale.US);
                            time.date = f.parse(time.time);
                            r.status = RouteURL.DONE;

                            //outstr_cur += String.format("%s to %s\n", time.time, time.dir);
                            curtimes.add(time);
                        }

                    }

                    //                  else if (scan.findWithinHorizon(no_busses_re, 0) != null) {
                    //                     r.status = RouteURL.NO_MORE_TODAY; 
                    //                  } 
                    //                  else if (scan.findWithinHorizon(no_timepoints_re, 0) != null) {
                    //                     r.status = RouteURL.NO_TIMEPOINTS;
                    //                  }
                    //                  else {
                    //                     r.status = RouteURL.ERROR;
                    //                     System.out.printf("BusRadar: Could not get stop info for %s\n", r.url);
                    //                     
                    //                     throw new Exception("Error parsing TransitTracker webpage.");
                    //                  }
                    else {
                        r.status = RouteURL.NO_STOPS_UNKONWN;
                    }

                    //r.text = outstr_cur;

                    G.activity.runOnUiThread(new Runnable() {
                        public void run() {
                            times.addAll(curtimes);
                            StopDialog.this.update_times();
                        }
                    });

                }
                //               catch  (final IOException ioe) {
                //                  log_problem(ioe);
                //                  G.activity.runOnUiThread(new Runnable() {
                //                     public void run() {
                //                        final Context ctx = StopDialog.this.getContext();
                //                        
                //                        StopDialog.this.setContentView(new RelativeLayout(ctx) {{
                //                           addView(new TextView(ctx) {{
                //                              setText(Html.fromHtml("Error downloading data. Is the data connection enabled?"+
                //                                                  "<p>Report problems to <a href='mailto:support@busradarapp.com'>support@busradarapp.com</a><p>"+ioe));
                //                              setPadding(5, 5, 5, 5);
                //                              this.setMovementMethod(LinkMovementMethod.getInstance());
                //                           }}, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
                //                        }});
                //                     }
                //                  });                  
                //                  return;
                //               }
                catch (Exception e) {
                    log_problem(e);

                    String custom_msg = "";
                    final String turl = TRANSITTRACKER_URL + r.url;
                    if ((e instanceof SocketException) || (e instanceof UnknownHostException)) {
                        // data connection doesn't work
                        custom_msg = "Error downloading data. Is the data connection enabled?"
                                + "<p>Report problems to <a href='mailto:support@busradarapp.com'>support@busradarapp.com</a><p>"
                                + TextUtils.htmlEncode(e.toString());
                    } else {

                        String rurl = String.format(
                                "http://www.cityofmadison.com/metro/BusStopDepartures/StopID/%04d.pdf", stopid);
                        custom_msg = "Trouble retrieving real-time arrival estimates from <a href='" + turl
                                + "'>this</a> TransitTracker webpage, which is displayed below. "
                                + "Meanwhile, try PDF timetable <a href='" + rurl + "'>here</a>. "
                                + "Contact us at <a href='mailto:support@busradarapp.com'>support@busradarapp.com</a> to report the problem.<p>"
                                + TextUtils.htmlEncode(e.toString());
                    }

                    final String msg = custom_msg;

                    G.activity.runOnUiThread(new Runnable() {
                        public void run() {
                            final Context ctx = StopDialog.this.getContext();

                            StopDialog.this.setContentView(new RelativeLayout(ctx) {
                                {
                                    addView(new TextView(ctx) {
                                        {
                                            setId(1);
                                            setText(Html.fromHtml(msg));
                                            setPadding(5, 5, 5, 5);
                                            this.setMovementMethod(LinkMovementMethod.getInstance());
                                        }
                                    }, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

                                    addView(new WebView(ctx) {
                                        {
                                            setWebViewClient(new WebViewClient());
                                            loadUrl(turl);
                                        }
                                    }, new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
                                            LayoutParams.FILL_PARENT) {
                                        {
                                            addRule(RelativeLayout.BELOW, 1);
                                        }
                                    });
                                }
                            });
                        }
                    });
                    return;
                }

            }

            G.activity.runOnUiThread(new Runnable() {
                public void run() {
                    cur_loading_text.setText("");
                }
            });
        }
    }.start();

    super.show();

}

From source file:com.ichi2.anki.StudyOptionsFragment.java

/**
 * Returns a listener that rebuilds the interface after execute.
 *
 * @param refreshDecklist If true, the listener notifies the parent activity to update its deck list
 *                        to reflect the latest values.
 *///w  w w.  java 2s.c o  m
private DeckTask.TaskListener getDeckTaskListener(final boolean refreshDecklist) {
    return new DeckTask.TaskListener() {
        @Override
        public void onPreExecute() {

        }

        @Override
        public void onPostExecute(DeckTask.TaskData result) {
            dismissProgressDialog();
            if (result != null) {
                // Get the return values back from the AsyncTask
                Object[] obj = result.getObjArray();
                int newCards = (Integer) obj[0];
                int lrnCards = (Integer) obj[1];
                int revCards = (Integer) obj[2];
                int totalNew = (Integer) obj[3];
                int totalCards = (Integer) obj[4];
                int eta = (Integer) obj[7];

                // Don't do anything if the fragment is no longer attached to it's Activity or col has been closed
                if (getActivity() == null) {
                    Timber.e("StudyOptionsFragment.mRefreshFragmentListener :: can't refresh");
                    return;
                }
                // Reinitialize controls incase changed to filtered deck
                initAllContentViews();
                // Set the deck name
                String fullName;
                JSONObject deck = getCol().getDecks().current();
                try {
                    // Main deck name
                    fullName = deck.getString("name");
                    String[] name = fullName.split("::");
                    StringBuilder nameBuilder = new StringBuilder();
                    if (name.length > 0) {
                        nameBuilder.append(name[0]);
                    }
                    if (name.length > 1) {
                        nameBuilder.append("\n").append(name[1]);
                    }
                    if (name.length > 3) {
                        nameBuilder.append("...");
                    }
                    if (name.length > 2) {
                        nameBuilder.append("\n").append(name[name.length - 1]);
                    }
                    mTextDeckName.setText(nameBuilder.toString());

                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

                // open cram deck option if deck is opened for the first time
                if (mLoadWithDeckOptions == true) {
                    openFilteredDeckOptions(mLoadWithDeckOptions);
                    return;
                }
                // Switch between the empty view, the ordinary view, and the "congratulations" view
                boolean isDynamic = deck.optInt("dyn", 0) != 0;
                if (totalCards == 0 && !isDynamic) {
                    mCurrentContentView = CONTENT_EMPTY;
                    mDeckInfoLayout.setVisibility(View.VISIBLE);
                    mTextCongratsMessage.setVisibility(View.VISIBLE);
                    mTextCongratsMessage.setText(R.string.studyoptions_empty);
                    mButtonStart.setVisibility(View.GONE);
                } else if (newCards + lrnCards + revCards == 0) {
                    mCurrentContentView = CONTENT_CONGRATS;
                    if (!isDynamic) {
                        mDeckInfoLayout.setVisibility(View.GONE);
                        mButtonStart.setVisibility(View.VISIBLE);
                        mButtonStart.setText(R.string.custom_study);
                    } else {
                        mButtonStart.setVisibility(View.GONE);
                    }
                    mTextCongratsMessage.setVisibility(View.VISIBLE);
                    mTextCongratsMessage.setText(getCol().getSched().finishedMsg(getActivity()));
                } else {
                    mCurrentContentView = CONTENT_STUDY_OPTIONS;
                    mDeckInfoLayout.setVisibility(View.VISIBLE);
                    mTextCongratsMessage.setVisibility(View.GONE);
                    mButtonStart.setVisibility(View.VISIBLE);
                    mButtonStart.setText(R.string.studyoptions_start);
                }

                // Set deck description
                String desc;
                if (isDynamic) {
                    desc = getResources().getString(R.string.dyn_deck_desc);
                } else {
                    desc = getCol().getDecks().getActualDescription();
                }
                if (desc.length() > 0) {
                    mTextDeckDescription.setText(Html.fromHtml(desc));
                    mTextDeckDescription.setVisibility(View.VISIBLE);
                } else {
                    mTextDeckDescription.setVisibility(View.GONE);
                }

                // Set new/learn/review card counts
                mTextTodayNew.setText(String.valueOf(newCards));
                mTextTodayLrn.setText(String.valueOf(lrnCards));
                mTextTodayRev.setText(String.valueOf(revCards));

                // Set the total number of new cards in deck
                if (totalNew < NEW_CARD_COUNT_TRUNCATE_THRESHOLD) {
                    // if it hasn't been truncated by libanki then just set it usually
                    mTextNewTotal.setText(String.valueOf(totalNew));
                } else {
                    // if truncated then make a thread to allow full count to load
                    mTextNewTotal.setText(">1000");
                    if (mFullNewCountThread != null) {
                        // a thread was previously made -- interrupt it
                        mFullNewCountThread.interrupt();
                    }
                    mFullNewCountThread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Collection collection = getCol();
                            // TODO: refactor code to not rewrite this query, add to Sched.totalNewForCurrentDeck()
                            StringBuilder sbQuery = new StringBuilder();
                            sbQuery.append("SELECT count(*) FROM cards WHERE did IN ");
                            sbQuery.append(Utils.ids2str(collection.getDecks().active()));
                            sbQuery.append(" AND queue = 0");
                            final int fullNewCount = collection.getDb().queryScalar(sbQuery.toString());
                            if (fullNewCount > 0) {
                                Runnable setNewTotalText = new Runnable() {
                                    @Override
                                    public void run() {
                                        mTextNewTotal.setText(String.valueOf(fullNewCount));
                                    }
                                };
                                if (!Thread.currentThread().isInterrupted()) {
                                    mTextNewTotal.post(setNewTotalText);
                                }
                            }
                        }
                    });
                    mFullNewCountThread.start();
                }

                // Set total number of cards
                mTextTotal.setText(String.valueOf(totalCards));
                // Set estimated time remaining
                if (eta != -1) {
                    mTextETA.setText(Integer.toString(eta));
                } else {
                    mTextETA.setText("-");
                }
                // Rebuild the options menu
                configureToolbar();
            }

            // If in fragmented mode, refresh the deck list
            if (mFragmented && refreshDecklist) {
                mListener.onRequireDeckListUpdate();
            }
        }

        @Override
        public void onProgressUpdate(DeckTask.TaskData... values) {

        }

        @Override
        public void onCancelled() {

        }
    };
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java

private CharSequence formatMessage(String contact, String body, String contentType) {
    System.out.println("MessageAdapter.java in formatMessage() ");
    SpannableStringBuilder buf = new SpannableStringBuilder();
    if (!TextUtils.isEmpty(body)) {
        // Converts html to spannable if ContentType is "text/html".
        if (contentType != null && "text/html".equals(contentType)) {
            buf.append("\n");
            buf.append(Html.fromHtml(body));
        } else {/*ww w  . j a v a 2s . c om*/
            SmileyParser parser = SmileyParser.getInstance();
            buf.append(parser.addSmileySpans(body));
        }
    }

    // We always show two lines because the optional icon bottoms are
    // aligned with the
    // bottom of the text field, assuming there are two lines for the
    // message and the sent time.
    buf.append("\n");
    int startOffset = buf.length();
    startOffset = buf.length();
    buf.setSpan(mTextSmallSpan, startOffset, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    System.out.println("formatMessage:" + buf);
    return buf;
}

From source file:com.slp.rss_api.activity.EditFeedActivity.java

/**
 * This is where the bulk of our work is done. This function is called in a background thread and should generate a new set of data to be
 * published by the loader.//from   w  w w  . j  a  va2s  .  co m
 */
@Override
public ArrayList<HashMap<String, String>> loadInBackground() {
    try {
        HttpURLConnection conn = NetworkUtils
                .setupConnection("https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=" + mSearchText);
        try {
            String jsonStr = new String(NetworkUtils.getBytes(conn.getInputStream()));

            // Parse results
            final ArrayList<HashMap<String, String>> results = new ArrayList<>();
            JSONObject response = new JSONObject(jsonStr).getJSONObject("responseData");
            JSONArray entries = response.getJSONArray("entries");
            for (int i = 0; i < entries.length(); i++) {
                try {
                    JSONObject entry = (JSONObject) entries.get(i);
                    String url = entry.get(EditFeedActivity.FEED_SEARCH_URL).toString();
                    if (!url.isEmpty()) {
                        HashMap<String, String> map = new HashMap<>();
                        map.put(EditFeedActivity.FEED_SEARCH_TITLE, Html
                                .fromHtml(entry.get(EditFeedActivity.FEED_SEARCH_TITLE).toString()).toString());
                        map.put(EditFeedActivity.FEED_SEARCH_URL, url);
                        map.put(EditFeedActivity.FEED_SEARCH_DESC, Html
                                .fromHtml(entry.get(EditFeedActivity.FEED_SEARCH_DESC).toString()).toString());

                        results.add(map);
                    }
                } catch (Exception ignored) {
                }
            }

            return results;
        } finally {
            conn.disconnect();
        }
    } catch (Exception e) {
        Log.e(TAG, "Error", e);
        return null;
    }
}