Hi Everybody!
Can anybody please tell what toString in Android is for and how it can be used?
As example would be highly appreciated.
Thanks in Advance john
Hi Everybody!
Can anybody please tell what toString in Android is for and how it can be used?
As example would be highly appreciated.
Thanks in Advance john
Its the same as in normal Java... I use it for debugging like this:
class MyClass {
var myVar;
var myOtherVar;
public String toString() {
return "myVar: " + myVar + " | myOtherVar: " + myOtherVar;
}
}
with Log.d("TAG", myClassObject.toString());
I can log what my object contains...
thats just one of countless possibilities.
toString is not specific to android. Its a method in java's Object class, which is the superclass of every java object. 'toString' is meant for returning textual representation of an object. This is generally overridden by java classes to create a human readable string to represent that object.
Apart from many other uses, it is widely used for logging purpose so as to print the object in a readable format. Appending an object with string automatically calls the toString() of that object e.g. "abc" + myObject
will invoke 'toString' of myObject and append the returned value to "abc"
A good example of toString implementation would look like -
@Override
public String toString() {
return new StringBuilder()
.append("{Address:")
.append(" street=").append(street)
.append(", pincode=").append(pincode)
.append("}").toString();
}