具有多个parentColumn和entityColumn的Android房间关系

时间:2018-08-31 14:32:28

标签: android android-room android-database

假设您有一个Room数据库,其中包含两个使用外键关联的表(实体)。 (这只是一个简化的示例,因此无需提出新的数据结构:))

@Entity(tableName = "Streets", primaryKeys = {"Country", "City"})
public class Street {
...
}

@Entity(tableName = "Users",
    primaryKeys = {"Country", "City", "Name"},
    foreignKeys = @ForeignKey(entity = Street.class,
            parentColumns = {"Country", "City"},
            childColumns = {"Country", "City"},
            onDelete = CASCADE))
public class User {
...
}

如何在一次查询中从数据库检索所有信息? 下面的工作几乎与预期的一样,但是我还需要添加“城市”列,但是如何做到这一点? 如何添加多个parentColumn和EntityColumn?

@Query("SELECT * FROM Streets")
public abstract LiveData<List<PoJo>> getAllUsers();

public static class PoJo {
    @Embedded
    private Street street;
    @Relation(parentColumn = "Country", entityColumn = "Country")
    private List<User> mUsers;
}

1 个答案:

答案 0 :(得分:0)

此答案不会解决有关使用Room的问题。我们正在使用SQLite,因此需要为Room设置代码样式。这段代码在Kotlin中
首先是两个模型类ParentModel和ChildModel

data class ParentModel (
    val title : String = "",
    val children : List<ChildModel>

data class ChildModel(
    val image : Int = -1,
    val title : String = ""

) 注意:我们未使用图片,因此很容易松动
现在,两个适配器YEA父级和子级都不能创造性地命名

class ChildAdapter(private val children : List<ChildModel>)
: RecyclerView.Adapter<ChildAdapter.ViewHolder>(){

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val v =  LayoutInflater.from(parent.context)
                  .inflate(R.layout.child_recycler,parent,false)
    return ViewHolder(v)
}

override fun getItemCount(): Int {
    return children.size
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val child = children[position]
    holder.imageView.setImageResource(child.image)
    holder.textView.text = child.title
}


inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){

    val textView : TextView = itemView.child_textView
    val imageView: ImageView = itemView.child_imageView

}

}

class ParentAdapter(private val parents : List<ParentModel>) : RecyclerView.Adapter<ParentAdapter.ViewHolder>(){

private val viewPool = RecyclerView.RecycledViewPool()

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val v = LayoutInflater.from(parent.context).inflate(R.layout.parent_recycler,parent,false)
    return ViewHolder(v)
}

override fun getItemCount(): Int {
   return parents.size
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val parent = parents[position]
    holder.textView.text = parent.title
    holder.recyclerView.apply {
        layoutManager = LinearLayoutManager(holder.recyclerView.context, LinearLayout.HORIZONTAL, false)
        adapter = ChildAdapter(parent.children)
        recycledViewPool = viewPool
    }
}


inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){
    val recyclerView : RecyclerView = itemView.rv_child
    val textView:TextView = itemView.textView
}

}

关于ParentAdapter的通知,ChildAdapter必须将信息移到
现在,与XML相关的文件首先是父文件,然后是子文件

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="2dp"
card_view:cardBackgroundColor="#fff"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="4dp"
card_view:cardUseCompatPadding="true">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        style="@style/Base.TextAppearance.AppCompat.Subhead"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/rv_child"
        android:padding="20dp"
        android:text="Hello World"
        android:textColor="@color/colorAccent"
        android:textStyle="bold" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_child"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:padding="20dp"
        android:layout_marginTop="30dp"
        android:orientation="horizontal"
        tools:layout_editor_absoluteX="74dp" />

</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/child_textView"
    android:layout_width="129dp"
    android:layout_height="37dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="1dp"
    android:background="@android:color/darker_gray"
    android:padding="10dp"
    android:text="TextView"
    android:textColor="@android:color/white"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@id/child_imageView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0" />

<ImageView
    android:id="@+id/child_imageView"
    android:layout_width="126dp"
    android:layout_height="189dp"
    android:layout_marginBottom="38dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="42dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0"
    app:srcCompat="@drawable/aviator" />

以及调用SQLite代码获取数据的代码(我们尚未编写用于实现视图的Activity)

    fun getDepartments(): List<ParentModel>{
    val cursor = writableDatabase.query(DEPARTMENTS, arrayOf(ID, TITLE), null, null,
            null, null, ID)
    val list = mutableListOf<ParentModel>()
    if (cursor != null) {
        cursor.moveToFirst()
        while (!cursor.isAfterLast){
            val departmentId = cursor.getLong(cursor.getColumnIndex(ID))
            val items = getItems(departmentId)
            val d = ParentModel(cursor.getString(cursor.getColumnIndex(TITLE)), items)
            list.add(d)
            cursor.moveToNext()
        }
        cursor.close()
    }

    return list

}