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:ru.orangesoftware.financisto2.export.flowzr.FlowzrSyncEngine.java

private String httpPush(ArrayList<NameValuePair> nameValuePairs, String action) throws Exception {
    HttpPost httppost = new HttpPost(
            FlowzrSyncOptions.FLOWZR_API_URL + options.getNamespace() + "/" + action + "/");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
    HttpResponse response;//from ww w . jav a 2s .c o  m
    String strResponse;
    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();
    entity.consumeContent();
    if (code != 200) {
        throw new Exception(Html.fromHtml(strResponse).toString());
    }
    return strResponse;
}

From source file:net.networksaremadeofstring.rhybudd.ViewZenossEventFragment.java

private void AddLogMessage(final String Message) {
    try {//w ww .  j ava  2 s . c  om
        addMessageProgressDialog = new ProgressDialog(getActivity());
        addMessageProgressDialog.setTitle("Contacting Zenoss");
        addMessageProgressDialog.setMessage("Please wait:\nProcessing Event Log Updates");
        addMessageProgressDialog.show();
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("ViewZenossEventFragment", "AddLogMessage Dialog", e);
    }

    addLogMessageHandler = new Handler() {
        public void handleMessage(Message msg) {
            addMessageProgressDialog.dismiss();

            if (msg.what == 1) {
                try {
                    String[] tmp = LogEntries.clone();
                    final int NewArrlength = tmp.length + 1;
                    LogEntries = new String[NewArrlength];

                    LogEntries[0] = "<strong>" + settings.getString("userName", "") + "</strong> wrote "
                            + Message + "\n<br/><strong>At:</strong> Just now";

                    for (int i = 1; i < NewArrlength; ++i) //
                    {
                        LogEntries[i] = tmp[(i - 1)];
                    }

                    TextView newLog = new TextView(getActivity());
                    newLog.setText(Html.fromHtml(LogEntries[0]));
                    newLog.setPadding(0, 6, 0, 6);

                    logList.addView(newLog);
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "AddMessageProgressHandler", e);
                    try {
                        Toast.makeText(getActivity(),
                                "The log message was successfully sent to Zenoss but an error occured when updating the UI",
                                Toast.LENGTH_LONG).show();
                    } catch (Exception e1) {
                        BugSenseHandler.sendExceptionMessage("ViewZenossEvent",
                                "AddMessageProgressHandler Toast", e1);
                    }
                }
            } else {
                try {
                    Toast.makeText(getActivity(), "An error was encountered adding your message to the log",
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "AddMessageProgressHandler", e);
                }
            }

        }
    };

    addLogMessageThread = new Thread() {
        public void run() {
            Boolean Success = false;

            try {
                if (API == null) {
                    if (settings.getBoolean(ZenossAPI.PREFERENCE_IS_ZAAS, false)) {
                        API = new ZenossAPIZaas();
                    } else {
                        API = new ZenossAPICore();
                    }

                    ZenossCredentials credentials = new ZenossCredentials(getActivity());
                    API.Login(credentials);
                }

                Success = API.AddEventLog(getArguments().getString("EventID"), Message);
            } catch (Exception e) {
                BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "AddLogMessageThread", e);
                addLogMessageHandler.sendEmptyMessage(0);
            }

            if (Success) {
                addLogMessageHandler.sendEmptyMessage(1);
            } else {
                addLogMessageHandler.sendEmptyMessage(0);
            }
        }
    };

    addLogMessageThread.start();
}

From source file:net.fred.feedex.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./* w  w w . j av a2  s . c o  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) {
        Dog.e("Error", e);
        return null;
    }
}

From source file:com.android.tv.dvr.ui.DvrUiHelper.java

@NonNull
public static CharSequence getStyledTitleWithEpisodeNumber(Context context, String title, String seasonNumber,
        String episodeNumber, int episodeNumberStyleResId) {
    if (TextUtils.isEmpty(title)) {
        return "";
    }//from   www  .  ja  va 2 s.  c  om
    SpannableStringBuilder builder;
    if (TextUtils.isEmpty(seasonNumber) || seasonNumber.equals("0")) {
        builder = TextUtils.isEmpty(episodeNumber) ? new SpannableStringBuilder(title)
                : new SpannableStringBuilder(Html.fromHtml(context.getString(
                        R.string.program_title_with_episode_number_no_season, title, episodeNumber)));
    } else {
        builder = new SpannableStringBuilder(Html.fromHtml(context
                .getString(R.string.program_title_with_episode_number, title, seasonNumber, episodeNumber)));
    }
    Object[] spans = builder.getSpans(0, builder.length(), Object.class);
    if (spans.length > 0) {
        if (episodeNumberStyleResId != 0) {
            builder.setSpan(new TextAppearanceSpan(context, episodeNumberStyleResId),
                    builder.getSpanStart(spans[0]), builder.getSpanEnd(spans[0]),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        builder.removeSpan(spans[0]);
    }
    return new SpannableString(builder);
}

From source file:com.pdftron.pdf.utils.Utils.java

public static void showAlertDialogWithLink(Context context, String message, String title) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);

    builder.setMessage(Html.fromHtml(message)).setCancelable(true).setPositiveButton(R.string.ok,
            new DialogInterface.OnClickListener() {

                @Override/*from   w w w .  j  av a 2s  . co m*/
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    if (title.length() > 0) {
        builder.setTitle(title);
    }
    final AlertDialog d = builder.create();
    d.show();

    // Make the textview clickable. Must be called after show()
    ((TextView) d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:com.hardcopy.retrowatch.contents.FeedParser.java

/*****************************************************
 *      Public methods/*  ww w.  j  a  v  a2  s .c  o m*/
 ******************************************************/

public ArrayList<FeedObject> parseResultString(CPObject CpObj, String strResult) {
    if (CpObj == null)
        return null;

    int type = CpObj.mId;
    ArrayList<FeedObject> feedList = new ArrayList<FeedObject>();

    Logs.d(TAG, "# Parsing string :: CP type = " + CpObj.mId + ", parsing type = " + CpObj.mParsingType);

    switch (CpObj.mParsingType) {
    case FeedObject.REQUEST_TYPE_DAUM_REALTIME_KEYWORDS: {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(strResult));

            Document doc = db.parse(is);
            Element element = doc.getDocumentElement();

            NodeList items = element.getElementsByTagName(PARSING_TAG_WORD); // <realtime/>[ <word/> {<rank/><keyword/><value/><type/><linkurl/>} ]

            for (int i = 0; i < items.getLength(); i++) {
                String link = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                int rankType = RANK_TYPE_NONE;
                int rankUpAndDown = 0;
                int commentCount = 0;

                Node item = items.item(i); //  ? Node? ??  .
                NodeList children = item.getChildNodes(); // ?? Node 

                for (int j = 0; j < children.getLength(); j++) {
                    Node child = children.item(j);
                    String nodeName = child.getNodeName();
                    if (nodeName.equalsIgnoreCase(PARSING_TAG_KEYWORD)) {
                        String temp = child.getFirstChild().getNodeValue();
                        if (temp != null)
                            keyword = new String(temp.getBytes());
                    } else if (nodeName.equalsIgnoreCase(PARSING_TAG_LINKURL)) {
                        String temp = child.getFirstChild().getNodeValue();
                        if (temp != null)
                            link = new String(temp.getBytes(), ENCODING_TYPE_UTF_8);
                    } else if (nodeName.equalsIgnoreCase(PARSING_TAG_TYPE)) {
                        String temp = child.getFirstChild().getNodeValue();
                        if (temp != null) {
                            String temp2 = new String(temp.getBytes(), ENCODING_TYPE_UTF_8); // <type> value : "new" or "++"
                            if (temp2.equalsIgnoreCase(PARSING_TAG_NEW))
                                rankType = RANK_TYPE_NEW;
                        }
                    } else if (nodeName.equalsIgnoreCase(PARSING_TAG_VALUE)) {
                        try {
                            String temp = child.getFirstChild().getNodeValue();
                            if (temp != null && temp.length() > 0) {
                                String temp2 = new String(temp.getBytes(), ENCODING_TYPE_UTF_8); // <value> : 
                                rankUpAndDown = Integer.parseInt(temp2) / RANK_MODIFIER_DAUM_REALTIME_KEYWORD; // TODO:
                                if (rankUpAndDown > 10)
                                    rankUpAndDown = 10;
                            }
                        } catch (Exception e) {
                        }
                    }
                } // End of for loop

                if (keyword != null && link != null) {
                    String idStr = keyword;
                    FeedObject feed = new FeedObject(type, idStr, link, keyword, null, null);
                    feed.mDownloadStatus = FeedObject.CONTENT_DOWNLOAD_STATUS_INIT;
                    feed.setRankInfo(rankType, rankUpAndDown, commentCount);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop

        } catch (Exception e) {
            Logs.d(TAG, e.getMessage() == null ? "Unknown error while parsing xml" : e.getMessage());
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_NAVER_REALTIME_KEYWORDS: {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(strResult));

            Document doc = db.parse(is);
            Element element = doc.getDocumentElement();

            NodeList temp = element.getElementsByTagName(PARSING_TAG_ITEM); // result -> item 
            NodeList items = temp.item(0).getChildNodes(); // List contains R1, R2...

            //? ? ??? Node ?
            for (int i = 0; i < items.getLength(); i++) {
                String link = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                int rankType = RANK_TYPE_NONE;
                int rankUpAndDown = 0;
                int commentCount = 0;

                Node item = items.item(i); // <Rn> :    n-th R tag
                NodeList children = item.getChildNodes(); // <k> <s> <v>

                for (int j = 0; j < children.getLength(); j++) {
                    Node child = children.item(j);
                    String nodeName = child.getNodeName();
                    if (nodeName.equalsIgnoreCase(PARSING_TAG_K)) {
                        String tempStr = child.getFirstChild().getNodeValue();
                        if (tempStr != null)
                            keyword = new String(tempStr.getBytes());
                    } else if (nodeName.equalsIgnoreCase(PARSING_TAG_V)) {
                        String tempStr = child.getFirstChild().getNodeValue();
                        rankUpAndDown = Integer.parseInt(tempStr) / RANK_MODIFIER_NAVER_REALTIME_KEYWORD; // TODO: 
                        if (rankUpAndDown > 10)
                            rankUpAndDown = 10;
                    }
                }

                if (keyword != null) {
                    String idStr = keyword;
                    FeedObject feed = new FeedObject(type, idStr, null, keyword, null, null);
                    feed.mDownloadStatus = FeedObject.CONTENT_DOWNLOAD_STATUS_INIT;
                    feed.setRankInfo(rankType, rankUpAndDown, commentCount);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop

        } catch (Exception e) {
            Logs.d(TAG, e.getMessage() == null ? "Unknown error while parsing xml" : e.getMessage());
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_DAUM_SOCIAL_PICK: {
        try {
            JSONObject jsonRoot = new JSONObject(strResult); // root { 
            JSONObject jsonObjSocialPick = jsonRoot.getJSONObject(PARSING_TAG_SOCIALPICK); // { socialpick :
            JSONArray jsonArray = jsonObjSocialPick.getJSONArray(PARSING_TAG_ITEM); // {item: [

            for (int i = 0; i < jsonArray.length(); i++) {
                String link = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                int rankType = RANK_TYPE_NONE;
                int rankUpAndDown = 0;
                int commentCount = 0;

                JSONObject obj = jsonArray.getJSONObject(i); // {rank:1, link:"xx", keyword:"xx", content:"xx", count:30000, quotation_cnt:1345, comment_cnt:13816, rank_diff:3, category:"c" }
                link = obj.getString(PARSING_TAG_LINK);
                keyword = obj.getString(PARSING_TAG_KEYWORD);
                content = obj.getString(PARSING_TAG_CONTENT);
                commentCount = obj.getInt(PARSING_TAG_COMMENT_CNT) / RANK_MODIFIER_DAUM_SOCIALPICK;
                commentCount = commentCount * 2; // To encourage rank priority
                if (commentCount > 10)
                    commentCount = 10;

                if (link != null && keyword != null && content != null) {
                    String idStr = keyword;
                    FeedObject feed = new FeedObject(type, idStr, link, keyword, content, null);
                    feed.mDownloadStatus = FeedObject.CONTENT_DOWNLOAD_STATUS_INIT;
                    feed.setRankInfo(rankType, rankUpAndDown, commentCount);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop
        } catch (JSONException e) {
            Logs.d(TAG, "##### JSON Parsing stopped with error :");
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_TWITTER_HOTTEST:
    case FeedObject.REQUEST_TYPE_TWITTER_REALTIME:
    case FeedObject.REQUEST_TYPE_TWITTER_TODAY:
    case FeedObject.REQUEST_TYPE_TWITTER_IMAGE: {
        String link = null;
        String keyword = null;
        String content = null;
        String thumbnail = null;

        try {
            JSONObject jsonRoot = new JSONObject(strResult); // root { 
            JSONArray jsonObjList = jsonRoot.getJSONArray(PARSING_TAG_RANKED_TWIT_LIST); // { rankedTwitList : [

            for (int i = 0; i < jsonObjList.length(); i++) {
                JSONObject obj = jsonObjList.getJSONObject(i); // id, owner, body, rtRank, rtCount, registDate, links:{}, rtTwitCount, twitId

                //---------- make content
                String idStr = obj.getString(PARSING_TAG_ID);
                String name = obj.getString(PARSING_TAG_OWNER);
                content = obj.getString(PARSING_TAG_BODY);

                JSONObject linkObj = obj.getJSONObject(PARSING_TAG_LINKS);
                if (linkObj != null) {
                    try { // If there is no <image> object, skip below routine
                        JSONArray imageObjList = linkObj.getJSONArray(PARSING_TAG_IMAGE);
                        if (imageObjList != null) {
                            // Multiple images can be found, but we'll take only first one.
                            JSONObject objImg = imageObjList.getJSONObject(0);
                            thumbnail = objImg.getString(PARSING_TAG_THUMBNAIL_URL);
                            link = objImg.getString(PARSING_TAG_URL);
                        }
                    } catch (Exception e) {
                    }
                }

                if (idStr != null && content != null) {
                    FeedObject feed = new FeedObject(type, idStr, link, keyword, content, thumbnail);
                    if (name != null)
                        feed.setName(name);
                    else
                        Log.d(TAG, "+++ Parsing :: id is null");

                    feed.mDownloadStatus = FeedObject.CONTENT_DOWNLOAD_STATUS_INIT;
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop
        } catch (JSONException e) {
            Logs.d(TAG, "##### JSON Parsing stopped with error :");
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_NAVER_RELATED_KEYWORDS: {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(strResult));

            // Document Element  w3c dom? ? ? .
            Document doc = db.parse(is);
            Element element = doc.getDocumentElement();

            NodeList temp = element.getElementsByTagName(PARSING_TAG_ITEM); // result -> item 

            //? ? ??? Node ?
            for (int i = 0; i < temp.getLength(); i++) {
                String keyword = null;
                Node item = temp.item(i);
                String tempStr = item.getFirstChild().getNodeValue();
                if (tempStr != null && tempStr.length() > 0)
                    keyword = new String(tempStr.getBytes());

                if (keyword != null) {
                    FeedObject feed = new FeedObject(type, keyword, null, keyword, null, null);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop

        } catch (Exception e) {
            Logs.d(TAG, e.getMessage() == null ? "Unknown error while parsing xml" : e.getMessage());
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_9GAG_HOT:
    case FeedObject.REQUEST_TYPE_9GAG_TREND: {
        try {
            JSONObject jsonRoot = new JSONObject(strResult); // root { 
            JSONArray jsonArray = jsonRoot.getJSONArray(PARSING_TAG_DATA); // {data: [

            long current = System.currentTimeMillis();
            for (int i = 0; i < jsonArray.length(); i++) {
                String id = null;
                String link = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                String fullSizeImage = null;
                // {id:xx, from:{name:xx}, caption:xx, images:{small:xx, normal:xx, large:xx}, link:xx, action:{like:xx, dislike:xx, unlike:xx}, vote:{count:xx}
                JSONObject obj = jsonArray.getJSONObject(i);
                id = obj.getString(PARSING_TAG_ID);
                link = obj.getString(PARSING_TAG_LINK);
                keyword = obj.getString(PARSING_TAG_CAPTION);
                JSONObject objImage = obj.getJSONObject(PARSING_TAG_IMAGES);
                thumbnail = objImage.getString(PARSING_TAG_SMALL);
                fullSizeImage = objImage.getString(PARSING_TAG_NORMAL);

                if (id != null && link != null && keyword != null && thumbnail != null) {
                    FeedObject feed = new FeedObject(type, id, link, keyword, null, thumbnail);
                    feed.setFullSizeImageURL(fullSizeImage);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop
        } catch (JSONException e) {
            Logs.d(TAG, "##### JSON Parsing stopped with error :");
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_NOTICE: {
        try {
            JSONObject jsonRoot = new JSONObject(strResult); // root { 
            JSONArray jsonArray = jsonRoot.getJSONArray(PARSING_TAG_NOTICE); // {notice: [

            long current = System.currentTimeMillis();
            for (int i = 0; i < jsonArray.length(); i++) {
                int version = 0;
                String id = null;
                String link = null;
                String name = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                String fullSizeImage = null;
                // {title:XXX, LINK:XXX, description:XXX, author:XXX, appversion:XXX, pubDate:XXX
                JSONObject obj = jsonArray.getJSONObject(i);

                keyword = obj.getString(PARSING_TAG_TITLE);
                link = obj.getString(PARSING_TAG_LINK);
                content = obj.getString(PARSING_TAG_DESCRIPTION);
                name = obj.getString(PARSING_TAG_AUTHOR);
                version = obj.getInt(PARSING_TAG_APP_VERSION);
                id = obj.getString(PARSING_TAG_PUBDATE);

                if (id != null && link != null && keyword != null) {
                    FeedObject feed = new FeedObject(type, id, link, keyword, content, null);
                    feed.setName(name);
                    feed.setDate(id);
                    feed.setVersion(version);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop
        } catch (JSONException e) {
            Logs.d(TAG, "##### JSON Parsing stopped with error :");
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_RSS_DEFAULT:
    case FeedObject.REQUEST_TYPE_RSS_FEED43: {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(strResult));

            // Document Element  w3c dom? ? ? .
            Document doc = db.parse(is);
            Element element = doc.getDocumentElement();

            // Extract logo image
            try {
                NodeList logoImage = element.getElementsByTagName(PARSING_TAG_IMAGE);
                if (logoImage != null && logoImage.getLength() > 0) {
                    Node logoitem = logoImage.item(0);
                    NodeList logochildren = logoitem.getChildNodes();
                    for (int j = 0; j < logochildren.getLength(); j++) {
                        Node logochild = logochildren.item(j);
                        String logoName = logochild.getNodeName();
                        if (logoName.equalsIgnoreCase(PARSING_TAG_URL)) {
                            String tempStr = logochild.getFirstChild().getNodeValue();
                            if (tempStr != null && tempStr.length() > 0)
                                CpObj.mLogoImage = tempStr;
                        }
                    }
                }
            } catch (Exception e) {
            }

            NodeList temp = element.getElementsByTagName(PARSING_TAG_ITEM); // channel -> item 

            long current = System.currentTimeMillis();
            for (int i = 0; i < temp.getLength(); i++) {
                int version = 0;
                String guid = null;
                String name = null;
                String date = null;
                String link = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                Node item = temp.item(i); // <item> :    n-th item tag
                NodeList children = item.getChildNodes(); // <title> <author> <link> <description> <pubDate>

                for (int j = 0; j < children.getLength(); j++) {
                    try { // If error occurs in this block, skip current item parsing and go next
                        Node child = children.item(j);
                        String nodeName = child.getNodeName();
                        if (nodeName.equalsIgnoreCase(PARSING_TAG_LINK)) {
                            String tempStr = child.getFirstChild().getNodeValue();
                            if (tempStr != null)
                                link = new String(tempStr.getBytes());
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_TITLE)) {
                            String tempStr = child.getFirstChild().getNodeValue();
                            if (tempStr != null) {
                                keyword = new String(tempStr.getBytes());
                            }
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_DESCRIPTION)) {
                            String tempStr = child.getFirstChild().getNodeValue();
                            if (tempStr != null) {
                                String[] strArray = tempStr.split(STRING_RSS_SPLIT_TAG);
                                if (strArray[0] != null && strArray[0].length() > 0) {
                                    strArray[0] = Html.fromHtml(strArray[0]).toString();
                                    strArray[0] = strArray[0].replaceAll(REG_EXP_REMOVE_TAG, "");
                                    strArray[0] = strArray[0].replaceAll(REG_EXP_REMOVE_NEWLINE, "");
                                    content = strArray[0];
                                }
                                if (strArray.length > 1 && strArray[1] != null && strArray[1].length() > 0) {
                                    thumbnail = strArray[1];
                                }
                            }
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_AUTHOR)) {
                            if (child != null && child.getFirstChild() != null) {
                                String tempStr = child.getFirstChild().getNodeValue();
                                if (tempStr != null)
                                    name = new String(tempStr.getBytes());
                            }
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_PUBDATE)) {
                            if (child != null && child.getFirstChild() != null) {
                                String tempStr = child.getFirstChild().getNodeValue();
                                if (tempStr != null)
                                    date = new String(tempStr.getBytes());
                            }
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_GUID)) {
                            if (child != null && child.getFirstChild() != null) {
                                String tempStr = child.getFirstChild().getNodeValue();
                                if (tempStr != null)
                                    guid = new String(tempStr.getBytes());
                            }
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_APP_VERSION)) {
                            if (child != null && child.getFirstChild() != null) {
                                String tempStr = child.getFirstChild().getNodeValue();
                                if (tempStr != null && tempStr.length() > 0)
                                    version = Integer.parseInt(tempStr);
                            }
                        } else if (nodeName.contains(PARSING_TAG_THUMBNAIL)) {
                            try {
                                if (child != null && child.hasAttributes()) {
                                    NamedNodeMap attrs = child.getAttributes();
                                    for (int k = 0; k < attrs.getLength(); k++) {
                                        Node attr = attrs.item(k);
                                        if (attr.getNodeName().equalsIgnoreCase(PARSING_TAG_URL)) {
                                            thumbnail = attr.getNodeValue();
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                thumbnail = null;
                            }

                        } else if (nodeName.contains(PARSING_TAG_ENCLOSURE)) {
                            try {
                                if (child != null && child.hasAttributes()) {
                                    NamedNodeMap attrs = child.getAttributes();
                                    for (int k = 0; k < attrs.getLength(); k++) {
                                        Node attr = attrs.item(k);
                                        if (attr.getNodeName().equalsIgnoreCase(PARSING_TAG_URL)) {
                                            thumbnail = attr.getNodeValue();
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                thumbnail = null;
                            }

                        }

                    } catch (Exception e) {
                        Logs.d(TAG,
                                e.getMessage() == null ? "Unknown error while parsing xml" : e.getMessage());
                        e.printStackTrace();
                    }

                } // End of for loop.... parsing each item

                if (link != null && keyword != null && content != null) {
                    StringBuilder sb = new StringBuilder();
                    if (guid != null) {
                        sb.append("rss_").append(removeSpecialChars(guid));
                    } else if (date != null) {
                        sb.append("rss_").append(date.replace(",", "").replace(":", "").trim());
                    } else {
                        String temp1 = null;
                        if (keyword.length() > 50)
                            temp1 = keyword.substring(0, 50);
                        else
                            temp1 = keyword;
                        temp1 = URLEncoder.encode(temp1, ENCODING_TYPE_UTF_8).replace("+", "%20")
                                .replace("*", "%2A").replace("%7E", "~");
                        if (temp1.length() > PARSER_ID_SUBSTRING_MAX)
                            temp1 = temp1.substring(0, PARSER_ID_SUBSTRING_MAX - 1);
                        temp1 = temp1.trim();
                        sb.append("rss_").append(temp1);
                    }

                    FeedObject feed = new FeedObject(type, sb.toString(), link, keyword, content, thumbnail);
                    feed.mDownloadStatus = FeedObject.CONTENT_DOWNLOAD_STATUS_INIT;
                    feed.setDate(date);
                    feed.setName(name);
                    if (CpObj.mParsingType == FeedObject.REQUEST_TYPE_NOTICE && version > 0)
                        feed.setVersion(version);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop

        } catch (Exception e) {
            Logs.d(TAG, e.getMessage() == null ? "Unknown error while parsing xml" : e.getMessage());
            e.printStackTrace();
            feedList = null;
        }
        break;
    } // End of default block

    } // End of switch(type)

    return feedList;

}

From source file:cn.edu.nju.dapenti.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.//w w w. j a va  2 s  .c om
 */
@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(NetworkUtils.getConnectionInputStream(conn)));

            // Parse results
            final ArrayList<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
            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<String, String>();
                        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) {
        return null;
    }
}

From source file:com.klinker.android.twitter.utils.NotificationUtils.java

public static void makeFavsNotification(ArrayList<String[]> tweets, Context context, boolean toDrawer) {
    String shortText;/* ww  w  .j  ava  2 s.c o m*/
    String longText;
    String title;
    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;

    Intent resultIntent;

    if (toDrawer) {
        resultIntent = new Intent(context, RedirectToDrawer.class);
    } else {
        resultIntent = new Intent(context, NotiTweetPager.class);
    }

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);

    NotificationCompat.InboxStyle inbox = null;

    if (tweets.size() == 1) {
        title = tweets.get(0)[0];
        shortText = tweets.get(0)[1];
        longText = shortText;

        largeIcon = getImage(context, tweets.get(0)[2]);
    } else {
        inbox = new NotificationCompat.InboxStyle();

        title = context.getResources().getString(R.string.favorite_users);
        shortText = tweets.size() + " " + context.getResources().getString(R.string.fav_user_tweets);
        longText = "";

        try {
            inbox.setBigContentTitle(shortText);
        } catch (Exception e) {

        }

        if (tweets.size() <= 5) {
            for (String[] s : tweets) {
                inbox.addLine(Html.fromHtml("<b>" + s[0] + ":</b> " + s[1]));
            }
        } else {
            for (int i = 0; i < 5; i++) {
                inbox.addLine(Html.fromHtml("<b>" + tweets.get(i)[0] + ":</b> " + tweets.get(i)[1]));
            }

            inbox.setSummaryText("+" + (tweets.size() - 5) + " " + context.getString(R.string.tweets));
        }

        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);
    }

    NotificationCompat.Builder mBuilder;

    AppSettings settings = AppSettings.getInstance(context);

    if (shortText.contains("@" + settings.myScreenName)) {
        // return because there is a mention notification for this already
        return;
    }

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setContentIntent(resultPendingIntent).setAutoCancel(true)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText)));
    } else {
        mBuilder.setStyle(inbox);
    }
    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(2, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (context
                .getSharedPreferences("com.klinker.android.twitter_world_preferences",
                        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE)
                .getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, shortText);
        }

        // Light Flow notification
        sendToLightFlow(context, title, shortText);
    }
}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java

private static String httpPush(ArrayList<NameValuePair> nameValuePairs, String action) throws Exception {
    HttpPost httppost = new HttpPost(FLOWZR_API_URL + nsString + "/" + action + "/");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
    HttpResponse response;//ww  w. j  av a2s . co  m
    String strResponse;
    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();
    entity.consumeContent();
    if (code != 200) {
        throw new Exception(Html.fromHtml(strResponse).toString());
    }
    return strResponse;
}

From source file:com.carlrice.reader.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./* w w  w . jav  a  2s.c  o  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) {
        return null;
    }
}