0

I have an array that keeps URL addresses in String format for me. Before loading URLs, I need to make sure that there is no space in strings. I wrote this code but ReplaceAll() doesn't change anything.

Please tell me what is wrong here?

public NewsFeedItemList getNewsList() {
        String str;

        for(int i=0; i<newsFeedItemList.getImage().size(); i++){
            str = newsFeedItemList.getImage().get(i);
            Log.i("before>>>", str);
            str.replaceAll(" ", "%20");
            Log.i("after<<<<", str);
            newsFeedItemList.getImage().set(i, str);
        }

        return newsFeedItemList;
    }
2
  • Actually when i test my android app, it crashed. When i checked the log it showed me that one of urls is like this: "mania.com.my/Portals/1/hazama_news 20(1).jpg" When i put it in browser, browser changed it to "mania.com.my/Portals/1/hazama_news%20(1).jpg". I put above code in somewhere in my app but nothing will change. Commented Mar 14, 2012 at 8:06
  • 1
    suggestion dont use replace method, using str = URLEncoder.encode(str) Commented Mar 14, 2012 at 8:09

6 Answers 6

7

Strings are immutable, meaning that you cannot change the contents of a String object. What you would need to do is something like

String cleanedString = str.replaceAll(" ", "%20");

The replaceAll()-Method returns the new String.

Sign up to request clarification or add additional context in comments.

Comments

2

String is immutable, so you need to assign it back like this: str = str.replaceAll(" ", "%20");

Comments

2

As already said by the other posters: String is immutable so you have to assign the return value of replaceAll to String.

Just as a hint: you should take a look at java.net.URLEncoder: http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html

This class helps you to format the url in a correct way and can handle all kinds of special characters - not only spaces.

Comments

1

You just need to replace the line

str.replaceAll(" ", "%20");

with

str=str.replaceAll(" ", "%20");

Comments

1

Updated your code with the following code,

public NewsFeedItemList getNewsList() { String str;

    for(int i=0; i<newsFeedItemList.getImage().size(); i++){
        str = newsFeedItemList.getImage().get(i);
        Log.i("before>>>", str);
        str = str.replaceAll(" ", "%20");  // I have update here
        Log.i("after<<<<", str);
        newsFeedItemList.getImage().set(i, str);
    }

    return newsFeedItemList;
}

Comments

1

suggestion dont use replace method,

using str = URLEncoder.encode(str),

sometimes not only the space and have another need changed character.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.