首页 > 解决方案 > Android Room: Are getters and Setters needed for @ColumnInfo fields in @Entity classes?

问题描述

I have an entity class which is not builiding. A simple MutableLiveData<String> with @TypeConverter for storage

package com.example.rough;

import androidx.lifecycle.MutableLiveData;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverter;

@Entity(tableName = "RoughEntity")
public class RoughEntity {


    @PrimaryKey(autoGenerate = true)
    public long uid;

    @ColumnInfo
    private MutableLiveData<String> str=new MutableLiveData<>("Hello");

    @TypeConverter
    public static String toString(MutableLiveData<String> str)
    {
        return  str.getValue();
    }

    @TypeConverter
    public static MutableLiveData<String> toString(String str)
    {
        return  toMutable(str);
    }

    private static <T> MutableLiveData<T> toMutable(T dat)
    {
        return new MutableLiveData<T>(dat);

    }


}

This gives the build error

error: Cannot find getter for field.
    private MutableLiveData<String> str=new MutableLiveData<>("Hello");
                                    ^

Adding a getter that returns LiveData<String> doesn't solve the issue while a getter for the MutableLiveData is beside the point -- externally the private data should only be observable.

How to solve this?

Also, if one does add a getter for the Mutable, another compile error pops up asking for a setter! This is happening(in a more sophisticated example) for every other field as well.

标签: androidandroid-room

解决方案


推荐阅读