Android房间数据库数据没有插入?

问题描述 投票:1回答:1

我将数据插入从网络接收的房间数据库。它没有显示任何错误,也没有应用程序崩溃,但屏幕是空的,表是空的一切正常,但当我使用Stetho调试工具,并查看饲料表没有插入任何东西,任何人都可以弄明白并帮助我。还要看是否正确实现了PageListAdapter和LivePageListBuilder?

1.Room DB数据没有输入2.Paging Implementation

这是Dao方法

//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
}

}

android kotlin android-room android-jetpack android-paging
1个回答
1
投票

我在答案部分发布了这个,因为评论部分太多了。

首先,确认问题是在插入还是在UI中显示。

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

其次,确认Adapter和ViewHolder是否正确。

  1. 您可以通过从仿真器中拉出数据库然后使用一些示例数据填充它并将数据库推回到仿真器来确认您的适配器和ViewHolder是否正常工作。
© www.soinside.com 2019 - 2024. All rights reserved.