Example usage for org.jsoup.nodes Element select

List of usage examples for org.jsoup.nodes Element select

Introduction

In this page you can find the example usage for org.jsoup.nodes Element select.

Prototype

public Elements select(String cssQuery) 

Source Link

Document

Find elements that match the Selector CSS query, with this element as the starting context.

Usage

From source file:com.lloydtorres.stately.telegrams.TelegramsFragment.java

/**
 * Actually parse through the response sent by NS and build telegram objects.
 * @param d Document containing parsed response.
 * @param direction Direction the user is loading telegrams
 * @param firstRun if first time running this process
 *//*from w  w w . ja va 2s .c  om*/
private void processRawTelegrams(Document d, int direction, boolean firstRun) {
    Element telegramsContainer = d.select("div#tglist").first();
    Element foldersContainer = d.select("select#tgfolder").first();

    if (telegramsContainer == null || foldersContainer == null) {
        // safety check
        mSwipeRefreshLayout.setRefreshing(false);
        SparkleHelper.makeSnackbar(mView, getString(R.string.login_error_parsing));
        return;
    }

    // Build list of folders
    folders = new ArrayList<TelegramFolder>();
    Elements rawFolders = foldersContainer.select("option[value]");
    for (Element rf : rawFolders) {
        TelegramFolder telFolder = new TelegramFolder();
        String rfValue = rf.attr("value");
        if (!rfValue.equals("_new")) {
            String rfName = rf.text();
            telFolder.name = rfName;
            telFolder.value = rfValue;
            folders.add(telFolder);
        }
    }

    // Build telegram objects from raw telegrams
    ArrayList<Telegram> scannedTelegrams = MuffinsHelper.processRawTelegrams(telegramsContainer,
            PinkaHelper.getActiveUser(getContext()).nationId);
    switch (direction) {
    case SCAN_FORWARD:
        processTelegramsForward(scannedTelegrams, firstRun);
        break;
    default:
        processTelegramsBackward(scannedTelegrams);
        break;
    }

    mSwipeRefreshLayout.setRefreshing(false);
}

From source file:com.near.chimerarevo.fragments.PostFragment.java

private void parseParagraphs(Elements ps) {
    for (Element p : ps) {
        if (!p.html().startsWith("&") && !p.html().startsWith("<iframe") && !p.html().startsWith("<!")
                && !p.html().contains("<h") && !p.html().contains("<ol") && !p.html().contains("<ul")
                && !p.html().contains("<pre") && !p.html().contains("<tr")) {
            parseNormalImages(p.select("img"));
            p.select("img").remove();

            Elements lnks = p.getElementsByTag("a");
            for (Element lnk : lnks) {
                if (lnk.attr("href").startsWith("#"))
                    lnk.removeAttr("href");
            }//  ww  w  .j a  v  a  2  s. co m

            String txt = p.html().replace("<br />", "").replace("\n", "").trim();
            if (txt.length() > 0)
                addText(txt, true, Typeface.DEFAULT);
        }
    }
}

From source file:com.njlabs.amrita.aid.news.NewsActivity.java

private void getNews(final Boolean refresh) {
    swipeRefreshLayout.setRefreshing(true);

    Request request = new Request.Builder().url("https://www.amrita.edu/campus/Coimbatore/news").build();

    client.newCall(request).enqueue(new Callback() {
        @Override//from   w  w  w. jav  a 2  s  .com
        public void onFailure(Call call, IOException e) {
            ((Activity) baseContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(false);
                    Snackbar.make(parentView, "Can't establish a reliable connection to the server.",
                            Snackbar.LENGTH_SHORT).setAction("Retry", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    getNews(refresh);
                                }
                            }).show();
                }
            });
        }

        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            final String responseString = response.body().string();
            ((Activity) baseContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (refresh) {
                        (new Thread(new Runnable() {
                            @Override
                            public void run() {
                                NewsModel.deleteAll();
                            }
                        })).start();
                    }

                    final List<NewsModel> newsArticles = new ArrayList<>();

                    Document doc = Jsoup.parse(responseString);
                    Elements articles = doc.select("article");
                    for (Element article : articles) {
                        Element header = article.select(".flexslider").first();
                        Element content = article.select(".group-blog-content").first();
                        Element footer = article.select(".group-blog-footer").first();
                        String imageUrl = header.select("ul > li > img").first().attr("src");
                        String title = content.select(".field-name-title > div > div > h2").first().text();
                        String url = "https://www.amrita.edu"
                                + footer.select(".field-name-node-link > div > div > a").first().attr("href");
                        newsArticles.add(new NewsModel(imageUrl, title, url));
                    }

                    (new Thread(new Runnable() {
                        @Override
                        public void run() {
                            ActiveAndroid.beginTransaction();
                            try {
                                for (NewsModel newsModel : newsArticles) {
                                    newsModel.save();
                                }
                                ActiveAndroid.setTransactionSuccessful();
                            } finally {
                                ActiveAndroid.endTransaction();
                            }
                        }
                    })).start();

                    recyclerView.setAdapter(new SlideInLeftAnimationAdapter(
                            new AlphaInAnimationAdapter(new NewsAdapter(newsArticles))));
                    swipeRefreshLayout.setRefreshing(false);
                }
            });
        }
    });
}

From source file:com.njlabs.amrita.aid.news.NewsUpdateService.java

private void getNews(final Boolean refresh, final List<NewsModel> oldArticles) {

    List<NewsModel> currentArticles;

    OkHttpClient client = new OkHttpClient.Builder().followRedirects(true).followSslRedirects(true).build();

    Request request = new Request.Builder().url("https://www.amrita.edu/campus/Coimbatore/news").build();

    try {//from   w ww  . j a va  2 s . c o  m
        Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
            String responseString = response.body().string();
            currentArticles = new ArrayList<>();
            if (refresh) {
                NewsModel.deleteAll();
            }

            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.setBigContentTitle("News Articles");

            Document doc = Jsoup.parse(responseString);
            Elements articles = doc.select("article");
            for (Element article : articles) {
                Element header = article.select(".flexslider").first();
                Element content = article.select(".group-blog-content").first();
                Element footer = article.select(".group-blog-footer").first();
                String imageUrl = header.select("ul > li > img").first().attr("src");
                String title = content.select(".field-name-title > div > div > h2").first().text();
                String url = "https://www.amrita.edu"
                        + footer.select(".field-name-node-link > div > div > a").first().attr("href");

                inboxStyle.addLine(title);
                currentArticles.add(new NewsModel(imageUrl, title, url));
            }

            ActiveAndroid.beginTransaction();
            try {
                for (NewsModel newsModel : currentArticles) {
                    newsModel.save();
                }
                ActiveAndroid.setTransactionSuccessful();
            } finally {
                ActiveAndroid.endTransaction();
            }

            Intent resultIntent = new Intent(mContext, NewsActivity.class);

            TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
            stackBuilder.addParentStack(NewsActivity.class);

            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            if (refresh && !currentArticles.get(0).getTitle().equals(oldArticles.get(0).getTitle())) {
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(NewsUpdateService.this)
                        .setSmallIcon(R.drawable.ic_stat_news)
                        .setLargeIcon(
                                BitmapFactory.decodeResource(mContext.getResources(), R.drawable.app_icon))
                        .setContentTitle("Latest News").setDefaults(Notification.DEFAULT_SOUND)
                        .setContentIntent(resultPendingIntent).setAutoCancel(true)
                        .setContentText(currentArticles.get(0).getTitle());

                if (allowNotification) {
                    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(0, mBuilder.build());
                }

            }
            if (!refresh) {
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);

                mBuilder.setContentTitle("New Posts");
                mBuilder.setContentText("Latest News Updated");
                mBuilder.setTicker("Latest News Updated");
                mBuilder.setSmallIcon(R.drawable.ic_stat_news);
                mBuilder.setLargeIcon(
                        BitmapFactory.decodeResource(mContext.getResources(), R.drawable.app_icon));
                mBuilder.setContentIntent(resultPendingIntent);
                mBuilder.setNumber(currentArticles.size());
                mBuilder.setAutoCancel(true);
                mBuilder.setStyle(inboxStyle);

                if (allowNotification) {
                    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(0, mBuilder.build());
                }

            }
        }
    } catch (IOException ignored) {
        FirebaseCrash.report(ignored);
    }

}

From source file:com.normalexception.app.rx8club.fragment.category.CategoryFragment.java

/**
 * Grab contents from the forum that the user clicked on
 * @param doc      The document parsed from the link
 * @param id      The id number of the link
 * @param isMarket    True if the link is from a marketplace category
 *///  www.  jav  a 2 s  . c o m
public void getCategoryContents(Document doc, String id, boolean isMarket) {

    // Update pagination
    try {
        Elements pageNumbers = doc.select("div[class=pagenav]");
        Elements pageLinks = pageNumbers.first().select("td[class^=vbmenu_control]");
        thisPage = pageLinks.text().split(" ")[1];
        finalPage = pageLinks.text().split(" ")[3];
    } catch (Exception e) {
    }

    // Make sure id contains only numbers
    if (!isNewTopicActivity)
        id = Utils.parseInts(id);

    // Grab each thread
    Elements threadListing = doc.select("table[id=threadslist] > tbody > tr");

    for (Element thread : threadListing) {
        try {
            boolean isSticky = false, isLocked = false, hasAttachment = false, isAnnounce = false,
                    isPoll = false;
            String formattedTitle = "", postCount = "0", views = "0", forum = "", threadUser = "",
                    lastUser = "", threadLink = "", lastPage = "", totalPosts = "0", threadDate = "";

            Elements announcementContainer = thread.select("td[colspan=5]");
            Elements threadTitleContainer = thread.select("a[id^=thread_title]");

            // We could have two different types of threads.  Announcement threads are 
            // completely different than the other types of threads (sticky, locked, etc)
            // so we need to play some games here
            if (announcementContainer != null && !announcementContainer.isEmpty()) {
                Log.d(TAG, "Announcement Thread Found");

                Elements annThread = announcementContainer.select("div > a");
                Elements annUser = announcementContainer.select("div > span[class=smallfont]");
                formattedTitle = "Announcement: " + annThread.first().text();
                threadUser = annUser.last().text();
                threadLink = annThread.attr("href");
                isAnnounce = true;
            } else if (threadTitleContainer != null && !threadTitleContainer.isEmpty()) {
                Element threadLinkEl = thread.select("a[id^=thread_title]").first();
                Element repliesText = thread.select("td[title^=Replies]").first();
                Element threaduser = thread.select("td[id^=td_threadtitle_] div.smallfont").first();
                Element threadicon = thread.select("img[id^=thread_statusicon_]").first();
                Element threadDiv = thread.select("td[id^=td_threadtitle_] > div").first();
                Element threadDateFull = thread.select("td[title^=Replies:] > div").first();

                try {
                    isSticky = threadDiv.text().contains("Sticky:");
                } catch (Exception e) {
                }

                try {
                    isPoll = threadDiv.text().contains("Poll:");
                } catch (Exception e) {
                }

                try {
                    String icSt = threadicon.attr("src");
                    isLocked = (icSt.contains("lock") && icSt.endsWith(".gif"));
                } catch (Exception e) {
                }

                String preString = "";
                try {
                    preString = threadDiv.select("span > b").text();
                } catch (Exception e) {
                }

                try {
                    hasAttachment = !threadDiv.select("a[onclick^=attachments]").isEmpty();
                } catch (Exception e) {
                }

                // Find the last page if it exists
                try {
                    lastPage = threadDiv.select("span").last().select("a").last().attr("href");
                } catch (Exception e) {
                }

                threadDate = threadDateFull.text();
                int findAMPM = threadDate.indexOf("M") + 1;
                threadDate = threadDate.substring(0, findAMPM);

                String totalPostsInThreadTitle = threadicon.attr("alt");

                if (totalPostsInThreadTitle != null && totalPostsInThreadTitle.length() > 0)
                    totalPosts = totalPostsInThreadTitle.split(" ")[2];

                // Remove page from the link
                String realLink = Utils.removePageFromLink(link);

                if (threadLinkEl.attr("href").contains(realLink) || (isNewTopicActivity || isMarket)) {

                    String txt = repliesText.getElementsByClass("alt2").attr("title");
                    String splitter[] = txt.split(" ", 4);

                    postCount = splitter[1].substring(0, splitter[1].length() - 1);
                    views = splitter[3];

                    try {
                        if (this.isNewTopicActivity)
                            forum = thread.select("td[class=alt1]").last().text();
                    } catch (Exception e) {
                    }

                    formattedTitle = String.format("%s%s%s", isSticky ? "Sticky: " : isPoll ? "Poll: " : "",
                            preString.length() == 0 ? "" : preString + " ", threadLinkEl.text());
                }

                threadUser = threaduser.text();
                lastUser = repliesText.select("a[href*=members]").text();
                threadLink = threadLinkEl.attr("href");
            }

            // Add our thread to our list as long as the thread
            // contains a title
            if (!formattedTitle.equals("")) {
                ThreadModel tv = new ThreadModel();
                tv.setTitle(formattedTitle);
                tv.setStartUser(threadUser);
                tv.setLastUser(lastUser);
                tv.setLink(threadLink);
                tv.setLastLink(lastPage);
                tv.setPostCount(postCount);
                tv.setMyPosts(totalPosts);
                tv.setViewCount(views);
                tv.setLocked(isLocked);
                tv.setSticky(isSticky);
                tv.setAnnouncement(isAnnounce);
                tv.setPoll(isPoll);
                tv.setHasAttachment(hasAttachment);
                tv.setForum(forum);
                tv.setLastPostTime(threadDate);
                threadlist.add(tv);
            } else if (thread.text()
                    .contains(MainApplication.getAppContext().getString(R.string.constantNoUpdate))) {
                Log.d(TAG, String.format("Found End of New Threads after %d threads...", threadlist.size()));
                if (threadlist.size() > 0) {
                    ThreadModel ltv = threadlist.get(threadlist.size() - 1);
                    Log.d(TAG, String.format("Last New Thread '%s'", ltv.getTitle()));
                }

                if (!PreferenceHelper.hideOldPosts(MainApplication.getAppContext()))
                    threadlist.add(new ThreadModel(true));
                else {
                    Log.d(TAG, "User Chose To Hide Old Threads");
                    break;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error Parsing That Thread...", e);
            Log.d(TAG, "Thread may have moved");
        }
    }
}

From source file:com.normalexception.app.rx8club.fragment.HomeFragment.java

/**
 * Get the forum contents as a Map that links the category names
 * to a list of the forums within each category
 * @param root   The full forum document
 * @return      A map of the categories to the forums
 *//*from ww  w.ja  va 2 s .  c o  m*/
private void getCategories(Document root) {
    // Grab each category
    Elements categories = root.select("td[class=tcat][colspan=5]");
    Log.d(TAG, "Category Size: " + categories.size());

    // Now grab each section within a category
    Elements categorySections = root.select("tbody[id^=collapseobj_forumbit_]");

    // These should match in size
    if (categories.size() != categorySections.size()) {
        Log.w(TAG, String.format("Size of Categories (%d) doesn't match Category Sections (%d)",
                categories.size(), categorySections.size()));
        return;
    }

    // Iterate over each category
    int catIndex = 0;
    for (Element category : categorySections) {

        CategoryModel cv = new CategoryModel();
        cv.setTitle(categories.get(catIndex++).text());
        mainList.add(cv);

        Elements forums = category.select("tr[align=center]");
        for (Element forum : forums) {
            cv = new CategoryModel();
            List<SubCategoryModel> scvList = cv.getSubCategories();

            // Each forum object should have 5 columns
            Elements columns = forum.select("tr[align=center] > td");
            try {
                if (columns.size() != 5)
                    continue;

                String forum_name = columns.get(HomeFragment.FORUM_NAME).select("strong").text();
                String forum_href = columns.get(HomeFragment.FORUM_NAME).select("a").attr("href");
                String forum_desc = "";
                try {
                    forum_desc = columns.get(HomeFragment.FORUM_NAME).select("div[class=smallfont]").first()
                            .text();
                } catch (NullPointerException npe) {
                    /* Some might not have a desc */ }
                String threads = columns.get(HomeFragment.THREADS_CNT).text();
                String posts = columns.get(HomeFragment.POSTS_CNT).text();

                // Lets grab each subcategory
                Elements subCats = columns.select("tbody a");
                for (Element subCat : subCats) {
                    SubCategoryModel scv = new SubCategoryModel();
                    scv.setLink(subCat.attr("href"));
                    scv.setTitle(subCat.text().toString());
                    scvList.add(scv);
                }

                cv.setTitle(forum_name);
                cv.setThreadCount(threads);
                cv.setPostCount(posts);
                cv.setLink(forum_href);
                cv.setDescription(forum_desc);
                cv.setSubCategories(scvList);
                mainList.add(cv);
            } catch (Exception e) {
                Log.e(TAG, "Error Parsing Forum", e);
            }
        }
    }

    return;
}

From source file:com.normalexception.app.rx8club.fragment.pm.PrivateMessageInboxFragment.java

/**
 * Construct view by grabbing all private messages.  This is only done
 * if the view is called for the first time.  If there was a savedinstance
 * of the view then this is not called//w  ww .j a va  2s .  c o  m
 */
private void constructView() {
    this.showOutbound = getArguments().getBoolean(showOutboundExtra, false);

    AsyncTask<Void, String, Void> updaterTask = new AsyncTask<Void, String, Void>() {
        @Override
        protected void onPreExecute() {

            loadingDialog = ProgressDialog.show(getActivity(), getString(R.string.loading),
                    getString(R.string.pleaseWait), true);
        }

        @Override
        protected Void doInBackground(Void... params) {
            Document doc = VBForumFactory.getInstance().get(getActivity(),
                    showOutbound ? WebUrls.pmSentUrl : WebUrls.pmInboxUrl);

            if (doc != null) {
                token = HtmlFormUtils.getInputElementValueByName(doc, "securitytoken");
                String current_month = getMonthForInt(0);
                Elements collapse = doc
                        .select(showOutbound ? "tbody[id^=collapseobj_pmf-1]" : "tbody[id^=collapseobj_pmf0]");

                publishProgress(getString(R.string.asyncDialogGrabPMs));
                for (Element coll : collapse) {
                    Elements trs = coll.select("tr");
                    for (Element tr : trs) {
                        Elements alt1s = tr.getElementsByClass("alt1Active");
                        for (Element alt1 : alt1s) {

                            Elements divs = alt1.select("div");

                            // First grab our link
                            Elements linkElement = divs.get(0).select("a[rel=nofollow]");
                            String pmLink = linkElement.attr("href");

                            // There should be two divs here with text in it
                            // the first is 'MM-DD-YYYY Subject'
                            String dateSubject = divs.get(0).text();
                            String[] dateSubjectSplit = dateSubject.split(" ", 2);

                            // The second is HH:MM AMPM User
                            String timeTimeUser = divs.get(1).text();
                            String[] timeTimeUserSplit = timeTimeUser.split(" ", 3);

                            // Create new pm
                            PMModel pm = new PMModel();
                            pm.setDate(dateSubjectSplit[0]);

                            // Check the month before we go further
                            String this_month = getMonthForInt(Integer.parseInt(pm.getDate().split("-")[0]));
                            if (!current_month.equals(this_month)) {
                                current_month = this_month;
                                PMModel pm_m = new PMModel();
                                pm_m.setTitle(String.format("%s - %s", this_month,
                                        showOutbound ? getResources().getString(R.string.inboxSent)
                                                : getResources().getString(R.string.inboxInbox)));
                                pmlist.add(pm_m);
                            }

                            pm.setTime(timeTimeUserSplit[0] + timeTimeUserSplit[1]);
                            pm.setTitle(dateSubjectSplit[1]);
                            pm.setUser(timeTimeUserSplit[2]);
                            pm.setLink(pmLink);
                            pm.setToken(token);

                            Log.v(TAG, "Adding PM From: " + pm.getUser());
                            pmlist.add(pm);
                        }
                    }
                }
                updateList();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... progress) {
            if (loadingDialog != null)
                loadingDialog.setMessage(progress[0]);
        }

        @Override
        protected void onPostExecute(Void result) {
            loadingDialog.dismiss();
        }
    };
    updaterTask.execute();
}

From source file:com.normalexception.app.rx8club.fragment.thread.ThreadFragment.java

/**
 * Grab contents from the forum that the user clicked on
 * @param doc   The document parsed from the link
 * @param id   The id number of the link
 * @return      An arraylist of forum contents
 *//*from   www.ja v  a  2 s.  c o  m*/
public void getThreadContents(Document doc) {
    // Update pagination
    try {
        Elements pageNumbers = doc.select("div[class=pagenav]");
        if (pageNumbers.first() != null) {
            Elements pageLinks = pageNumbers.first().select("td[class^=vbmenu_control]");
            thisPage = pageLinks.text().split(" ")[1];
            finalPage = pageLinks.text().split(" ")[3];
            Log.d(TAG, String.format("This Page: %s, Final Page: %s", thisPage, finalPage));
        } else {
            Log.d(TAG, "Thread only contains one page");
        }
    } catch (Exception e) {
        Log.e(TAG, "We had an error with pagination", e);
    }

    // Is user thread admin??
    Elements threadTools = doc.select("div[id=threadtools_menu] > form > table");
    if (threadTools.text().contains(MODERATION_TOOLS)) {
        Log.d(TAG, "<><> User has administrative rights here! <><>");
    } else {
        //adminContent.setVisibility(View.GONE);
        lv.removeHeaderView(adminContent);
    }

    // Get the user's actual ID, there is a chance they never got it
    // before
    UserProfile.getInstance().setUserId(HtmlFormUtils.getInputElementValueByName(doc, "loggedinuser"));

    // Get Post Number and security token
    securityToken = HtmlFormUtils.getInputElementValueByName(doc, "securitytoken");

    Elements pNumber = doc.select("a[href^=http://www.rx8club.com/newreply.php?do=newreply&noquote=1&p=]");
    String pNumberHref = pNumber.attr("href");
    postNumber = pNumberHref.substring(pNumberHref.lastIndexOf("=") + 1);
    threadNumber = doc.select("input[name=searchthreadid]").attr("value");

    Elements posts = doc.select("div[id=posts]").select("div[id^=edit]");
    Log.v(TAG, String.format("Parsing through %d posts", posts.size()));
    for (Element post : posts) {
        try {
            Elements innerPost = post.select("table[id^=post]");

            // User Control Panel
            Elements userCp = innerPost.select("td[class=alt2]");
            Elements userDetail = userCp.select("div[class=smallfont]");
            Elements userSubDetail = userDetail.last().select("div");
            Elements userAvatar = userDetail.select("img[alt$=Avatar]");

            // User Information
            PostModel pv = new PostModel();
            pv.setUserName(userCp.select("div[id^=postmenu]").text());
            pv.setIsLoggedInUser(LoginFactory.getInstance().isLoggedIn()
                    ? UserProfile.getInstance().getUsername().equals(pv.getUserName())
                    : false);
            pv.setUserTitle(userDetail.first().text());
            pv.setUserImageUrl(userAvatar.attr("src"));
            pv.setPostDate(innerPost.select("td[class=thead]").first().text());
            pv.setPostId(Utils.parseInts(post.attr("id")));
            pv.setRootThreadUrl(currentPageLink);

            // get Likes if any exist
            Elements eLikes = innerPost.select("div[class*=vbseo_liked] > a");
            List<String> likes = new ArrayList<String>();
            for (Element eLike : eLikes)
                likes.add(eLike.text());
            pv.setLikes(likes);

            Iterator<Element> itr = userSubDetail.listIterator();
            while (itr.hasNext()) {
                String txt = itr.next().text();
                if (txt.contains("Location:"))
                    pv.setUserLocation(txt);
                else if (txt.contains("Posts:"))
                    pv.setUserPostCount(txt);
                else if (txt.contains("Join Date:"))
                    pv.setJoinDate(txt);
            }

            // User Post Content
            pv.setUserPost(formatUserPost(innerPost));

            // User signature
            try {
                Element userSig = innerPost.select("div[class=konafilter]").first();
                pv.setUserSignature(userSig.html());
            } catch (NullPointerException npe) {
            }

            Elements postAttachments = innerPost.select("a[id^=attachment]");
            if (postAttachments != null && !postAttachments.isEmpty()) {
                ArrayList<String> attachments = new ArrayList<String>();
                for (Element postAttachment : postAttachments) {
                    attachments.add(postAttachment.attr("href"));
                }
                pv.setAttachments(attachments);
            }

            pv.setSecurityToken(securityToken);

            // Make sure we aren't adding a blank user post
            if (pv.getUserPost() != null)
                postlist.add(pv);
        } catch (Exception e) {
            Log.w(TAG, "Error Parsing Post...Probably Deleted");
        }
    }
}

From source file:com.normalexception.app.rx8club.fragment.thread.ThreadFragment.java

/**
 * Format the user post by removing the vb style quotes and the 
 * duplicate youtube links/*from ww  w  .  ja  v  a 2 s. c om*/
 * @param innerPost   The element that contains the inner post
 * @return         The formatted string
 */
private String formatUserPost(Elements innerPost) {
    try {
        Element ipost = innerPost.select("td[class=alt1]").select("div[id^=post_message]").first();

        // Only if there is a post to key off of
        if (ipost != null) {
            // Remove the duplicate youtube links (this is caused by a plugin on 
            // the forum that embeds youtube videos automatically)
            for (Element embedded : ipost.select("div[id^=ame_doshow_post_]"))
                embedded.remove();

            // Remove the vbulletin quotes
            return Utils.reformatQuotes(ipost.html());
        } else {
            return null;
        }
    } catch (Exception e) {
        Log.e(TAG, "Error Parsing Post", e);
        return null;
    }
}

From source file:com.normalexception.app.rx8club.fragment.UserCpFragment.java

/**
 * Construct the main view for our user profile
 *///from   ww  w  .ja  v a  2 s .c  om
private void constructView() {
    AsyncTask<Void, String, Void> updaterTask = new AsyncTask<Void, String, Void>() {
        @Override
        protected void onPreExecute() {

            loadingDialog = ProgressDialog.show(getActivity(), getString(R.string.loading),
                    getString(R.string.pleaseWait), true);
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                Document doc = VBForumFactory.getInstance().get(getActivity(), WebUrls.editProfile);

                if (doc != null) {
                    token = HtmlFormUtils.getInputElementValueByName(doc, "securitytoken");

                    Elements fieldSets = doc.select("fieldset[class=fieldset]");

                    publishProgress(getString(R.string.asyncDialogPopulating));
                    for (Element fieldSet : fieldSets) {
                        String legend = fieldSet.select("legend").text();
                        if (legend.equals("Custom User Title")) {
                            customTitle = fieldSet.select("strong").text();
                            continue;
                        } else if (legend.equals("Home Page URL")) {
                            homepageurl = fieldSet.getElementById("tb_homepage").attr("value");
                            continue;
                        } else if (legend.equals("Biography")) {
                            biography = fieldSet.getElementById("ctb_field1").attr("value");
                            continue;
                        } else if (legend.equals("Location")) {
                            location = fieldSet.getElementById("ctb_field2").attr("value");
                            continue;
                        } else if (legend.equals("Interests")) {
                            interests = fieldSet.getElementById("ctb_field3").attr("value");
                            continue;
                        } else if (legend.equals("Occupation")) {
                            occupation = fieldSet.getElementById("ctb_field4").attr("value");
                            continue;
                        }
                    }

                    updateView();
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... progress) {
            if (loadingDialog != null)
                loadingDialog.setMessage(progress[0]);
        }

        @Override
        protected void onPostExecute(Void result) {
            try {
                loadingDialog.dismiss();
                loadingDialog = null;
            } catch (Exception e) {
                Log.w(TAG, e.getMessage());
            }
        }
    };
    updaterTask.execute();

}