5

In my android app, I am getting the String from an Edit Text and using it as a parameter to call a web service and fetch JSON data. Now, the method I use for getting the String value from Edit Text is like this :

final EditText edittext = (EditText) findViewById(R.id.search);

String k = edittext.getText().toString();

Now normally it works fine, but if we the text in Edit Text contains space then my app crashes.

for eg. - if someone types "food" in the Edit Text Box, then it's OK but if somebody types "Indian food" it crashes.

How to remove spaces and get just the String ?

4 Answers 4

23

Isn't that just Java?

String k = edittext.getText().toString().replace(" ", "");
2
  • yeah just java. I am sorry that was a little silly question.I could have just googled it.
    – Ankit
    May 11, 2011 at 7:52
  • 3
    single quotation mark('') is making error ..I use double quotation("") mark is working ..Ex : String k = edittext.getText().toString().replace(" ", "");
    – reegan29
    Sep 8, 2015 at 12:59
2

try this...

final EditText edittext = (EditText) findViewById(R.id.search);

String k = edittext.getText().toString();

String newData  = k.replaceAll(" ", "%20");

and use "newData"

1
  • your solution seems perfect, but may I ask why the stress on "new"
    – Ankit
    May 11, 2011 at 7:50
1
String email=recEmail.getText().toString().trim();
String password=recPassword.getText().toString().trim();

In the future, I highly recommend checking the Java String methods in the API. It's a lifeline to getting the most out of your Java environment.

-1

You can easily remove all white spaces using something like this. But you'll face another serious problem if you just do that. For example if you have input

String input1 = "aa bb cc"; // output aabbcc
String input2 = "a abbcc";  // output aabbcc
String input3 = "aabb cc";  // output aabbcc

One solution will be to fix your application to accept white spaces in input string or use some other literal to replace the white spaces. If you are using only alphanumeric values you do something like this

String input1 = "aa bb cc"; // aa_bb_cc
String input2 = "a abbcc";  //a_abbcc
String input3 = "aabb cc";  //aabb_cc

And after all if you are don' caring about the loose of information you can use any approach you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.