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:android.melbournehistorymap.MapsActivity.java

/**
 * Manipulates the map once available./* w w w  . ja  v  a2 s. com*/
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    spinner = (ProgressBar) findViewById(R.id.prograssSpinner);
    //check if permission has been granted
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Permission has already been granted
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(false);

    double lat;
    double lng;
    final int radius;
    int zoom;

    lat = Double.parseDouble(CurrLat);
    lng = Double.parseDouble(CurrLong);

    //build current location
    LatLng currentLocation = new LatLng(lat, lng);
    final LatLng realLocation = currentLocation;

    if (MELBOURNE.contains(currentLocation)) {
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        zoom = 17;
    } else {
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        lat = -37.81161508043379;
        lng = 144.9647320434451;
        zoom = 15;
        currentLocation = new LatLng(lat, lng);
    }

    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 13));

    CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLocation) // Sets the center of the map to location user
            .zoom(zoom) // Sets the zoom
            .bearing(0) // Sets the orientation of the camera to east
            .tilt(25) // Sets the tilt of the camera to 30 degrees
            .build(); // Creates a CameraPosition from the builder

    //Animate user to map location, if in Melbourne or outside of Melbourne bounds
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
            new GoogleMap.CancelableCallback() {
                @Override
                public void onFinish() {
                    updateMap();
                }

                @Override
                public void onCancel() {

                }
            });

    final TextView placeTitle = (TextView) findViewById(R.id.placeTitle);
    final TextView placeVic = (TextView) findViewById(R.id.placeVic);
    final TextView expPlaceTitle = (TextView) findViewById(R.id.expPlaceTitle);
    final TextView expPlaceVic = (TextView) findViewById(R.id.expPlaceVic);
    final TextView expPlaceDescription = (TextView) findViewById(R.id.placeDescription);
    final TextView wikiLicense = (TextView) findViewById(R.id.wikiLicense);
    final TextView expPlaceDistance = (TextView) findViewById(R.id.expPlaceDistance);
    final RelativeLayout tile = (RelativeLayout) findViewById(R.id.tile);
    final TextView fab = (TextView) findViewById(R.id.fab);
    final RelativeLayout distanceCont = (RelativeLayout) findViewById(R.id.distanceContainer);

    //        String license = "Text is available under the <a rel=\"license\" href=\"//en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\">Creative Commons Attribution-ShareAlike License</a><a rel=\"license\" href=\"//creativecommons.org/licenses/by-sa/3.0/\" style=\"display:none;\"></a>;\n" +
    //                "additional terms may apply.";
    //        wikiLicense.setText(Html.fromHtml(license));
    //        wikiLicense.setMovementMethod(LinkMovementMethod.getInstance());
    //Marker click
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(Marker marker) {
            String title = marker.getTitle();
            mMap.setPadding(0, 0, 0, 620);
            //set clicked marker to full opacity
            marker.setAlpha(1f);
            //set previous marker back to partial opac (if there is a prevMarker
            if (dirtyMarker == 1) {
                prevMarker.setAlpha(0.6f);
            }
            prevMarker = marker;
            dirtyMarker = 1;

            //Set DB helper
            DBHelper myDBHelper = new DBHelper(MapsActivity.this, WikiAPI.DB_NAME, null, WikiAPI.VERSION);

            //Only search for Wiki API requests if no place article returned.
            // **
            //Open DB as readable only.
            SQLiteDatabase db = myDBHelper.getReadableDatabase();
            //Set the query
            String dbFriendlyName = title.replace("\'", "\'\'");
            //Limit by 1 rows
            Cursor cursor = db.query(DBHelper.TABLE_NAME, null, "PLACE_NAME = '" + dbFriendlyName + "'", null,
                    null, null, null, "1");

            //move through each row returned in the query results
            while (cursor.moveToNext()) {

                String place_ID = cursor.getString(cursor.getColumnIndex("PLACE_ID"));
                String placeName = cursor.getString(cursor.getColumnIndex("PLACE_NAME"));
                String placeLoc = cursor.getString(cursor.getColumnIndex("PLACE_LOCATION"));
                String placeArticle = cursor.getString(cursor.getColumnIndex("ARTICLE"));
                String placeLat = cursor.getString(cursor.getColumnIndex("LAT"));
                String placeLng = cursor.getString(cursor.getColumnIndex("LNG"));

                //Get Google Place photos
                //Source: https://developers.google.com/places/android-api/photos
                final String placeId = place_ID;
                Places.GeoDataApi.getPlacePhotos(mGoogleApiClient, placeId)
                        .setResultCallback(new ResultCallback<PlacePhotoMetadataResult>() {
                            @Override
                            public void onResult(PlacePhotoMetadataResult photos) {
                                if (!photos.getStatus().isSuccess()) {
                                    return;
                                }
                                ImageView mImageView = (ImageView) findViewById(R.id.imageView);
                                ImageView mImageViewExpanded = (ImageView) findViewById(R.id.headerImage);
                                TextView txtAttribute = (TextView) findViewById(R.id.photoAttribute);
                                TextView expTxtAttribute = (TextView) findViewById(R.id.expPhotoAttribute);
                                PlacePhotoMetadataBuffer photoMetadataBuffer = photos.getPhotoMetadata();
                                if (photoMetadataBuffer.getCount() > 0) {
                                    // Display the first bitmap in an ImageView in the size of the view
                                    photoMetadataBuffer.get(0).getScaledPhoto(mGoogleApiClient, 600, 200)
                                            .setResultCallback(mDisplayPhotoResultCallback);
                                    //get photo attributions
                                    PlacePhotoMetadata photo = photoMetadataBuffer.get(0);
                                    CharSequence attribution = photo.getAttributions();
                                    if (attribution != null) {
                                        txtAttribute.setText(Html.fromHtml(String.valueOf(attribution)));
                                        expTxtAttribute.setText(Html.fromHtml(String.valueOf(attribution)));
                                        //http://stackoverflow.com/questions/4303160/how-can-i-make-links-in-fromhtml-clickable-android
                                        txtAttribute.setMovementMethod(LinkMovementMethod.getInstance());
                                        expTxtAttribute.setMovementMethod(LinkMovementMethod.getInstance());
                                    } else {
                                        txtAttribute.setText(" ");
                                        expTxtAttribute.setText(" ");
                                    }
                                } else {
                                    //Reset image view as no photo was identified
                                    mImageView.setImageResource(android.R.color.transparent);
                                    mImageViewExpanded.setImageResource(android.R.color.transparent);
                                    txtAttribute.setText(R.string.no_photos);
                                    expTxtAttribute.setText(R.string.no_photos);
                                }
                                photoMetadataBuffer.release();
                            }
                        });

                LatLng destLocation = new LatLng(Double.parseDouble(placeLat), Double.parseDouble(placeLng));
                //Work out distance between current location and place location
                //Source Library: https://github.com/googlemaps/android-maps-utils
                double distance = SphericalUtil.computeDistanceBetween(realLocation, destLocation);
                distance = Math.round(distance);
                distance = distance * 0.001;
                String strDistance = String.valueOf(distance);
                String[] arrDistance = strDistance.split("\\.");
                String unit = "km";
                if (arrDistance[0] == "0") {
                    unit = "m";
                    strDistance = arrDistance[1];
                } else {
                    strDistance = arrDistance[0] + "." + arrDistance[1].substring(0, 1);
                }

                placeArticle = placeArticle
                        .replaceAll("(<div class=\"thumb t).*\\s.*\\s.*\\s.*\\s.*\\s<\\/div>\\s<\\/div>", " ");

                Spannable noUnderlineMessage = new SpannableString(Html.fromHtml(placeArticle));

                //http://stackoverflow.com/questions/4096851/remove-underline-from-links-in-textview-android
                for (URLSpan u : noUnderlineMessage.getSpans(0, noUnderlineMessage.length(), URLSpan.class)) {
                    noUnderlineMessage.setSpan(new UnderlineSpan() {
                        public void updateDrawState(TextPaint tp) {
                            tp.setUnderlineText(false);
                        }
                    }, noUnderlineMessage.getSpanStart(u), noUnderlineMessage.getSpanEnd(u), 0);
                }

                placeArticle = String.valueOf(noUnderlineMessage);
                placeArticle = placeArticle.replaceAll("(\\[\\d\\])", " ");

                placeTitle.setText(placeName);
                expPlaceTitle.setText(placeName);
                placeVic.setText(placeLoc);
                expPlaceVic.setText(placeLoc);
                expPlaceDescription.setText(placeArticle);
                if (MELBOURNE.contains(realLocation)) {
                    expPlaceDistance.setText("Distance: " + strDistance + unit);
                    distanceCont.setVisibility(View.VISIBLE);
                }
            }

            tile.setVisibility(View.VISIBLE);
            fab.setVisibility(View.VISIBLE);
            //Set to true to not show default behaviour.
            return false;
        }
    });

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            int viewStatus = tile.getVisibility();
            if (viewStatus == View.VISIBLE) {
                tile.setVisibility(View.INVISIBLE);
                fab.setVisibility(View.INVISIBLE);
                //set previous marker back to partial opac (if there is a prevMarker
                if (dirtyMarker == 1) {
                    prevMarker.setAlpha(0.6f);
                }
            }

            mMap.setPadding(0, 0, 0, 0);
        }
    });

    FloatingActionButton shareIcon = (FloatingActionButton) findViewById(R.id.shareIcon);
    shareIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //https://www.google.com.au/maps/place/Federation+Square/@-37.8179789,144.9668635,15z

            //Build implicit intent by triggering a SENDTO action, which will capture applications that allow for messages
            //that allow for messages to be sent to a specific user with data
            //http://developer.android.com/reference/android/content/Intent.html#ACTION_SENDTO
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            //Build SMS
            String encodedPlace = "empty";
            try {
                encodedPlace = URLEncoder.encode(String.valueOf(expPlaceTitle.getText()), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            intent.putExtra(Intent.EXTRA_TEXT, String.valueOf(expPlaceTitle.getText())
                    + " \n\nhttps://www.google.com.au/maps/place/" + encodedPlace);
            Intent sms = Intent.createChooser(intent, null);
            startActivity(sms);
        }
    });

    TextView fullArticle = (TextView) findViewById(R.id.fullArticle);
    fullArticle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String wikiPlace = WikiPlace.getName(String.valueOf(expPlaceTitle.getText()));
            String url = "https://en.wikipedia.org/wiki/" + wikiPlace;

            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(browserIntent);
        }
    });
}

From source file:com.bionx.res.DashMainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.settings:
        @SuppressWarnings("unused")
        final Context context = this;
        Intent settings_menu = new Intent(Settings.ACTION_SETTINGS);
        startActivity(settings_menu);// w  ww  .  ja  va2  s .c  o m
        return true;
    case R.id.info:
        new AlertDialog.Builder(this).setTitle(R.string.info)
                .setMessage(Html.fromHtml(getString(R.string.info_msg))).show();
        return true;
    case R.id.preference:
        @SuppressWarnings("unused")
        final Context context1 = this;
        Intent preference = new Intent(getBaseContext(), Preferences.class);
        startActivity(preference);
        return true;
    case R.id.exit:
        Toast.makeText(getApplicationContext(), "Bionx FTW!", Toast.LENGTH_SHORT).show();
        DashMainActivity.this.finish();
    }
    return false;
}

From source file:in.rade.armud.armudclient.MainActivity.java

private void parseMessage(String[] splitMessage) {
    Log.d(WEBSOCKET_TAG, "parsing");
    if (splitMessage[0].equals("DATA")) {
        Log.d(WEBSOCKET_TAG, "Sending message to watch");
        new SendMessageToWearThread(Globals.ARMUD_DATA_PATH, splitMessage[1] + "," + splitMessage[2]).start();
        if (splitMessage[1].equals("LOC") && !splitMessage[2].equals(mCurrentRoom)) {
            mAccuracyThresh = mLatestLocAccuracy < 10 ? 10 : mLatestLocAccuracy;
            mCurrentRoom = splitMessage[2];
            mRoomArrivalTime = System.currentTimeMillis();
        }//from ww w. j ava 2  s  .c o m

    } else {
        //keep in mind that the message either can't have commas or the splitMessage array needs to be reworked
        if (amWaitingOnSubmit) {
            if (!"Sorry".equals(splitMessage[0])) {
                mSubmitSuccess = true;
                SharedPreferences.Editor edit = mPrefs.edit();
                edit.putString("LOGIN_STRING", mLoginString);
                while (!edit.commit()) {
                    Log.d("login init", "commit failed, trying again");
                }
                logintoMUD();
            }
            amWaitingOnSubmit = false;
        }
        String message = "";
        for (int i = 0; i < splitMessage.length; i++) {
            message = i == 0 ? splitMessage[i] : message + ", " + splitMessage[i];
        }
        message = Html.fromHtml(message).toString();
        speech(message);
        mLocInfoLabel = mLocInfoLabel + "\n ======== \n" + message;
    }
}

From source file:com.mobicage.rogerthat.registration.RegistrationActivity2.java

@Override
protected void onServiceBound() {
    T.UI();//from   w w  w.  ja v a  2  s.c  om
    if (mNotYetProcessedIntent != null) {
        processIntent(mNotYetProcessedIntent);
        mNotYetProcessedIntent = null;
    }

    setContentView(R.layout.registration2);

    //Apply Fonts
    TextUtils.overrideFonts(this, findViewById(android.R.id.content));

    final Typeface faTypeFace = Typeface.createFromAsset(getAssets(), "FontAwesome.ttf");
    final int[] visibleLogos;
    final int[] goneLogos;
    if (AppConstants.FULL_WIDTH_HEADERS) {
        visibleLogos = FULL_WIDTH_ROGERTHAT_LOGOS;
        goneLogos = NORMAL_WIDTH_ROGERTHAT_LOGOS;
        View viewFlipper = findViewById(R.id.registration_viewFlipper);
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) viewFlipper.getLayoutParams();
        params.setMargins(0, 0, 0, 0);
    } else {
        visibleLogos = NORMAL_WIDTH_ROGERTHAT_LOGOS;
        goneLogos = FULL_WIDTH_ROGERTHAT_LOGOS;
    }

    for (int id : visibleLogos)
        findViewById(id).setVisibility(View.VISIBLE);
    for (int id : goneLogos)
        findViewById(id).setVisibility(View.GONE);

    handleScreenOrientation(getResources().getConfiguration().orientation);

    ScrollView rc = (ScrollView) findViewById(R.id.registration_container);
    Resources resources = getResources();
    if (CloudConstants.isRogerthatApp()) {
        rc.setBackgroundColor(resources.getColor(R.color.mc_page_dark));
    } else {
        rc.setBackgroundColor(resources.getColor(R.color.mc_homescreen_background));
    }

    TextView rogerthatWelcomeTextView = (TextView) findViewById(R.id.rogerthat_welcome);

    TextView tosTextView = (TextView) findViewById(R.id.registration_tos);
    Typeface FONT_THIN_ITALIC = Typeface.createFromAsset(getAssets(), "fonts/lato_light_italic.ttf");
    tosTextView.setTypeface(FONT_THIN_ITALIC);
    tosTextView.setTextColor(ContextCompat.getColor(RegistrationActivity2.this, R.color.mc_words_color));

    Button agreeBtn = (Button) findViewById(R.id.registration_agree_tos);

    TextView tvRegistration = (TextView) findViewById(R.id.registration);
    tvRegistration.setText(getString(R.string.registration_city_app_sign_up, getString(R.string.app_name)));

    mEnterEmailAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.registration_enter_email);

    if (CloudConstants.isEnterpriseApp()) {
        rogerthatWelcomeTextView
                .setText(getString(R.string.rogerthat_welcome_enterprise, getString(R.string.app_name)));
        tosTextView.setVisibility(View.GONE);
        agreeBtn.setText(R.string.start_registration);
        mEnterEmailAutoCompleteTextView.setHint(R.string.registration_enter_email_hint_enterprise);
    } else {
        rogerthatWelcomeTextView
                .setText(getString(R.string.registration_welcome_text, getString(R.string.app_name)));

        tosTextView.setText(Html.fromHtml(
                "<a href=\"" + CloudConstants.TERMS_OF_SERVICE_URL + "\">" + tosTextView.getText() + "</a>"));
        tosTextView.setMovementMethod(LinkMovementMethod.getInstance());

        agreeBtn.setText(R.string.registration_btn_agree_tos);

        mEnterEmailAutoCompleteTextView.setHint(R.string.registration_enter_email_hint);
    }

    agreeBtn.getBackground().setColorFilter(Message.GREEN_BUTTON_COLOR, PorterDuff.Mode.MULTIPLY);
    agreeBtn.setOnClickListener(new SafeViewOnClickListener() {
        @Override
        public void safeOnClick(View v) {
            sendRegistrationStep(RegistrationWizard2.REGISTRATION_STEP_AGREED_TOS);
            mWiz.proceedToNextPage();

        }
    });

    initLocationUsageStep(faTypeFace);

    View.OnClickListener emailLoginListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendRegistrationStep(RegistrationWizard2.REGISTRATION_STEP_EMAIL_LOGIN);
            mWiz.proceedToNextPage();
        }
    };

    findViewById(R.id.login_via_email).setOnClickListener(emailLoginListener);

    Button facebookButton = (Button) findViewById(R.id.login_via_fb);

    View.OnClickListener facebookLoginListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Check network connectivity
            if (!mService.getNetworkConnectivityManager().isConnected()) {
                UIUtils.showNoNetworkDialog(RegistrationActivity2.this);
                return;
            }

            sendRegistrationStep(RegistrationWizard2.REGISTRATION_STEP_FACEBOOK_LOGIN);

            FacebookUtils.ensureOpenSession(RegistrationActivity2.this,
                    AppConstants.PROFILE_SHOW_GENDER_AND_BIRTHDATE
                            ? Arrays.asList("email", "user_friends", "user_birthday")
                            : Arrays.asList("email", "user_friends"),
                    PermissionType.READ, new Session.StatusCallback() {
                        @Override
                        public void call(Session session, SessionState state, Exception exception) {
                            if (session != Session.getActiveSession()) {
                                session.removeCallback(this);
                                return;
                            }

                            if (exception != null) {
                                session.removeCallback(this);
                                if (!(exception instanceof FacebookOperationCanceledException)) {
                                    L.bug("Facebook SDK error during registration", exception);
                                    AlertDialog.Builder builder = new AlertDialog.Builder(
                                            RegistrationActivity2.this);
                                    builder.setMessage(R.string.error_please_try_again);
                                    builder.setPositiveButton(R.string.rogerthat, null);
                                    AlertDialog dialog = builder.create();
                                    dialog.show();
                                }
                            } else if (session.isOpened()) {
                                session.removeCallback(this);
                                if (session.getPermissions().contains("email")) {
                                    registerWithAccessToken(session.getAccessToken());
                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(
                                            RegistrationActivity2.this);
                                    builder.setMessage(R.string.facebook_registration_email_missing);
                                    builder.setPositiveButton(R.string.rogerthat, null);
                                    AlertDialog dialog = builder.create();
                                    dialog.show();
                                }
                            }
                        }
                    }, false);
        }

        ;
    };

    facebookButton.setOnClickListener(facebookLoginListener);

    final Button getAccountsButton = (Button) findViewById(R.id.get_accounts);
    if (configureEmailAutoComplete()) {
        // GET_ACCOUNTS permission is granted
        getAccountsButton.setVisibility(View.GONE);
    } else {
        getAccountsButton.setTypeface(faTypeFace);
        getAccountsButton.setOnClickListener(new SafeViewOnClickListener() {
            @Override
            public void safeOnClick(View v) {
                ActivityCompat.requestPermissions(RegistrationActivity2.this,
                        new String[] { Manifest.permission.GET_ACCOUNTS }, PERMISSION_REQUEST_GET_ACCOUNTS);
            }
        });
    }

    mEnterPinEditText = (EditText) findViewById(R.id.registration_enter_pin);

    mEnterPinEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == PIN_LENGTH)
                onPinEntered();
        }
    });

    Button requestNewPinButton = (Button) findViewById(R.id.registration_request_new_pin);
    requestNewPinButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mWiz.setEmail(null);
            hideNotification();
            mWiz.reInit();
            mWiz.goBackToPrevious();
            mEnterEmailAutoCompleteTextView.setText("");
        }
    });

    mWiz = RegistrationWizard2.getWizard(mService);
    mWiz.setFlipper((ViewFlipper) findViewById(R.id.registration_viewFlipper));
    setFinishHandler();
    addAgreeTOSHandler();
    addIBeaconUsageHandler();
    addChooseLoginMethodHandler();
    addEnterPinHandler();
    mWiz.run();
    mWiz.setDeviceId(Installation.id(this));

    handleEnterEmail();

    if (mWiz.getBeaconRegions() != null && mBeaconManager == null) {
        bindBeaconManager();
    }

    if (CloudConstants.USE_GCM_KICK_CHANNEL && GoogleServicesUtils.checkPlayServices(this, true)) {
        GoogleServicesUtils.registerGCMRegistrationId(mService, new GCMRegistrationIdFoundCallback() {
            @Override
            public void idFound(String registrationId) {
                mGCMRegistrationId = registrationId;
            }
        });
    }
}

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

private void AddLogMessage(final String Message) {
    addMessageProgressDialog = new ProgressDialog(this);
    addMessageProgressDialog.setTitle("Contacting Zenoss");
    addMessageProgressDialog.setMessage("Please wait:\nProcessing Event Log Updates");
    addMessageProgressDialog.show();/*from   w  ww .j ava2s .  co  m*/

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

            if (msg.what == 1) {
                try {
                    /*String[] tmp = LogEntries.clone();
                    final int NewArrlength = tmp.length + 1;
                    LogEntries = new String[NewArrlength];
                            
                    LogEntries[0] = settings.getString("userName", "") + " wrote " + Message + "\nAt: Just now";*/

                    /*for (int i = 1; i < NewArrlength; ++i) //
                    {
                       LogEntries[i] = tmp[(i -1)];
                    }
                    tmp = null;//help out the GC
                          ((ListView) findViewById(R.id.LogList)).setAdapter(new ArrayAdapter<String>(ViewZenossEvent.this, R.layout.search_simple,LogEntries));*/

                    TextView newLog = new TextView(ViewZenossEvent.this);
                    newLog.setText(Html.fromHtml("<strong>" + settings.getString("userName", "")
                            + "</strong> wrote " + Message + "\n<br/><strong>At:</strong> Just now"));
                    newLog.setPadding(0, 6, 0, 6);
                    ((LinearLayout) findViewById(R.id.LogList)).addView(newLog);
                } catch (Exception e) {
                    BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "AddMessageProgressHandler", e);
                    Toast.makeText(ViewZenossEvent.this,
                            "The log message was successfully sent to Zenoss but an error occured when updating the UI",
                            Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(ViewZenossEvent.this, "An error was encountered adding your message to the log",
                        Toast.LENGTH_LONG).show();
            }

        }
    };

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

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

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

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

    addLogMessageThread.start();
}

From source file:in.codehex.arrow.MainActivity.java

/**
 * Parse the JSON object and create an array list of the instructions
 *
 * @param response the json response from the google directions API
 */// w  w w. ja v a  2 s .c  o  m
private void processDirectionData(String response) {
    directionItemList.clear();
    try {
        JSONObject json = new JSONObject(response);
        JSONArray array = json.getJSONArray("routes");
        JSONObject routes = array.getJSONObject(0);
        JSONArray legs = routes.getJSONArray("legs");
        JSONObject jsonObject = legs.getJSONObject(0);
        String source = jsonObject.getString("start_address");
        String destination = jsonObject.getString("end_address");
        JSONArray steps = jsonObject.getJSONArray("steps");
        for (int i = 0; i < steps.length(); i++) {
            JSONObject object = steps.getJSONObject(i);
            JSONObject distance = object.getJSONObject("distance");
            String mDistance = distance.getString("text");
            JSONObject duration = object.getJSONObject("duration");
            String mDuration = duration.getString("text");
            String mInstruction = object.getString("html_instructions");
            String data = "Instruction: " + Html.fromHtml(mInstruction) + ". Distance: " + mDistance
                    + ". Duration: " + mDuration + ".";
            JSONObject startLocation = object.getJSONObject("start_location");
            double startLat = startLocation.getDouble("lat");
            double startLng = startLocation.getDouble("lng");
            JSONObject endLocation = object.getJSONObject("end_location");
            double endLat = endLocation.getDouble("lat");
            double endLng = endLocation.getDouble("lng");
            JSONObject polyline = object.getJSONObject("polyline");
            String points = polyline.getString("points");
            directionItemList.add(new DirectionItem(data, startLat, startLng, endLat, endLng, points, false));
            updateRecentSearch(source, destination);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (directionItemList.isEmpty())
        textToSpeech.speak("No direction instruction is available", TextToSpeech.QUEUE_FLUSH, null, null);
}

From source file:com.bionx.res.DashMainActivity.java

@SuppressWarnings("deprecation")
@Override//from   w  ww  .  j av a  2s  .  c o m
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case 11:
        // Create our About Dialog
        TextView aboutMsg = new TextView(this);
        aboutMsg.setMovementMethod(LinkMovementMethod.getInstance());
        aboutMsg.setPadding(30, 30, 30, 30);
        aboutMsg.setText(Html.fromHtml(
                "To view more information about the development of the Bionx Dashboard, Continue into the Information Center, If you don't care much for license and authors, click 'Proceed'."));

        Builder builder = new AlertDialog.Builder(this);
        builder.setView(aboutMsg)
                .setTitle(Html.fromHtml("Dashboard <b><font color='"
                        + getResources().getColor(R.color.holo_blue) + "'>Info</font></b>"))
                .setIcon(R.drawable.ic_launcher).setCancelable(true)
                .setPositiveButton("Information Drawer", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent dialog_intent = new Intent(getBaseContext(), InformationDrawer.class);
                        startActivity(dialog_intent);
                    }
                }).setNegativeButton("Proceed", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(), "Bionx Dashboard", Toast.LENGTH_LONG).show();
                    }
                });
        return builder.create();
    }
    return super.onCreateDialog(id);
}

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

private void share() {

    TextView title = (TextView) findViewById(R.id.title);
    String sTitle = title.getText().toString();
    Intent share = new Intent(this, ShareBarActivity.class);
    share.putExtra("summaryF", "" + Html.fromHtml("<h2>" + sTitle + "</h2><br>" + pText));
    share.putExtra("summaryT", sTitle);

    this.startActivityForResult(share, 0);

}

From source file:cgeo.geocaching.connector.gc.GCParser.java

static SearchResult parseCacheFromText(final String pageIn, final CancellableHandler handler) {
    CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_details);

    if (StringUtils.isBlank(pageIn)) {
        Log.e("GCParser.parseCache: No page given");
        return null;
    }/*from   w  ww .  j ava 2  s  .co m*/

    final SearchResult searchResult = new SearchResult();

    if (pageIn.contains(GCConstants.STRING_UNPUBLISHED_OTHER)
            || pageIn.contains(GCConstants.STRING_UNPUBLISHED_FROM_SEARCH)) {
        searchResult.setError(StatusCode.UNPUBLISHED_CACHE);
        return searchResult;
    }

    if (pageIn.contains(GCConstants.STRING_PREMIUMONLY_1)
            || pageIn.contains(GCConstants.STRING_PREMIUMONLY_2)) {
        searchResult.setError(StatusCode.PREMIUM_ONLY);
        return searchResult;
    }

    final String cacheName = Html.fromHtml(TextUtils.getMatch(pageIn, GCConstants.PATTERN_NAME, true, ""))
            .toString();
    if (GCConstants.STRING_UNKNOWN_ERROR.equalsIgnoreCase(cacheName)) {
        searchResult.setError(StatusCode.UNKNOWN_ERROR);
        return searchResult;
    }

    // first handle the content with line breaks, then trim everything for easier matching and reduced memory consumption in parsed fields
    String personalNoteWithLineBreaks = "";
    MatcherWrapper matcher = new MatcherWrapper(GCConstants.PATTERN_PERSONALNOTE, pageIn);
    if (matcher.find()) {
        personalNoteWithLineBreaks = matcher.group(1).trim();
    }

    final String page = TextUtils.replaceWhitespace(pageIn);

    final Geocache cache = new Geocache();
    cache.setDisabled(page.contains(GCConstants.STRING_DISABLED));

    cache.setArchived(page.contains(GCConstants.STRING_ARCHIVED));

    cache.setPremiumMembersOnly(TextUtils.matches(page, GCConstants.PATTERN_PREMIUMMEMBERS));

    cache.setFavorite(TextUtils.matches(page, GCConstants.PATTERN_FAVORITE));

    // cache geocode
    cache.setGeocode(TextUtils.getMatch(page, GCConstants.PATTERN_GEOCODE, true, cache.getGeocode()));

    // cache id
    cache.setCacheId(TextUtils.getMatch(page, GCConstants.PATTERN_CACHEID, true, cache.getCacheId()));

    // cache guid
    cache.setGuid(TextUtils.getMatch(page, GCConstants.PATTERN_GUID, true, cache.getGuid()));

    // name
    cache.setName(cacheName);

    // owner real name
    cache.setOwnerUserId(Network
            .decode(TextUtils.getMatch(page, GCConstants.PATTERN_OWNER_USERID, true, cache.getOwnerUserId())));

    cache.setUserModifiedCoords(false);

    String tableInside = page;

    final int pos = tableInside.indexOf(GCConstants.STRING_CACHEDETAILS);
    if (pos == -1) {
        Log.e("GCParser.parseCache: ID \"cacheDetails\" not found on page");
        return null;
    }

    tableInside = tableInside.substring(pos);

    if (StringUtils.isNotBlank(tableInside)) {
        // cache terrain
        String result = TextUtils.getMatch(tableInside, GCConstants.PATTERN_TERRAIN, true, null);
        if (result != null) {
            try {
                cache.setTerrain(Float.parseFloat(StringUtils.replaceChars(result, '_', '.')));
            } catch (final NumberFormatException e) {
                Log.e("Error parsing terrain value", e);
            }
        }

        // cache difficulty
        result = TextUtils.getMatch(tableInside, GCConstants.PATTERN_DIFFICULTY, true, null);
        if (result != null) {
            try {
                cache.setDifficulty(Float.parseFloat(StringUtils.replaceChars(result, '_', '.')));
            } catch (final NumberFormatException e) {
                Log.e("Error parsing difficulty value", e);
            }
        }

        // owner
        cache.setOwnerDisplayName(StringEscapeUtils.unescapeHtml4(TextUtils.getMatch(tableInside,
                GCConstants.PATTERN_OWNER_DISPLAYNAME, true, cache.getOwnerDisplayName())));

        // hidden
        try {
            String hiddenString = TextUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDEN, true, null);
            if (StringUtils.isNotBlank(hiddenString)) {
                cache.setHidden(GCLogin.parseGcCustomDate(hiddenString));
            }
            if (cache.getHiddenDate() == null) {
                // event date
                hiddenString = TextUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDENEVENT, true, null);
                if (StringUtils.isNotBlank(hiddenString)) {
                    cache.setHidden(GCLogin.parseGcCustomDate(hiddenString));
                }
            }
        } catch (final ParseException e) {
            // failed to parse cache hidden date
            Log.w("GCParser.parseCache: Failed to parse cache hidden (event) date");
        }

        // favorite
        try {
            cache.setFavoritePoints(Integer
                    .parseInt(TextUtils.getMatch(tableInside, GCConstants.PATTERN_FAVORITECOUNT, true, "0")));
        } catch (final NumberFormatException e) {
            Log.e("Error parsing favorite count", e);
        }

        // cache size
        cache.setSize(CacheSize.getById(
                TextUtils.getMatch(tableInside, GCConstants.PATTERN_SIZE, true, CacheSize.NOT_CHOSEN.id)));
    }

    // cache found
    cache.setFound(TextUtils.matches(page, GCConstants.PATTERN_FOUND)
            || TextUtils.matches(page, GCConstants.PATTERN_FOUND_ALTERNATIVE));

    // cache found date
    try {
        final String foundDateString = TextUtils.getMatch(page, GCConstants.PATTERN_FOUND_DATE, true, null);
        if (StringUtils.isNotBlank(foundDateString)) {
            cache.setVisitedDate(GCLogin.parseGcCustomDate(foundDateString).getTime());
        }
    } catch (final ParseException e) {
        // failed to parse cache found date
        Log.w("GCParser.parseCache: Failed to parse cache found date");
    }

    // cache type
    cache.setType(CacheType
            .getByPattern(TextUtils.getMatch(page, GCConstants.PATTERN_TYPE, true, cache.getType().id)));

    // on watchlist
    cache.setOnWatchlist(TextUtils.matches(page, GCConstants.PATTERN_WATCHLIST));

    // latitude and longitude. Can only be retrieved if user is logged in
    String latlon = TextUtils.getMatch(page, GCConstants.PATTERN_LATLON, true, "");
    if (StringUtils.isNotEmpty(latlon)) {
        try {
            cache.setCoords(new Geopoint(latlon));
            cache.setReliableLatLon(true);
        } catch (final Geopoint.GeopointException e) {
            Log.w("GCParser.parseCache: Failed to parse cache coordinates", e);
        }
    }

    // cache location
    cache.setLocation(TextUtils.getMatch(page, GCConstants.PATTERN_LOCATION, true, ""));

    // cache hint
    final String result = TextUtils.getMatch(page, GCConstants.PATTERN_HINT, false, null);
    if (result != null) {
        // replace linebreak and paragraph tags
        final String hint = GCConstants.PATTERN_LINEBREAK.matcher(result).replaceAll("\n");
        cache.setHint(StringUtils.replace(hint, "</p>", "").trim());
    }

    cache.checkFields();

    // cache personal note
    cache.setPersonalNote(personalNoteWithLineBreaks);

    // cache short description
    cache.setShortDescription(TextUtils.getMatch(page, GCConstants.PATTERN_SHORTDESC, true, ""));

    // cache description
    cache.setDescription(TextUtils.getMatch(page, GCConstants.PATTERN_DESC, true, ""));

    // cache attributes
    try {
        final String attributesPre = TextUtils.getMatch(page, GCConstants.PATTERN_ATTRIBUTES, true, null);
        if (null != attributesPre) {
            final MatcherWrapper matcherAttributesInside = new MatcherWrapper(
                    GCConstants.PATTERN_ATTRIBUTESINSIDE, attributesPre);

            final ArrayList<String> attributes = new ArrayList<String>();
            while (matcherAttributesInside.find()) {
                if (matcherAttributesInside.groupCount() > 1
                        && !matcherAttributesInside.group(2).equalsIgnoreCase("blank")) {
                    // by default, use the tooltip of the attribute
                    String attribute = matcherAttributesInside.group(2).toLowerCase(Locale.US);

                    // if the image name can be recognized, use the image name as attribute
                    final String imageName = matcherAttributesInside.group(1).trim();
                    if (StringUtils.isNotEmpty(imageName)) {
                        final int start = imageName.lastIndexOf('/');
                        final int end = imageName.lastIndexOf('.');
                        if (start >= 0 && end >= 0) {
                            attribute = imageName.substring(start + 1, end).replace('-', '_')
                                    .toLowerCase(Locale.US);
                        }
                    }
                    attributes.add(attribute);
                }
            }
            cache.setAttributes(attributes);
        }
    } catch (final RuntimeException e) {
        // failed to parse cache attributes
        Log.w("GCParser.parseCache: Failed to parse cache attributes");
    }

    // cache spoilers
    try {
        if (CancellableHandler.isCancelled(handler)) {
            return null;
        }
        CancellableHandler.sendLoadProgressDetail(handler,
                R.string.cache_dialog_loading_details_status_spoilers);

        final MatcherWrapper matcherSpoilersInside = new MatcherWrapper(GCConstants.PATTERN_SPOILER_IMAGE,
                page);

        while (matcherSpoilersInside.find()) {
            // the original spoiler URL (include .../display/... contains a low-resolution image
            // if we shorten the URL we get the original-resolution image
            final String url = matcherSpoilersInside.group(1).replace("/display", "");

            String title = null;
            if (matcherSpoilersInside.group(3) != null) {
                title = matcherSpoilersInside.group(3);
            }
            String description = null;
            if (matcherSpoilersInside.group(4) != null) {
                description = matcherSpoilersInside.group(4);
            }
            cache.addSpoiler(new Image(url, title, description));
        }
    } catch (final RuntimeException e) {
        // failed to parse cache spoilers
        Log.w("GCParser.parseCache: Failed to parse cache spoilers");
    }

    // cache inventory
    try {
        cache.setInventoryItems(0);

        final MatcherWrapper matcherInventory = new MatcherWrapper(GCConstants.PATTERN_INVENTORY, page);
        if (matcherInventory.find()) {
            if (cache.getInventory() == null) {
                cache.setInventory(new ArrayList<Trackable>());
            }

            if (matcherInventory.groupCount() > 1) {
                final String inventoryPre = matcherInventory.group(2);

                if (StringUtils.isNotBlank(inventoryPre)) {
                    final MatcherWrapper matcherInventoryInside = new MatcherWrapper(
                            GCConstants.PATTERN_INVENTORYINSIDE, inventoryPre);

                    while (matcherInventoryInside.find()) {
                        if (matcherInventoryInside.groupCount() > 0) {
                            final Trackable inventoryItem = new Trackable();
                            inventoryItem.setGuid(matcherInventoryInside.group(1));
                            inventoryItem.setName(matcherInventoryInside.group(2));

                            cache.getInventory().add(inventoryItem);
                            cache.setInventoryItems(cache.getInventoryItems() + 1);
                        }
                    }
                }
            }
        }
    } catch (final RuntimeException e) {
        // failed to parse cache inventory
        Log.w("GCParser.parseCache: Failed to parse cache inventory (2)");
    }

    // cache logs counts
    try {
        final String countlogs = TextUtils.getMatch(page, GCConstants.PATTERN_COUNTLOGS, true, null);
        if (null != countlogs) {
            final MatcherWrapper matcherLog = new MatcherWrapper(GCConstants.PATTERN_COUNTLOG, countlogs);

            while (matcherLog.find()) {
                final String typeStr = matcherLog.group(1);
                final String countStr = getNumberString(matcherLog.group(2));

                if (StringUtils.isNotBlank(typeStr) && LogType.UNKNOWN != LogType.getByIconName(typeStr)
                        && StringUtils.isNotBlank(countStr)) {
                    cache.getLogCounts().put(LogType.getByIconName(typeStr), Integer.parseInt(countStr));
                }
            }
        }
    } catch (final NumberFormatException e) {
        // failed to parse logs
        Log.w("GCParser.parseCache: Failed to parse cache log count");
    }

    // waypoints - reset collection
    cache.setWaypoints(Collections.<Waypoint>emptyList(), false);

    // add waypoint for original coordinates in case of user-modified listing-coordinates
    try {
        final String originalCoords = TextUtils.getMatch(page, GCConstants.PATTERN_LATLON_ORIG, false, null);

        if (null != originalCoords) {
            final Waypoint waypoint = new Waypoint(
                    CgeoApplication.getInstance().getString(R.string.cache_coordinates_original),
                    WaypointType.ORIGINAL, false);
            waypoint.setCoords(new Geopoint(originalCoords));
            cache.addOrChangeWaypoint(waypoint, false);
            cache.setUserModifiedCoords(true);
        }
    } catch (final Geopoint.GeopointException e) {
    }

    int wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">");
    if (wpBegin != -1) { // parse waypoints
        if (CancellableHandler.isCancelled(handler)) {
            return null;
        }
        CancellableHandler.sendLoadProgressDetail(handler,
                R.string.cache_dialog_loading_details_status_waypoints);

        String wpList = page.substring(wpBegin);

        int wpEnd = wpList.indexOf("</p>");
        if (wpEnd > -1 && wpEnd <= wpList.length()) {
            wpList = wpList.substring(0, wpEnd);
        }

        if (!wpList.contains("No additional waypoints to display.")) {
            wpEnd = wpList.indexOf("</table>");
            wpList = wpList.substring(0, wpEnd);

            wpBegin = wpList.indexOf("<tbody>");
            wpEnd = wpList.indexOf("</tbody>");
            if (wpBegin >= 0 && wpEnd >= 0 && wpEnd <= wpList.length()) {
                wpList = wpList.substring(wpBegin + 7, wpEnd);
            }

            final String[] wpItems = wpList.split("<tr");

            for (int j = 1; j < wpItems.length; j++) {
                String[] wp = wpItems[j].split("<td");

                // waypoint name
                // res is null during the unit tests
                final String name = TextUtils.getMatch(wp[6], GCConstants.PATTERN_WPNAME, true, 1,
                        CgeoApplication.getInstance().getString(R.string.waypoint), true);

                // waypoint type
                final String resulttype = TextUtils.getMatch(wp[3], GCConstants.PATTERN_WPTYPE, null);

                final Waypoint waypoint = new Waypoint(name, WaypointType.findById(resulttype), false);

                // waypoint prefix
                waypoint.setPrefix(TextUtils.getMatch(wp[4], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, true,
                        2, waypoint.getPrefix(), false));

                // waypoint lookup
                waypoint.setLookup(TextUtils.getMatch(wp[5], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, true,
                        2, waypoint.getLookup(), false));

                // waypoint latitude and longitude
                latlon = Html.fromHtml(TextUtils.getMatch(wp[7], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON,
                        false, 2, "", false)).toString().trim();
                if (!StringUtils.startsWith(latlon, "???")) {
                    waypoint.setLatlon(latlon);
                    waypoint.setCoords(new Geopoint(latlon));
                }

                j++;
                if (wpItems.length > j) {
                    wp = wpItems[j].split("<td");
                }

                // waypoint note
                waypoint.setNote(TextUtils.getMatch(wp[3], GCConstants.PATTERN_WPNOTE, waypoint.getNote()));

                cache.addOrChangeWaypoint(waypoint, false);
            }
        }
    }

    cache.parseWaypointsFromNote();

    // logs
    cache.setLogs(getLogsFromDetails(page, false));

    // last check for necessary cache conditions
    if (StringUtils.isBlank(cache.getGeocode())) {
        searchResult.setError(StatusCode.UNKNOWN_ERROR);
        return searchResult;
    }

    cache.setDetailedUpdatedNow();
    searchResult.addAndPutInCache(Collections.singletonList(cache));
    return searchResult;
}