简体   繁体   中英

Android how to get a String from the TextView to a String

I know how to take integer value to string like

String s = st.getText().toString(0;

but my question is how we will take for a character... suppose the value ofa textView txt1 = 'A' so how we will take the value to a string str1..

String str1 = txt1.getText().toString();

is it correct....?

TextView.getText() return java.lang.CharSequence , and ideally you should be able to apply toString() to get the String value. But, however,

from CharSequence java doc

This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. It is therefore inappropriate to use arbitrary CharSequence instances as elements in a set or as keys in a map.

CharSequence is an interface( though toString() appears as declared), it should work provided the CharSequence implementer did their job properly. To avoid any suprises, you can try a different approch

final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();
String str1 = txt1.getText().toString();

Yes. It's the right answer to get the string value from string .

If getText() already returns a String , your job is already done for you. It's a string to begin with.

If you absolutely must create a String from a single char value, you can do so with the constructor that takes a char[] as an argument: new String(new char[] {value}) .

If, as Satheesh stated above, it returns a CharSequence , there is also a String constructor that takes that as a parameter. Thus, it may be best to declare a new String(txt1.getText()) rather than relying on the implementation of the returned CharSequence 's toString() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM