Android Room Database数据未插入?

时间:2018-09-09 11:38:23

标签: android kotlin android-room android-jetpack android-paging

我正在将数据插入从网络接收的会议室数据库中。 它没有显示任何错误,也没有应用崩溃,但屏幕为空,表为空 一切正常,但是当我使用Stetho Debug Tool并查看 feed table 时,没有任何插入,任何人都可以解决并帮助我。还要查看PageListAdapter和LivePageListBuilder是否正确实现?

1. 房间数据库数据未插入 2. 分页实施

这是道方法

//Post feed item
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(feed:feed)

存储库类:

class FeedRepository (
    private val feedDao: FeedDao
){


private var lastRequestedItem = 0
private var isRequestInProgress = false
var executor = Executors.newSingleThreadExecutor()
companion object {
    lateinit var feedList:List<Feed>
    private const val DEFAULT_NETWORK_PAGE_SIZE = 50
    private const val DEAULT_DATABASE_PAGE_SIZE = 20
    private val apiClient = ApiClient.getApiClient().create(UserClient::class.java)
    // For Singleton instantiation
    @Volatile private var instance: FeedRepository? = null

    fun getInstance(feedDao: FeedDao) =
            instance ?: synchronized(this) {
                instance ?: FeedRepository(feedDao).also { instance = it }
            }
}


fun showFeed():LiveData<PagedList<feed>>{
    Timber.d("showFeed() method called")
    val dataSourceFactory = feedDao.getAllFeed()
    val boundaryCallback = FeedBoundaryCallBack(id = lastRequestedItem)
    val builder = LivePagedListBuilder(dataSourceFactory, DEAULT_DATABASE_PAGE_SIZE)
            .setBoundaryCallback(boundaryCallback)
            .build()
    return builder

}

public fun getFeedResponse() {
    Timber.i("getFeedResponse()")
    if(isRequestInProgress) return
    isRequestInProgress = true
    val call: Call<FeedResult> = apiClient.getFeed(DEFAULT_NETWORK_PAGE_SIZE,lastRequestedItem)
    call.enqueue(object :Callback<FeedResult>{
        override fun onFailure(call: Call<FeedResult>?, t: Throwable?) {
            Timber.d(t.toString())
        }

        override fun onResponse(call: Call<FeedResult>?, response: Response<FeedResult>?) {
            if(response!!.isSuccessful){
                //lastRequestedItem += response?.body()!!.size
                feedList = response?.body()!!.feedList
                for (i in feedList){
                    var name = i.username
                    var media = i.mUrl
                    var loc = i.location
                    var like = i.likesCount.toString()
                    var timeStamp = i.timeStamp
                    var id = i.id.toLong()
                    var res:feed = feed(id,name,media,timeStamp,loc,like)
                    addResponseTODB(res)
                }
                Timber.i("Successful Response -> Adding to DB")
                isRequestInProgress = false
            }else{
                when(response.code()){
                    400 -> Timber.d("Not Found 400")
                    500 -> Timber.d("Not logged in or Server broken")
                }

            }

        }
    })
}

private fun addResponseTODB(items:feed) ={
    executor.execute( {feedDao.insert(items)})
    Timber.d("Feed object Inserted into Database")
}

适配器和ViewHolder:

class FeedAdapter : PagedListAdapter<feed,FeedAdapter.ViewHolder> 
   (FeedDiffCallBack()){
  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): 
  ViewHolder {
    return ViewHolder(
            LayoutInflater.from(parent.context)
                    .inflate(R.layout.feedrow,parent,false)
    )
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val feedItem = getItem(position)
    if(feedItem != null){
        holder.bind(feedItem)
    }
}

class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView) {
    //Retrieve data
    private val username:TextView = itemView.findViewById(R.id.username_txt)
    private val userPic:ImageView = itemView.findViewById(R.id.feedImage)
    private val location:TextView = itemView.findViewById(R.id.postLocation)
    private val time:TextView = itemView.findViewById(R.id.postTime)
    private val post:ImageView = itemView.findViewById(R.id.postImage)

    fun bind(feed: feed) = with(itemView){
        //TODO:Bind Data with View
        if(feed == null) {
            post.visibility = View.GONE
        }
        else{
            showFeedData(feed)
        }

    }

    private fun showFeedData(feed: feed) {
        username.text = feed.username
        userPic.setImageURI(null)
        userPic.visibility = View.GONE
        location.text = feed.location
        time.text = feed.timeStamp.toString()
        post.setImageURI(Uri.parse(feed.mUrl))

    }

}

}

class FeedDiffCallBack : DiffUtil.ItemCallback<feed>() {
override fun areItemsTheSame(oldItem:feed, newItem: feed): Boolean {
    return oldItem?.id == newItem?.id
}

override fun areContentsTheSame(oldItem: feed, newItem: feed): Boolean {
    return oldItem == newItem
}

}

1 个答案:

答案 0 :(得分:1)

我将其发布在答案部分,因为注释部分太多了。

  

首先,确认问题是在插入中还是在在用户界面中显示中。

  1. Stetho调试工具有时无法使用,尤其是当ROOM处于WAL模式时。因此,请在仿真器中运行您的应用程序,然后使用“设备管理器”并解压缩数据库,并查看是否插入了条目。如果您在WAL模式下使用Room,那么除了DB之外,您还会注意到几个文件。您还需要将其提取出来,以查看完整的数据库。
  2. 如果插入是您的问题,那么您需要专注于此。以下是一些要寻找的地方:
    1. 检查是否调用了insert方法。
    2. 检查是否使用正确的Feed调用了insert方法
    3. 检查是否从非UI线程调用了insert方法
  

第二,确认Adaper和ViewHolder是否正确。

  1. 只需从仿真器中拉数据库,然后向其中填充一些示例数据,然后将数据库推回仿真器,即可确认Adapter和ViewHolder正常工作。