RealmResults大小返回Zero

时间:2017-12-06 13:11:12

标签: android kotlin realm

我有一点问题,我找不到任何结果。是的我也做了一些研究。

我有一个变量mResults = RealmResults<掉落> ;

这有数据,如下图所示

enter image description here

但是当我输入>> mResults.size<<它返回0。 问题是什么?顺便说一句。我在Android中使用kotlin工作。

pröblem位于RecyclerviewgetItemCöunt

ActivityMain ::::

Realm.init(this)
        val configuration = RealmConfiguration.Builder().build()
        Realm.setDefaultConfiguration(configuration)
    mRealm = Realm.getDefaultInstance()
            val results:RealmResults<Drop> = mRealm.where(Drop::class.java).findAll()

            mToolbar = findViewById<Toolbar>(R.id.toolbar)
            mRecycler = findViewById<RecyclerView>(R.id.rv_drops)
            val manager = LinearLayoutManager(this)

            mRecycler.layoutManager = manager
            mRecycler.adapter = AdapterDrops(this, results)
open class Drop : RealmObject {
private var what: String? = null
@PrimaryKey
private var added: Long? = null
private var whenT: Long? = null
private var completed: Boolean? = null

constructor(){}

constructor(what: String, added: Long, whenT: Long, completed: Boolean) : super() {
    this.what = what
    this.added = added
    this.whenT = whenT
    this.completed = completed
}


fun getWhat(): String? {
    return what
}

fun setWhat(what: String) {
    this.what = what
}


fun getAdded(): Long? {
    return added
}

fun setAdded(added: Long) {
    this.added = added
}

fun getWhenT(): Long? {
    return whenT
}

fun setWhenT(whenT: Long) {
    this.whenT = whenT
}


fun getCompleted(): Boolean? {
    return completed
}

fun setCompleted(completed: Boolean) {
    this.completed = completed
}

}

class AdapterDrops: RecyclerView.Adapter<AdapterDrops.DropHolder> {
    private var mInflater:LayoutInflater
    private var mResults:RealmResults<Drop>
    constructor(context:Context, results: RealmResults<Drop>){
        mInflater = LayoutInflater.from(context)
        mResults = results

    }

    override fun onBindViewHolder(holder: DropHolder?, position: Int) {
        val drop:Drop = mResults[position]!!
        holder!!.mTextWhat.setText(drop.getWhat())

    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): DropHolder {
        val view = mInflater.inflate(R.layout.row_drop, parent, false)
        val holder = DropHolder(view)
        return holder
    }

    override fun getItemCount(): Int {
        return mResults.size   <<<<< pröblem
    }

    class DropHolder: RecyclerView.ViewHolder {


        var mTextWhat:TextView
        constructor(itemView: View):super(itemView){
            mTextWhat = itemView.findViewById<TextView>(R.id.tv_what)

        }

    }

}

谢谢你们。

1 个答案:

答案 0 :(得分:2)

在从db

获取所有记录时尝试此操作
count()

请使用空构造函数定义Drop类。

请从活动中删除以下代码并将其粘贴到您的应用类

var mResults:OrderedRealmCollection<Drop> = Realm.getDefaultInstance().where(Drop::class.java).findAll()
在kotlin中

无需为Drop类定义getter setter方法,因此删除