Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

java - How to override `toString()` properly to get rid of hash code

I'm retrieving test data from Room, but all I get is the hash-code data, even though I override the toString() method in my @Entity class. How do I know if the override method is used at all?

I have properly set up Room with a database, repository, viewModel and view using Live-data. From onCreate I have an observer that triggers correctly, and data is shown. As expected it is has-code data. Usually I turn this into string data by overriding toString() in the @Entity class and then using it in onCreate() but it doesn't work. It still gives me the hash data.

In my @Entity class I override toString() like this:

@Override
public String toString() {
    return "MyEntity{" +
            "id=" + id +
            ", title='" + title + ''' +
            ", description='" + description + ''' +
            ", priority=" + priority +
            '}';
}

And in my onCreate() I call the Interface using:

myViewModel.getAllData().observe( this, new Observer<List<MyEntity>>() {
        @Override
        public void onChanged(@Nullable List<MyEntity> myEntities) {

            Log.d("TAG: ", "DATA CHANGED! " + myViewModel.getAllData().toString());
        }
} );

But despite using .toString() I still just get the hash data:

D/TAG:: DATA CHANGED! android.arch.lifecycle.ComputableLiveData$1@a12e85e

I expect some basic test data:

"MY FIRST OBJECT", "THIS IS MY OBJECT", 1 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are calling toString() on ComputableLiveData, you have to call toString() on myEntities which will in turn call toString() on the individual elements which are MyEntity.

myViewModel.getAllData().observe( this, new Observer<List<MyEntity>>() {
    @Override
    public void onChanged(@Nullable List<MyEntity> myEntities) {
        Log.d("TAG: ", "DATA CHANGED! " + myEntities.toString());
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...