Question

I am trying to replace a URL with a shortened URL inside of a String:

public void shortenMessage()
    {
        String body = composeEditText.getText().toString();
        String shortenedBody = new String();
        String [] tokens = body.split("\\s");

        // Attempt to convert each item into an URL.  
        for( String token : tokens ) 
        {
            try
            {
                Url url = as("mycompany", "someapikey").call(shorten(token));
                Log.d("SHORTENED", token + " was shortened!");
                shortenedBody = body.replace(token, url.getShortUrl());
            }
            catch(BitlyException e)
            {
                //Log.d("BitlyException", token + " could not be shortened!");

            }
        }

        composeEditText.setText(shortenedBody);
        // url.getShortUrl() -> http://bit.ly/fB05
    }

After the links are shortened, I want to print the modified string in an EditText. My EditText is not displaying my messages properly.

For example:

"I like www.google.com" should be "I like [some shortened url]" after my code executes.
Was it helpful?

Solution

In Java, strings are immutable. String.replace() returns a new string which is the result of the replacement. Thus, when you do shortenedBody = body.replace(token, url.getShortUrl()); in a loop, shortenedBody will hold the result of (only the very) last replace.

Here's a fix, using StringBuilder.

public void shortenMessage()
{
    String body = composeEditText.getText().toString();
    StringBuilder shortenedBody = new StringBuilder();
    String [] tokens = body.split("\\s");

    // Attempt to convert each item into an URL.  
    for( String token : tokens ) 
    {
        try
        {
            Url url = as("mycompany", "someapikey").call(shorten(token));
            Log.d("SHORTENED", token + " was shortened!");
            shortenedBody.append(url.getShortUrl()).append(" ");
        }
        catch(BitlyException e)
        {
            //Log.d("BitlyException", token + " could not be shortened!");

        }
    }

    composeEditText.setText(shortenedBody.toString());
    // url.getShortUrl() -> http://bit.ly/fB05
}

OTHER TIPS

You'll probably want String.replaceAll and Pattern.quote to "quote" your string before you pass it to replaceAll, which expects a regex.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top