如何正确覆盖`toString()`以摆脱哈希码 [英] How to override `toString()` properly to get rid of hash code
问题描述
我正在从 Room
检索测试数据,但我得到的只是哈希码数据,即使我覆盖了 toString()
方法在我的 >@Entity
类.我怎么知道是否使用了覆盖方法?
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?
我已经使用 database
、repository
、viewModel
和 view<正确设置了
Room
/code> 使用 Live-data
.从 onCreate 我有一个 observer
可以正确触发,并显示数据.正如预期的那样,它是 has-code
数据.通常我通过覆盖 @Entity
类中的 toString()
然后在 onCreate()<中使用它来将其转换为
string
数据/code> 但它不起作用.它仍然给我 hash
数据.
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.
在我的 @Entity
类中,我像这样覆盖了 toString()
:
In my @Entity
class I override toString()
like this:
@Override
public String toString() {
return "MyEntity{" +
"id=" + id +
", title='" + title + '\'' +
", description='" + description + '\'' +
", priority=" + priority +
'}';
}
在我的 onCreate()
中,我调用 Interface
使用:
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());
}
} );
但是尽管使用了 .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
推荐答案
您正在对 ComputableLiveData
调用 toString()
,你必须在 myEntities
上调用 toString()
,这又会在 MyEntity的各个元素上调用
toString()
代码>.
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());
}
});
这篇关于如何正确覆盖`toString()`以摆脱哈希码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!