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.irccloud.android.Notifications.java

private void showMessageNotifications(String ticker) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
    String text = "";
    String weartext = "";
    ArrayList<Notification> notifications = getMessageNotifications();

    int notify_type = Integer.parseInt(prefs.getString("notify_type", "1"));
    boolean notify = false;
    if (notify_type == 1 || (notify_type == 2 && NetworkConnection.getInstance().isVisible()))
        notify = true;/*from   w w  w.  jav a  2  s  .c  om*/

    if (notifications.size() > 0 && notify) {
        int lastbid = notifications.get(0).bid;
        int count = 0;
        long[] eids = new long[notifications.size()];
        String[] auto_messages = new String[notifications.size()];
        Notification last = null;
        count = 0;
        boolean show = false;
        for (Notification n : notifications) {
            if (n.bid != lastbid) {
                if (show) {
                    String title = last.chan;
                    if (title == null || title.length() == 0)
                        title = last.nick;
                    if (title == null || title.length() == 0)
                        title = last.network;

                    Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
                    replyIntent.putExtra("bid", last.bid);
                    replyIntent.putExtra("cid", last.cid);
                    replyIntent.putExtra("eids", eids);
                    replyIntent.putExtra("network", last.network);
                    if (last.buffer_type.equals("channel"))
                        replyIntent.putExtra("to", last.chan);
                    else
                        replyIntent.putExtra("to", last.nick);

                    String body = "";
                    if (last.buffer_type.equals("channel")) {
                        if (last.message_type.equals("buffer_me_msg"))
                            body = "<b> " + last.nick + "</b> " + last.message;
                        else
                            body = "<b>&lt;" + last.nick + "&gt;</b> " + last.message;
                    } else {
                        if (last.message_type.equals("buffer_me_msg"))
                            body = " " + last.nick + " " + last.message;
                        else
                            body = last.message;
                    }

                    NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext())
                            .notify(lastbid,
                                    buildNotification(ticker, lastbid, eids, title, body, Html.fromHtml(text),
                                            count, replyIntent, Html.fromHtml(weartext), last.network,
                                            auto_messages));
                }
                lastbid = n.bid;
                text = "";
                weartext = "";
                count = 0;
                eids = new long[notifications.size()];
                show = false;
                auto_messages = new String[notifications.size()];
            }
            if (count < 3) {
                if (text.length() > 0)
                    text += "<br/>";
                if (n.buffer_type.equals("conversation") && n.message_type.equals("buffer_me_msg"))
                    text += " " + n.message;
                else if (n.buffer_type.equals("conversation"))
                    text += n.message;
                else if (n.message_type.equals("buffer_me_msg"))
                    text += "<b> " + n.nick + "</b> " + n.message;
                else
                    text += "<b>" + n.nick + "</b> " + n.message;
            }
            if (weartext.length() > 0)
                weartext += "<br/><br/>";
            if (n.message_type.equals("buffer_me_msg"))
                weartext += "<b> " + n.nick + "</b> " + n.message;
            else
                weartext += "<b>&lt;" + n.nick + "&gt;</b> " + n.message;

            if (n.buffer_type.equals("conversation")) {
                if (n.message_type.equals("buffer_me_msg"))
                    auto_messages[count] = " " + n.nick + " " + Html.fromHtml(n.message).toString();
                else
                    auto_messages[count] = Html.fromHtml(n.message).toString();
            } else {
                if (n.message_type.equals("buffer_me_msg"))
                    auto_messages[count] = " " + n.nick + " " + Html.fromHtml(n.message).toString();
                else
                    auto_messages[count] = n.nick + " said: " + Html.fromHtml(n.message).toString();
            }

            if (!n.shown) {
                n.shown = true;
                show = true;

                if (prefs.getBoolean("notify_sony", false)) {
                    long time = System.currentTimeMillis();
                    long sourceId = NotificationUtil.getSourceId(
                            IRCCloudApplication.getInstance().getApplicationContext(),
                            SonyExtensionService.EXTENSION_SPECIFIC_ID);
                    if (sourceId == NotificationUtil.INVALID_ID) {
                        Crashlytics.log(Log.ERROR, "IRCCloud",
                                "Sony LiveWare Manager not configured, disabling Sony notifications");
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putBoolean("notify_sony", false);
                        editor.commit();
                    } else {
                        ContentValues eventValues = new ContentValues();
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.EVENT_READ_STATUS,
                                false);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.DISPLAY_NAME,
                                n.nick);

                        if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE,
                                    n.chan);
                        else
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE,
                                    n.network);

                        if (n.message_type.equals("buffer_me_msg"))
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE,
                                    " " + Html.fromHtml(n.message).toString());
                        else
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE,
                                    Html.fromHtml(n.message).toString());

                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PERSONAL,
                                1);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PUBLISHED_TIME,
                                time);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.SOURCE_ID,
                                sourceId);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY,
                                String.valueOf(n.bid));

                        try {
                            IRCCloudApplication.getInstance().getApplicationContext().getContentResolver()
                                    .insert(com.sonyericsson.extras.liveware.aef.notification.Notification.Event.URI,
                                            eventValues);
                        } catch (IllegalArgumentException e) {
                            Log.e("IRCCloud", "Failed to insert event", e);
                        } catch (SecurityException e) {
                            Log.e("IRCCloud", "Failed to insert event, is Live Ware Manager installed?", e);
                        } catch (SQLException e) {
                            Log.e("IRCCloud", "Failed to insert event", e);
                        }
                    }
                }

                if (prefs.getBoolean("notify_pebble", false)) {
                    String pebbleTitle = n.network + ":\n";
                    String pebbleBody = "";
                    if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
                        pebbleTitle = n.chan + ":\n";

                    if (n.message_type.equals("buffer_me_msg"))
                        pebbleBody = " " + n.message;
                    else
                        pebbleBody = n.message;

                    if (n.nick != null && n.nick.length() > 0)
                        notifyPebble(n.nick, pebbleTitle + Html.fromHtml(pebbleBody).toString());
                    else
                        notifyPebble(n.network, pebbleTitle + Html.fromHtml(pebbleBody).toString());
                }
            }
            eids[count++] = n.eid;
            last = n;
        }

        if (show) {
            String title = last.chan;
            if (title == null || title.length() == 0)
                title = last.nick;
            if (title == null || title.length() == 0)
                title = last.network;

            Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
            replyIntent.putExtra("bid", last.bid);
            replyIntent.putExtra("cid", last.cid);
            replyIntent.putExtra("network", last.network);
            replyIntent.putExtra("eids", eids);
            if (last.buffer_type.equals("channel"))
                replyIntent.putExtra("to", last.chan);
            else
                replyIntent.putExtra("to", last.nick);

            String body = "";
            if (last.buffer_type.equals("channel")) {
                if (last.message_type.equals("buffer_me_msg"))
                    body = "<b> " + last.nick + "</b> " + last.message;
                else
                    body = "<b>&lt;" + last.nick + "&gt;</b> " + last.message;
            } else {
                if (last.message_type.equals("buffer_me_msg"))
                    body = " " + last.nick + " " + last.message;
                else
                    body = last.message;
            }
            NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext())
                    .notify(lastbid, buildNotification(ticker, lastbid, eids, title, body, Html.fromHtml(text),
                            count, replyIntent, Html.fromHtml(weartext), last.network, auto_messages));
        }
    }
}

From source file:com.connectsdk.service.DLNAService.java

String parseData(String response, String key) {
    if (isXmlEncoded(response)) {
        response = Html.fromHtml(response).toString();
    }/*from   w ww .j a  v a 2s. co m*/
    XmlPullParser parser = Xml.newPullParser();
    try {
        parser.setInput(new StringReader(response));
        int event;
        boolean isFound = false;
        do {
            event = parser.next();
            if (event == XmlPullParser.START_TAG) {
                String tag = parser.getName();
                if (key.equals(tag)) {
                    isFound = true;
                }
            } else if (event == XmlPullParser.TEXT && isFound) {
                return parser.getText();
            }
        } while (event != XmlPullParser.END_DOCUMENT);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:com.matthewmitchell.peercoin_android_wallet.ui.WalletActivity.java

private void backupWallet(@Nonnull final String password) {

    Constants.Files.EXTERNAL_WALLET_BACKUP_DIR.mkdirs();

    final File file = new File(Constants.Files.EXTERNAL_WALLET_BACKUP_DIR,
            Constants.Files.EXTERNAL_WALLET_BACKUP + "-" + getFileDate());
    final Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(application.getWallet());

    Writer cipherOut = null;//from   w  w  w  .  ja v a 2s . co  m

    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        walletProto.writeTo(baos);
        baos.close();
        final byte[] plainBytes = baos.toByteArray();

        cipherOut = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8);
        cipherOut.write(Crypto.encrypt(plainBytes, password.toCharArray()));
        cipherOut.flush();

        final DialogBuilder dialog = new DialogBuilder(this);
        dialog.setMessage(Html.fromHtml(getString(R.string.export_keys_dialog_success, file)));
        dialog.setPositiveButton(WholeStringBuilder.bold(getString(R.string.export_keys_dialog_button_archive)),
                new OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        archiveWalletBackup(file);
                    }
                });
        dialog.setNegativeButton(R.string.button_dismiss, null);
        dialog.show();

        log.info("backed up wallet to: '" + file + "'");
    } catch (final IOException x) {
        final DialogBuilder dialog = DialogBuilder.warn(this, R.string.import_export_keys_dialog_failure_title);
        dialog.setMessage(getString(R.string.export_keys_dialog_failure, x.getMessage()));
        dialog.singleDismissButton(null);
        dialog.show();

        log.error("problem backing up wallet", x);
    } finally {
        try {
            cipherOut.close();
        } catch (final IOException x) {
            // swallow
        }
    }
}

From source file:org.nla.tarotdroid.lib.ui.GameSetHistoryActivity.java

/**
 * Called when excel export task is done.
 * // w ww .j  a  va 2s .c  o m
 * @param filePath
 */
private void onGameSetExportedToExcelFile(String filePath) {
    // should never happen
    if (filePath == null) {
        UIHelper.showSimpleRichTextDialog(this, this.getString(R.string.msgDbExportFailed),
                this.getString(R.string.titleDbExportFailed));
    }

    else {
        this.tempExcelFilePath = filePath;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(this.getString(R.string.titleGameSetExportedToExcelFile));
        builder.setMessage(Html.fromHtml(this.getText(R.string.msgGameSetExportedToExcelFile).toString()));
        builder.setPositiveButton(this.getString(R.string.btnOk), this.exportExcelByEmailDialogClickListener);
        builder.setNegativeButton(this.getString(R.string.btnCancel),
                this.exportExcelByEmailDialogClickListener);
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.show();
    }
}

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

public static void notifySecondDMs(Context context, int secondAccount) {
    DMDataSource data = DMDataSource.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences(
            "com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    int numberNew = sharedPrefs.getInt("dm_unread_" + secondAccount, 0);

    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;//from w  w w .j ava 2 s  .c  o  m

    Intent resultIntent = new Intent(context, SwitchAccountsRedirect.class);

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

    NotificationCompat.Builder mBuilder;

    String title = context.getResources().getString(R.string.app_name) + " - "
            + context.getResources().getString(R.string.sec_acc);
    String name;
    String message;
    String messageLong;

    NotificationCompat.InboxStyle inbox = null;
    if (numberNew == 1) {
        name = data.getNewestName(secondAccount);

        // if they are muted, and you don't want them to show muted mentions
        // then just quit
        if (sharedPrefs.getString("muted_users", "").contains(name)
                && !sharedPrefs.getBoolean("show_muted_mentions", false)) {
            return;
        }

        message = context.getResources().getString(R.string.mentioned_by) + " @" + name;
        messageLong = "<b>@" + name + "</b>: " + data.getNewestMessage(secondAccount);
        largeIcon = getImage(context, name);
    } else { // more than one dm
        message = numberNew + " " + context.getResources().getString(R.string.new_mentions);
        messageLong = "<b>" + context.getResources().getString(R.string.mentions) + "</b>: " + numberNew + " "
                + context.getResources().getString(R.string.new_mentions);
        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);

        inbox = getDMInboxStyle(numberNew, secondAccount, context, message);
    }

    Intent markRead = new Intent(context, MarkReadSecondAccService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    AppSettings settings = AppSettings.getInstance(context);

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

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

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? messageLong.replaceAll("FF8800", settings.accentColor) : messageLong)));
    } 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(9, 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 (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, messageLong);
        }

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

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

private void populateChat(JSONArray chats, boolean admin) {
    if (findViewById(R.id.chat_list) == null)
        return;//from  ww  w.j  a  va 2 s .  c om
    chatList = (ListView) findViewById(R.id.chat_list);

    int newChatNo = 0;

    int latestChatTime = 0;
    ArrayList<JSONObject> chatArray = new ArrayList<JSONObject>();

    if (chats.length() < lastChatArray.size()) { // prepend old chats
        for (int i = chats.length(); i < lastChatArray.size(); i++) {
            chatArray.add(lastChatArray.get(i));
        }
    }

    for (int i = 0; i < chats.length(); i++) {
        try {
            JSONObject chat = chats.getJSONObject(i);
            latestChatTime = Integer.parseInt(chat.getString("time"));
            if (latestChatTime > lastChatTime)
                newChatNo++;

            chatArray.add(chat);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    lastChatArray = chatArray;

    if (latestChatTime < lastChatTime)
        newChatNo = -1;

    if (admin)
        chatList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                String cid = (String) view.findViewById(R.id.message).getTag();
                ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                doSubmit("delchat_" + cid, nvp, true);
                return true;
            }
        });

    // save index and top position
    int index = chatList.getFirstVisiblePosition();
    View v = chatList.getChildAt(0);
    int top = (v == null) ? 0 : v.getTop();

    AdapterChat adapter = new AdapterChat(this, R.layout.list_item_chat, chatArray);
    chatList.setAdapter(adapter);

    // restore index and position

    if (doChatScroll) {
        chatList.setSelection(adapter.getCount() - 1);
        doChatScroll = false;
    } else
        chatList.setSelectionFromTop(index, top);

    if (newChatNo > 0) {
        if (currentPosition != 1 && lastChatTime > 0) {
            final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.tick);
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    mp.release();
                }
            });
            mp.start();
            newChats = true;
            ActionBar actionBar = getSupportActionBar();
            if (actionBar.getTabAt(1) != null)
                actionBar.getTabAt(1).setText(
                        Html.fromHtml(getString(R.string.title_section2).toUpperCase(Locale.getDefault()) + " ("
                                + newChatNo + ")"));
        }
    }
    lastChatTime = latestChatTime;
}

From source file:carnero.cgeo.cgBase.java

public cgCacheWrap parseSearch(cgSearchThread thread, String url, String page, boolean showCaptcha) {
    if (page == null || page.length() == 0) {
        Log.e(cgSettings.tag, "cgeoBase.parseSearch: No page given");
        return null;
    }/*from  w ww  . ja  v  a2s. c  o  m*/

    final cgCacheWrap caches = new cgCacheWrap();
    final ArrayList<String> cids = new ArrayList<String>();
    final ArrayList<String> guids = new ArrayList<String>();
    String recaptchaChallenge = null;
    String recaptchaText = null;

    caches.url = url;

    final Pattern patternCacheType = Pattern.compile(
            "<td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=[^\"]+\"[^>]+>[^<]*<img src=\"[^\"]*/images/wpttypes/[^\\.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternGuidAndDisabled = Pattern.compile(
            "<img src=\"[^\"]*/images/wpttypes/[^>]*>[^<]*</a></td><td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=([a-z0-9\\-]+)\" class=\"lnk([^\"]*)\">([^<]*<span>)?([^<]*)(</span>[^<]*)?</a>[^<]+<br />([^<]*)<span[^>]+>([^<]*)</span>([^<]*<img[^>]+>)?[^<]*<br />[^<]*</td>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternTbs = Pattern.compile(
            "<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternTbsInside = Pattern.compile(
            "(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternDirection = Pattern.compile(
            "<img id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxDistanceAndHeading\" title=\"[^\"]*\" src=\"[^\"]*/seek/CacheDir\\.ashx\\?k=([^\"]+)\"[^>]*>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternCode = Pattern.compile("\\|[^\\w]*(GC[a-z0-9]+)[^\\|]*\\|",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternId = Pattern.compile("name=\"CID\"[^v]*value=\"([0-9]+)\"", Pattern.CASE_INSENSITIVE);
    final Pattern patternFavourite = Pattern.compile(
            "<span id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxFavoritesValue\" title=\"[^\"]*\" class=\"favorite-rank\">([0-9]+)</span>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternTotalCnt = Pattern.compile(
            "<td class=\"PageBuilderWidget\"><span>Total Records[^<]*<b>(\\d+)<\\/b>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternRecaptcha = Pattern.compile(
            "<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE);
    final Pattern patternRecaptchaChallenge = Pattern.compile("challenge : '([^']+)'",
            Pattern.CASE_INSENSITIVE);

    caches.viewstate = findViewstate(page, 0);
    caches.viewstate1 = findViewstate(page, 1);

    // recaptcha
    if (showCaptcha == true) {
        try {
            String recaptchaJsParam = null;
            final Matcher matcherRecaptcha = patternRecaptcha.matcher(page);
            while (matcherRecaptcha.find()) {
                if (matcherRecaptcha.groupCount() > 0) {
                    recaptchaJsParam = matcherRecaptcha.group(1);
                }
            }

            if (recaptchaJsParam != null) {
                final String recaptchaJs = request(false, "www.google.com", "/recaptcha/api/challenge", "GET",
                        "k=" + urlencode_rfc3986(recaptchaJsParam.trim()), 0, true).getData();

                if (recaptchaJs != null && recaptchaJs.length() > 0) {
                    final Matcher matcherRecaptchaChallenge = patternRecaptchaChallenge.matcher(recaptchaJs);
                    while (matcherRecaptchaChallenge.find()) {
                        if (matcherRecaptchaChallenge.groupCount() > 0) {
                            recaptchaChallenge = matcherRecaptchaChallenge.group(1).trim();
                        }
                    }
                }
            }
        } catch (Exception e) {
            // failed to parse recaptcha challenge
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse recaptcha challenge");
        }

        if (thread != null && recaptchaChallenge != null && recaptchaChallenge.length() > 0) {
            thread.setChallenge(recaptchaChallenge);
            thread.notifyNeed();
        }
    }

    int startPos = -1;
    int endPos = -1;

    startPos = page.indexOf("<div id=\"ctl00_ContentBody_ResultsPanel\"");
    if (startPos == -1) {
        Log.e(cgSettings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_dlResults\" not found on page");
        return null;
    }

    page = page.substring(startPos); // cut on <table

    startPos = page.indexOf(">");
    endPos = page.indexOf("ctl00_ContentBody_UnitTxt");
    if (startPos == -1 || endPos == -1) {
        Log.e(cgSettings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_UnitTxt\" not found on page");
        return null;
    }

    page = page.substring(startPos + 1, endPos - startPos + 1); // cut between <table> and </table>

    final String[] rows = page.split("<tr class=");
    final int rows_count = rows.length;

    for (int z = 1; z < rows_count; z++) {
        cgCache cache = new cgCache();
        String row = rows[z];

        // check for cache type presence
        if (row.indexOf("images/wpttypes") == -1) {
            continue;
        }

        try {
            final Matcher matcherGuidAndDisabled = patternGuidAndDisabled.matcher(row);

            while (matcherGuidAndDisabled.find()) {
                if (matcherGuidAndDisabled.groupCount() > 0) {
                    guids.add(matcherGuidAndDisabled.group(1));

                    cache.guid = matcherGuidAndDisabled.group(1);
                    if (matcherGuidAndDisabled.group(4) != null) {
                        cache.name = Html.fromHtml(matcherGuidAndDisabled.group(4).trim()).toString();
                    }
                    if (matcherGuidAndDisabled.group(6) != null) {
                        cache.location = Html.fromHtml(matcherGuidAndDisabled.group(6).trim()).toString();
                    }

                    final String attr = matcherGuidAndDisabled.group(2);
                    if (attr != null) {
                        if (attr.contains("Strike") == true) {
                            cache.disabled = true;
                        } else {
                            cache.disabled = false;
                        }

                        if (attr.contains("OldWarning") == true) {
                            cache.archived = true;
                        } else {
                            cache.archived = false;
                        }
                    }
                }
            }
        } catch (Exception e) {
            // failed to parse GUID and/or Disabled
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse GUID and/or Disabled data");
        }

        if (settings.excludeDisabled == 1 && (cache.disabled == true || cache.archived == true)) {
            // skip disabled and archived caches
            cache = null;
            continue;
        }

        String inventoryPre = null;

        // GC* code
        try {
            final Matcher matcherCode = patternCode.matcher(row);
            while (matcherCode.find()) {
                if (matcherCode.groupCount() > 0) {
                    cache.geocode = matcherCode.group(1).toUpperCase();
                }
            }
        } catch (Exception e) {
            // failed to parse code
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache code");
        }

        // cache type
        try {
            final Matcher matcherCacheType = patternCacheType.matcher(row);
            while (matcherCacheType.find()) {
                if (matcherCacheType.groupCount() > 0) {
                    cache.type = cacheTypes.get(matcherCacheType.group(1).toLowerCase());
                }
            }
        } catch (Exception e) {
            // failed to parse type
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache type");
        }

        // cache direction - image
        try {
            final Matcher matcherDirection = patternDirection.matcher(row);
            while (matcherDirection.find()) {
                if (matcherDirection.groupCount() > 0) {
                    cache.directionImg = matcherDirection.group(1);
                }
            }
        } catch (Exception e) {
            // failed to parse direction image
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache direction image");
        }

        // cache inventory
        try {
            final Matcher matcherTbs = patternTbs.matcher(row);
            while (matcherTbs.find()) {
                if (matcherTbs.groupCount() > 0) {
                    cache.inventoryItems = Integer.parseInt(matcherTbs.group(1));
                    inventoryPre = matcherTbs.group(2);
                }
            }
        } catch (Exception e) {
            // failed to parse inventory
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory (1)");
        }

        if (inventoryPre != null && inventoryPre.trim().length() > 0) {
            try {
                final Matcher matcherTbsInside = patternTbsInside.matcher(inventoryPre);
                while (matcherTbsInside.find()) {
                    if (matcherTbsInside.groupCount() == 2 && matcherTbsInside.group(2) != null) {
                        final String inventoryItem = matcherTbsInside.group(2).toLowerCase();
                        if (inventoryItem.equals("premium member only cache")) {
                            continue;
                        } else {
                            if (cache.inventoryItems <= 0) {
                                cache.inventoryItems = 1;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                // failed to parse cache inventory info
                Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory info");
            }
        }

        // premium cache
        if (row.indexOf("/images/small_profile.gif") != -1) {
            cache.members = true;
        } else {
            cache.members = false;
        }

        // found it
        if (row.indexOf("/images/icons/icon_smile.gif") != -1) {
            cache.found = true;
        } else {
            cache.found = false;
        }

        // own it
        if (row.indexOf("/images/silk/star.png") != -1) {
            cache.own = true;
        } else {
            cache.own = false;
        }

        // id
        try {
            final Matcher matcherId = patternId.matcher(row);
            while (matcherId.find()) {
                if (matcherId.groupCount() > 0) {
                    cache.cacheid = matcherId.group(1);
                    cids.add(cache.cacheid);
                }
            }
        } catch (Exception e) {
            // failed to parse cache id
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache id");
        }

        // favourite count
        try {
            final Matcher matcherFavourite = patternFavourite.matcher(row);
            while (matcherFavourite.find()) {
                if (matcherFavourite.groupCount() > 0) {
                    cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1));
                }
            }
        } catch (Exception e) {
            // failed to parse favourite count
            Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse favourite count");
        }

        if (cache.nameSp == null) {
            cache.nameSp = (new Spannable.Factory()).newSpannable(cache.name);
            if (cache.disabled == true || cache.archived == true) { // strike
                cache.nameSp.setSpan(new StrikethroughSpan(), 0, cache.nameSp.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        caches.cacheList.add(cache);
    }

    // total caches found
    try {
        final Matcher matcherTotalCnt = patternTotalCnt.matcher(page);
        while (matcherTotalCnt.find()) {
            if (matcherTotalCnt.groupCount() > 0) {
                if (matcherTotalCnt.group(1) != null) {
                    caches.totalCnt = new Integer(matcherTotalCnt.group(1));
                }
            }
        }
    } catch (Exception e) {
        // failed to parse cache count
        Log.w(cgSettings.tag, "cgeoBase.parseSearch: Failed to parse cache count");
    }

    if (thread != null && recaptchaChallenge != null) {
        if (thread.getText() == null) {
            thread.waitForUser();
        }

        recaptchaText = thread.getText();
    }

    if (cids.size() > 0 && (recaptchaChallenge == null
            || (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0))) {
        Log.i(cgSettings.tag, "Trying to get .loc for " + cids.size() + " caches");

        try {
            // get coordinates for parsed caches
            final String host = "www.geocaching.com";
            final String path = "/seek/nearest.aspx";
            final StringBuilder params = new StringBuilder();
            params.append("__EVENTTARGET=");
            params.append("&");
            params.append("__EVENTARGUMENT=");
            params.append("&");
            params.append("__VIEWSTATE=");
            params.append(urlencode_rfc3986(caches.viewstate));
            if (caches.viewstate1 != null) {
                params.append("&");
                params.append("__VIEWSTATE1=");
                params.append(urlencode_rfc3986(caches.viewstate1));
                params.append("&");
                params.append("__VIEWSTATEFIELDCOUNT=2");
            }

            for (String cid : cids) {
                params.append("&");
                params.append("CID=");
                params.append(urlencode_rfc3986(cid));
            }

            if (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0) {
                params.append("&");
                params.append("recaptcha_challenge_field=");
                params.append(urlencode_rfc3986(recaptchaChallenge));
                params.append("&");
                params.append("recaptcha_response_field=");
                params.append(urlencode_rfc3986(recaptchaText));
            }
            params.append("&");
            params.append("ctl00%24ContentBody%24uxDownloadLoc=Download+Waypoints");

            final String coordinates = request(false, host, path, "POST", params.toString(), 0, true).getData();

            if (coordinates != null && coordinates.length() > 0) {
                if (coordinates.indexOf(
                        "You have not agreed to the license agreement. The license agreement is required before you can start downloading GPX or LOC files from Geocaching.com") > -1) {
                    Log.i(cgSettings.tag,
                            "User has not agreed to the license agreement. Can\'t download .loc file.");

                    caches.error = errorRetrieve.get(-7);

                    return caches;
                }
            }

            if (coordinates != null && coordinates.length() > 0) {
                final HashMap<String, cgCoord> cidCoords = new HashMap<String, cgCoord>();
                final Pattern patternCidCode = Pattern.compile("name id=\"([^\"]+)\"");
                final Pattern patternCidLat = Pattern.compile("lat=\"([^\"]+)\"");
                final Pattern patternCidLon = Pattern.compile("lon=\"([^\"]+)\"");
                // premium only >>
                final Pattern patternCidDif = Pattern.compile("<difficulty>([^<]+)</difficulty>");
                final Pattern patternCidTer = Pattern.compile("<terrain>([^<]+)</terrain>");
                final Pattern patternCidCon = Pattern.compile("<container>([^<]+)</container>");
                // >> premium only

                final String[] points = coordinates.split("<waypoint>");

                // parse coordinates
                for (String point : points) {
                    final cgCoord pointCoord = new cgCoord();
                    final Matcher matcherCidCode = patternCidCode.matcher(point);
                    final Matcher matcherLatCode = patternCidLat.matcher(point);
                    final Matcher matcherLonCode = patternCidLon.matcher(point);
                    final Matcher matcherDifCode = patternCidDif.matcher(point);
                    final Matcher matcherTerCode = patternCidTer.matcher(point);
                    final Matcher matcherConCode = patternCidCon.matcher(point);
                    HashMap<String, Object> tmp = null;

                    if (matcherCidCode.find() == true) {
                        pointCoord.name = matcherCidCode.group(1).trim().toUpperCase();
                    }
                    if (matcherLatCode.find() == true) {
                        tmp = parseCoordinate(matcherLatCode.group(1), "lat");
                        pointCoord.latitude = (Double) tmp.get("coordinate");
                    }
                    if (matcherLonCode.find() == true) {
                        tmp = parseCoordinate(matcherLonCode.group(1), "lon");
                        pointCoord.longitude = (Double) tmp.get("coordinate");
                    }
                    if (matcherDifCode.find() == true) {
                        pointCoord.difficulty = new Float(matcherDifCode.group(1));
                    }
                    if (matcherTerCode.find() == true) {
                        pointCoord.terrain = new Float(matcherTerCode.group(1));
                    }
                    if (matcherConCode.find() == true) {
                        final int size = Integer.parseInt(matcherConCode.group(1));

                        if (size == 1) {
                            pointCoord.size = "not chosen";
                        } else if (size == 2) {
                            pointCoord.size = "micro";
                        } else if (size == 3) {
                            pointCoord.size = "regular";
                        } else if (size == 4) {
                            pointCoord.size = "large";
                        } else if (size == 5) {
                            pointCoord.size = "virtual";
                        } else if (size == 6) {
                            pointCoord.size = "other";
                        } else if (size == 8) {
                            pointCoord.size = "small";
                        } else {
                            pointCoord.size = "unknown";
                        }
                    }

                    cidCoords.put(pointCoord.name, pointCoord);
                }

                Log.i(cgSettings.tag, "Coordinates found in .loc file: " + cidCoords.size());

                // save found cache coordinates
                for (cgCache oneCache : caches.cacheList) {
                    if (cidCoords.containsKey(oneCache.geocode) == true) {
                        cgCoord thisCoords = cidCoords.get(oneCache.geocode);

                        oneCache.latitude = thisCoords.latitude;
                        oneCache.longitude = thisCoords.longitude;
                        oneCache.difficulty = thisCoords.difficulty;
                        oneCache.terrain = thisCoords.terrain;
                        oneCache.size = thisCoords.size;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.parseSearch.CIDs: " + e.toString());
        }
    }

    // get direction images
    cgDirectionImg dirImgDownloader = new cgDirectionImg(settings);
    for (cgCache oneCache : caches.cacheList) {
        if (oneCache.latitude == null && oneCache.longitude == null && oneCache.direction == null
                && oneCache.directionImg != null) {
            dirImgDownloader.getDrawable(oneCache.geocode, oneCache.directionImg);
        }
    }
    dirImgDownloader = null;

    // get ratings
    if (guids.size() > 0) {
        Log.i(cgSettings.tag, "Trying to get ratings for " + cids.size() + " caches");

        try {
            final HashMap<String, cgRating> ratings = getRating(guids, null);

            if (ratings != null) {
                // save found cache coordinates
                for (cgCache oneCache : caches.cacheList) {
                    if (ratings.containsKey(oneCache.guid) == true) {
                        cgRating thisRating = ratings.get(oneCache.guid);

                        oneCache.rating = thisRating.rating;
                        oneCache.votes = thisRating.votes;
                        oneCache.myVote = thisRating.myVote;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.parseSearch.GCvote: " + e.toString());
        }
    }

    return caches;
}

From source file:com.android.mms.ui.MessageListItem.java

public void updateDelayCountDown() {
    if (mMessageItem.isSms() && mMessageItem.getCountDown() > 0 && mMessageItem.isSending()) {
        String content = mContext.getResources().getQuantityString(R.plurals.remaining_delay_time,
                mMessageItem.getCountDown(), mMessageItem.getCountDown());
        Spanned spanned = Html.fromHtml(buildTimestampLine(content));
        mDateView.setText(spanned);/*  w  w  w  .  ja v  a  2s .c  o m*/
    } else {
        mDateView.setText(buildTimestampLine(
                mMessageItem.isSending() ? mContext.getResources().getString(R.string.sending_message)
                        : mMessageItem.mTimestamp));
    }
}

From source file:carnero.cgeo.original.libs.Base.java

public CacheWrap parseSearch(SearchThread thread, String url, String page, boolean showCaptcha) {
    if (page == null || page.length() == 0) {
        Log.e(Settings.tag, "cgeoBase.parseSearch: No page given");
        return null;
    }//from www.ja va 2  s .c  o  m

    final CacheWrap caches = new CacheWrap();
    final ArrayList<String> cids = new ArrayList<String>();
    final ArrayList<String> guids = new ArrayList<String>();
    String recaptchaChallenge = null;
    String recaptchaText = null;

    caches.url = url;

    final Pattern patternCacheType = Pattern.compile(
            "<td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=[^\"]+\"[^>]+>[^<]*<img src=\"[^\"]*/images/wpttypes/[^\\.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternGuidAndDisabled = Pattern.compile(
            "<img src=\"[^\"]*/images/wpttypes/[^>]*>[^<]*</a></td><td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=([a-z0-9\\-]+)\" class=\"lnk([^\"]*)\">([^<]*<span>)?([^<]*)(</span>[^<]*)?</a>[^<]+<br />([^<]*)<span[^>]+>([^<]*)</span>([^<]*<img[^>]+>)?[^<]*<br />[^<]*</td>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternTbs = Pattern.compile(
            "<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternTbsInside = Pattern.compile(
            "(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternDirection = Pattern.compile(
            "<img id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxDistanceAndHeading\" title=\"[^\"]*\" src=\"[^\"]*/seek/CacheDir\\.ashx\\?k=([^\"]+)\"[^>]*>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternCode = Pattern.compile("\\|[^\\w]*(GC[a-z0-9]+)[^\\|]*\\|",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Pattern patternId = Pattern.compile("name=\"CID\"[^v]*value=\"([0-9]+)\"", Pattern.CASE_INSENSITIVE);
    final Pattern patternFavourite = Pattern.compile(
            "<span id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxFavoritesValue\" title=\"[^\"]*\" class=\"favorite-rank\">([0-9]+)</span>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternTotalCnt = Pattern.compile(
            "<td class=\"PageBuilderWidget\"><span>Total Records[^<]*<b>(\\d+)<\\/b>",
            Pattern.CASE_INSENSITIVE);
    final Pattern patternRecaptcha = Pattern.compile(
            "<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE);
    final Pattern patternRecaptchaChallenge = Pattern.compile("challenge : '([^']+)'",
            Pattern.CASE_INSENSITIVE);

    caches.viewstate = findViewstate(page, 0);
    caches.viewstate1 = findViewstate(page, 1);

    // recaptcha
    if (showCaptcha == true) {
        try {
            String recaptchaJsParam = null;
            final Matcher matcherRecaptcha = patternRecaptcha.matcher(page);
            while (matcherRecaptcha.find()) {
                if (matcherRecaptcha.groupCount() > 0) {
                    recaptchaJsParam = matcherRecaptcha.group(1);
                }
            }

            if (recaptchaJsParam != null) {
                final String recaptchaJs = request(false, "www.google.com", "/recaptcha/api/challenge", "GET",
                        "k=" + urlencode_rfc3986(recaptchaJsParam.trim()), 0, true).getData();

                if (recaptchaJs != null && recaptchaJs.length() > 0) {
                    final Matcher matcherRecaptchaChallenge = patternRecaptchaChallenge.matcher(recaptchaJs);
                    while (matcherRecaptchaChallenge.find()) {
                        if (matcherRecaptchaChallenge.groupCount() > 0) {
                            recaptchaChallenge = matcherRecaptchaChallenge.group(1).trim();
                        }
                    }
                }
            }
        } catch (Exception e) {
            // failed to parse recaptcha challenge
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse recaptcha challenge");
        }

        if (thread != null && recaptchaChallenge != null && recaptchaChallenge.length() > 0) {
            thread.setChallenge(recaptchaChallenge);
            thread.notifyNeed();
        }
    }

    int startPos = -1;
    int endPos = -1;

    startPos = page.indexOf("<div id=\"ctl00_ContentBody_ResultsPanel\"");
    if (startPos == -1) {
        Log.e(Settings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_dlResults\" not found on page");
        return null;
    }

    page = page.substring(startPos); // cut on <table

    startPos = page.indexOf(">");
    endPos = page.indexOf("ctl00_ContentBody_UnitTxt");
    if (startPos == -1 || endPos == -1) {
        Log.e(Settings.tag, "cgeoBase.parseSearch: ID \"ctl00_ContentBody_UnitTxt\" not found on page");
        return null;
    }

    page = page.substring(startPos + 1, endPos - startPos + 1); // cut between <table> and </table>

    final String[] rows = page.split("<tr class=");
    final int rows_count = rows.length;

    for (int z = 1; z < rows_count; z++) {
        Cache cache = new Cache();
        String row = rows[z];

        // check for cache type presence
        if (row.indexOf("images/wpttypes") == -1) {
            continue;
        }

        try {
            final Matcher matcherGuidAndDisabled = patternGuidAndDisabled.matcher(row);

            while (matcherGuidAndDisabled.find()) {
                if (matcherGuidAndDisabled.groupCount() > 0) {
                    guids.add(matcherGuidAndDisabled.group(1));

                    cache.guid = matcherGuidAndDisabled.group(1);
                    if (matcherGuidAndDisabled.group(4) != null) {
                        cache.name = Html.fromHtml(matcherGuidAndDisabled.group(4).trim()).toString();
                    }
                    if (matcherGuidAndDisabled.group(6) != null) {
                        cache.location = Html.fromHtml(matcherGuidAndDisabled.group(6).trim()).toString();
                    }

                    final String attr = matcherGuidAndDisabled.group(2);
                    if (attr != null) {
                        if (attr.contains("Strike") == true) {
                            cache.disabled = true;
                        } else {
                            cache.disabled = false;
                        }

                        if (attr.contains("OldWarning") == true) {
                            cache.archived = true;
                        } else {
                            cache.archived = false;
                        }
                    }
                }
            }
        } catch (Exception e) {
            // failed to parse GUID and/or Disabled
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse GUID and/or Disabled data");
        }

        if (settings.excludeDisabled == 1 && (cache.disabled == true || cache.archived == true)) {
            // skip disabled and archived caches
            cache = null;
            continue;
        }

        String inventoryPre = null;

        // GC* code
        try {
            final Matcher matcherCode = patternCode.matcher(row);
            while (matcherCode.find()) {
                if (matcherCode.groupCount() > 0) {
                    cache.geocode = matcherCode.group(1).toUpperCase();
                }
            }
        } catch (Exception e) {
            // failed to parse code
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache code");
        }

        // cache type
        try {
            final Matcher matcherCacheType = patternCacheType.matcher(row);
            while (matcherCacheType.find()) {
                if (matcherCacheType.groupCount() > 0) {
                    cache.type = cacheTypes.get(matcherCacheType.group(1).toLowerCase());
                }
            }
        } catch (Exception e) {
            // failed to parse type
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache type");
        }

        // cache direction - image
        try {
            final Matcher matcherDirection = patternDirection.matcher(row);
            while (matcherDirection.find()) {
                if (matcherDirection.groupCount() > 0) {
                    cache.directionImg = matcherDirection.group(1);
                }
            }
        } catch (Exception e) {
            // failed to parse direction image
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache direction image");
        }

        // cache inventory
        try {
            final Matcher matcherTbs = patternTbs.matcher(row);
            while (matcherTbs.find()) {
                if (matcherTbs.groupCount() > 0) {
                    cache.inventoryItems = Integer.parseInt(matcherTbs.group(1));
                    inventoryPre = matcherTbs.group(2);
                }
            }
        } catch (Exception e) {
            // failed to parse inventory
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory (1)");
        }

        if (inventoryPre != null && inventoryPre.trim().length() > 0) {
            try {
                final Matcher matcherTbsInside = patternTbsInside.matcher(inventoryPre);
                while (matcherTbsInside.find()) {
                    if (matcherTbsInside.groupCount() == 2 && matcherTbsInside.group(2) != null) {
                        final String inventoryItem = matcherTbsInside.group(2).toLowerCase();
                        if (inventoryItem.equals("premium member only cache")) {
                            continue;
                        } else {
                            if (cache.inventoryItems <= 0) {
                                cache.inventoryItems = 1;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                // failed to parse cache inventory info
                Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache inventory info");
            }
        }

        // premium cache
        if (row.indexOf("/images/small_profile.gif") != -1) {
            cache.members = true;
        } else {
            cache.members = false;
        }

        // found it
        if (row.indexOf("/images/icons/icon_smile.png") != -1) {
            cache.found = true;
        } else {
            cache.found = false;
        }

        // own it
        if (row.indexOf("/images/silk/star.png") != -1) {
            cache.own = true;
        } else {
            cache.own = false;
        }

        // id
        try {
            final Matcher matcherId = patternId.matcher(row);
            while (matcherId.find()) {
                if (matcherId.groupCount() > 0) {
                    cache.cacheid = matcherId.group(1);
                    cids.add(cache.cacheid);
                }
            }
        } catch (Exception e) {
            // failed to parse cache id
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache id");
        }

        // favourite count
        try {
            final Matcher matcherFavourite = patternFavourite.matcher(row);
            while (matcherFavourite.find()) {
                if (matcherFavourite.groupCount() > 0) {
                    cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1));
                }
            }
        } catch (Exception e) {
            // failed to parse favourite count
            Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse favourite count");
        }

        if (cache.nameSp == null) {
            cache.nameSp = (new Spannable.Factory()).newSpannable(cache.name);
            if (cache.disabled == true || cache.archived == true) { // strike
                cache.nameSp.setSpan(new StrikethroughSpan(), 0, cache.nameSp.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        caches.cacheList.add(cache);
    }

    // total caches found
    try {
        final Matcher matcherTotalCnt = patternTotalCnt.matcher(page);
        while (matcherTotalCnt.find()) {
            if (matcherTotalCnt.groupCount() > 0) {
                if (matcherTotalCnt.group(1) != null) {
                    caches.totalCnt = new Integer(matcherTotalCnt.group(1));
                }
            }
        }
    } catch (Exception e) {
        // failed to parse cache count
        Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse cache count");
    }

    if (thread != null && recaptchaChallenge != null) {
        if (thread.getText() == null) {
            thread.waitForUser();
        }

        recaptchaText = thread.getText();
    }

    if (cids.size() > 0 && (recaptchaChallenge == null
            || (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0))) {
        Log.i(Settings.tag, "Trying to get .loc for " + cids.size() + " caches");

        try {
            // get coordinates for parsed caches
            final String host = "www.geocaching.com";
            final String path = "/seek/nearest.aspx";
            final StringBuilder params = new StringBuilder();
            params.append("__EVENTTARGET=");
            params.append("&");
            params.append("__EVENTARGUMENT=");
            params.append("&");
            params.append("__VIEWSTATE=");
            params.append(urlencode_rfc3986(caches.viewstate));
            if (caches.viewstate1 != null) {
                params.append("&");
                params.append("__VIEWSTATE1=");
                params.append(urlencode_rfc3986(caches.viewstate1));
                params.append("&");
                params.append("__VIEWSTATEFIELDCOUNT=2");
            }

            for (String cid : cids) {
                params.append("&");
                params.append("CID=");
                params.append(urlencode_rfc3986(cid));
            }

            if (recaptchaChallenge != null && recaptchaText != null && recaptchaText.length() > 0) {
                params.append("&");
                params.append("recaptcha_challenge_field=");
                params.append(urlencode_rfc3986(recaptchaChallenge));
                params.append("&");
                params.append("recaptcha_response_field=");
                params.append(urlencode_rfc3986(recaptchaText));
            }
            params.append("&");
            params.append("ctl00%24ContentBody%24uxDownloadLoc=Download+Waypoints");

            final String coordinates = request(false, host, path, "POST", params.toString(), 0, true).getData();

            if (coordinates != null && coordinates.length() > 0) {
                if (coordinates.indexOf(
                        "You have not agreed to the license agreement. The license agreement is required before you can start downloading GPX or LOC files from Geocaching.com") > -1) {
                    Log.i(Settings.tag,
                            "User has not agreed to the license agreement. Can\'t download .loc file.");

                    caches.error = errorRetrieve.get(-7);

                    return caches;
                }
            }

            if (coordinates != null && coordinates.length() > 0) {
                final HashMap<String, Coord> cidCoords = new HashMap<String, Coord>();
                final Pattern patternCidCode = Pattern.compile("name id=\"([^\"]+)\"");
                final Pattern patternCidLat = Pattern.compile("lat=\"([^\"]+)\"");
                final Pattern patternCidLon = Pattern.compile("lon=\"([^\"]+)\"");
                // premium only >>
                final Pattern patternCidDif = Pattern.compile("<difficulty>([^<]+)</difficulty>");
                final Pattern patternCidTer = Pattern.compile("<terrain>([^<]+)</terrain>");
                final Pattern patternCidCon = Pattern.compile("<container>([^<]+)</container>");
                // >> premium only

                final String[] points = coordinates.split("<waypoint>");

                // parse coordinates
                for (String point : points) {
                    final Coord pointCoord = new Coord();
                    final Matcher matcherCidCode = patternCidCode.matcher(point);
                    final Matcher matcherLatCode = patternCidLat.matcher(point);
                    final Matcher matcherLonCode = patternCidLon.matcher(point);
                    final Matcher matcherDifCode = patternCidDif.matcher(point);
                    final Matcher matcherTerCode = patternCidTer.matcher(point);
                    final Matcher matcherConCode = patternCidCon.matcher(point);
                    HashMap<String, Object> tmp = null;

                    if (matcherCidCode.find() == true) {
                        pointCoord.name = matcherCidCode.group(1).trim().toUpperCase();
                    }
                    if (matcherLatCode.find() == true) {
                        tmp = parseCoordinate(matcherLatCode.group(1), "lat");
                        pointCoord.latitude = (Double) tmp.get("coordinate");
                    }
                    if (matcherLonCode.find() == true) {
                        tmp = parseCoordinate(matcherLonCode.group(1), "lon");
                        pointCoord.longitude = (Double) tmp.get("coordinate");
                    }
                    if (matcherDifCode.find() == true) {
                        pointCoord.difficulty = new Float(matcherDifCode.group(1));
                    }
                    if (matcherTerCode.find() == true) {
                        pointCoord.terrain = new Float(matcherTerCode.group(1));
                    }
                    if (matcherConCode.find() == true) {
                        final int size = Integer.parseInt(matcherConCode.group(1));

                        if (size == 1) {
                            pointCoord.size = "not chosen";
                        } else if (size == 2) {
                            pointCoord.size = "micro";
                        } else if (size == 3) {
                            pointCoord.size = "regular";
                        } else if (size == 4) {
                            pointCoord.size = "large";
                        } else if (size == 5) {
                            pointCoord.size = "virtual";
                        } else if (size == 6) {
                            pointCoord.size = "other";
                        } else if (size == 8) {
                            pointCoord.size = "small";
                        } else {
                            pointCoord.size = "unknown";
                        }
                    }

                    cidCoords.put(pointCoord.name, pointCoord);
                }

                Log.i(Settings.tag, "Coordinates found in .loc file: " + cidCoords.size());

                // save found cache coordinates
                for (Cache oneCache : caches.cacheList) {
                    if (cidCoords.containsKey(oneCache.geocode) == true) {
                        Coord thisCoords = cidCoords.get(oneCache.geocode);

                        oneCache.latitude = thisCoords.latitude;
                        oneCache.longitude = thisCoords.longitude;
                        oneCache.difficulty = thisCoords.difficulty;
                        oneCache.terrain = thisCoords.terrain;
                        oneCache.size = thisCoords.size;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(Settings.tag, "cgBase.parseSearch.CIDs: " + e.toString());
        }
    }

    // get direction images
    DirectionImg dirImgDownloader = new DirectionImg(settings);
    for (Cache oneCache : caches.cacheList) {
        if (oneCache.latitude == null && oneCache.longitude == null && oneCache.direction == null
                && oneCache.directionImg != null) {
            dirImgDownloader.getDrawable(oneCache.geocode, oneCache.directionImg);
        }
    }
    dirImgDownloader = null;

    return caches;
}