Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android + toString

Can anybody please tell what toString in Android is for and how it can be used?

As example would be highly appreciated.

like image 335
John Avatar asked Aug 23 '10 09:08

John


3 Answers

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();
  }
like image 99
Gopi Avatar answered Nov 23 '22 18:11

Gopi


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.

like image 32
WarrenFaith Avatar answered Nov 23 '22 19:11

WarrenFaith


class Account {

    public final String name;
    public final String email;

    public Account(String name, String email) {
        this.name = name;
        this.email = email;
    }

    @Override
    public String toString() {
        return new Gson().toJson(this);
    }

}
like image 24
JP Ventura Avatar answered Nov 23 '22 17:11

JP Ventura