6

How can we extract a line from a multiLine EditText ?

I tried this way, but I know that is not a good practice :

String street1 = "";
String street2 = "";
EditText streetEt = ((EditText) findViewById(R.id.street));
ExtractedText extractedText = new ExtractedText();
ExtractedTextRequest req = new ExtractedTextRequest();
int endOfLineOffset = 0;

req.hintMaxLines = 1;
streetEt.extractText(req, extractedText);
endOfLineOffset = extractedText.partialEndOffset;
street1 = extractedText.toString();
...

is there an easier way to do this like looking for \n in the string ?

5
  • I'm slightly confused, are you trying to extract the text from the TextView?
    – JuiCe
    Jun 28, 2012 at 14:51
  • Ah, ignore my answer below then :D I just reread your question sorry
    – JuiCe
    Jun 28, 2012 at 14:53
  • 1
    Actually, you can just use the getText() method, and then search for the \n in THAT string.
    – JuiCe
    Jun 28, 2012 at 14:54
  • Jack's answer seems good
    – JuiCe
    Jun 28, 2012 at 14:57
  • Possible duplicate of How do I get the text at a specific line in a TextView
    – rocknow
    Sep 16, 2017 at 7:26

3 Answers 3

12

Try using String.split(). Code example:

String multiLines = streetEt.getText().toString();
String[] streets;
String delimiter = "\n";

streets = multiLines.split(delimiter);

Now you have an array of streets.

Let's say, for example, your EditText reads "1st St.\nHighway Rd.\nUniversity Ave." (or is those 3 streets separated by line breaks, instead of you actually seeing \n). Following the code example I provided you,

  • multiLines becomes "1st St.\nHighway Rd.\nUniversity Ave."
  • streets = multiLines.split(delimiter); fills the array streets with the street names, i.e.

    • streets[0] = "1st St."
    • streets[1] = "Highway Rd."
    • streets[2] = "University Ave."
3
  • This is a much better way to accomplish this than my answer. Jun 28, 2012 at 15:07
  • I am trying to use your code to implement search functionality in an edit text in android.But I am unable to search for the next element in my array list.I have also posted a question stackoverflow.com/questions/40670878/… Nov 18, 2016 at 6:49
  • 2
    This answer is not full. User can input very long sequence and when it reaches end of current line it continues on the next one. So we can have several lines without any new line symbol. Correct answer: stackoverflow.com/a/6273546/1140997
    – rocknow
    Sep 16, 2017 at 7:23
4

Try this:

String text = streetEt.getText();

String firstLine = text.substring(0,text.indexOf("\n"));
1

Try this,

String text=editText1.getText().toString().replace("\n", " ").trim();
0

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.