0

for some reason when I run my app, instead of getting the name of the lecture, I get a bunch of random characters that show up. I'm not sure why though. Thanks in advance!

public Lecture(String lecturename) {
    this.lecturename = lecturename;
    listofwork = new ArrayList<Work>();
}

public String toString(Lecture lecture) {
    return lecture.lecturename;
    }

    /////////// IN ANOTHER ACTIVITY   /////////////////////

    Lecture test = new Lecture("TEST");
    Toast.makeText(getApplicationContext(), test.toString(), Toast.LENGTH_LONG).show();

And instead of getting a toast saying "TEST", I get whatsmymark.Lecture@41abcf8. I have a feeling its returning the actual lecture object rather than the string. However, I can't find out why cause the code is so simple.

3 Answers3

1

You are writing a toString that takes a Lecture as an argument, and calling toString() that takes no arguments. If you change your method definition to have no args, you will override the Object.toString() correctly.

public String toString() {
    return this.lecturename;
}

If you do not want to change your method definition for some reason, your other option is to call your version explicitly, but I am sure you will agree this looks a little redundant.

Lecture test = new Lecture("TEST");
Toast.makeText(getApplicationContext(), test.toString(test), Toast.LENGTH_LONG).show();
merlin2011
  • 71,677
  • 44
  • 195
  • 329
1

When you do test.toString(), you're printing the *test object itself *, not a string representing the object. Because you didn't override Object#toString() (you overloaded it instead), your object inherits this implementation:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

And that's probably not what you wanted.

What you'll need to do is put the toString() method you have inside the Lecture class, and remove its formal parameter. Then it should work.

A good idea is to put the @Override annotation on methods you intended to override. This way if you accidentally mess up the compiler should emit an error/warning letting you know.

awksp
  • 11,764
  • 4
  • 37
  • 44
0

you may want to change your code like this

public Lecture(String lecturename) {
    this.lecturename = lecturename;
    listofwork = new ArrayList<Work>();



    public String toString() {
        return this.lecturename;
    }

}
user1928596
  • 1,503
  • 16
  • 21