首页 > 解决方案 > 在 kotlin 中实现 ROOM 数据库后出现错误

问题描述

摇篮(模块):

def room_ver = "2.2.5"

dependencies {
  implementation "androidx.room:room-ktx:" + room_ver
    kapt "androidx.room:room-compiler:" + room_ver
    androidTestImplementation "androidx.room:room-testing:" + room_ver
}

错误 :

在此处输入图像描述

尝试添加:

gradle (app level) 
dependencies {
   classpath "com.android.tools.build:gradle:3.1.3"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51"
}

毕业典礼:模块

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-kapt'

仪表板.kt

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnScrollChangedListener
import android.view.inputmethod.EditorInfo
import android.widget.TextView.GONE
import android.widget.TextView.OnEditorActionListener
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.ddnsoftech.mrenvois.R
import com.ddnsoftech.mrenvois.common.APIService.Const
import com.ddnsoftech.mrenvois.common.APIService.IntentKeys
import com.ddnsoftech.mrenvois.common.`interface`.BackButtonClickIntefrace
import com.ddnsoftech.mrenvois.common.helpers.UserSession
import com.ddnsoftech.mrenvois.common.util.SnackNotify
import com.ddnsoftech.mrenvois.common.util.hideKeyboard
import com.ddnsoftech.mrenvois.model.Restaurant
import com.ddnsoftech.mrenvois.view.Activities.RestaurantsDetails.ResturantsDetailsActivity
import com.ddnsoftech.mrenvois.view.Adapter.CategoryAdapter
import com.ddnsoftech.mrenvois.view.Adapter.ResturantAdapter
import com.ddnsoftech.mrenvois.view.BaseActivity.BaseActivity
import com.ddnsoftech.mrenvois.view.ServiceNotAvailable.ServiceNotAvailableActivity
import kotlinx.android.synthetic.main.filer_search_view.*
import kotlinx.android.synthetic.main.fragment_dashboard.*


// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [DashboardFragment.newInstance] factory method to
 * create an instance of this fragment.
 */

private enum class DashboardListType {
    FILTER_VIEW,HOME_VIEW
}


enum class FilterType {
    popular,promo,location
}


class DashboardFragment : Fragment(), BackButtonClickIntefrace {

    val viewModel = DashboardFragmentVM()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
//            param1 = it.getString(ARG_PARAM1)
//            param2 = it.getString(ARG_PARAM2)
        }
        hideKeyboard()
    }

    lateinit var popularRestaurantAdapter: ResturantAdapter
    lateinit var nearRestaurantAdapter: ResturantAdapter
    lateinit var categoryAdapter: CategoryAdapter


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_dashboard, container, false)
    }

    override fun onStart() {
        super.onStart()
        txtDeliveringTo.text =  "${getString(R.string.delivering_to)} ${UserSession.shared.currentAddress?.address ?: ""}"
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initialSetup()
        getHomePageData()
    }

    companion object {

        @JvmStatic
        fun newInstance() =
            DashboardFragment().apply {
//                arguments = Bundle().apply {
//                    putString(ARG_PARAM1, param1)
//                    putString(ARG_PARAM2, param2)
//                }
            }
    }

    @SuppressLint("ClickableViewAccessibility")
    fun initialSetup() {
        viewModel.clearFilter()
        popularRestaurantAdapter = ResturantAdapter(viewModel.popular_restaurant,requireActivity())
        nearRestaurantAdapter = ResturantAdapter(viewModel.near_restaurants,requireActivity(), GridLayoutManager.HORIZONTAL)
        categoryAdapter = CategoryAdapter(viewModel.categories,requireContext())


        popularRestaurantAdapter.onItemSelect = { restaurant ->
            redirectToRestaurantDetails(restaurant)
        }

        nearRestaurantAdapter.onItemSelect = { restaurant ->
            redirectToRestaurantDetails(restaurant)
        }

        categoryAdapter.onItemSelect = { index,value ->
            viewModel.restaurants.clear()
            viewModel.categories[index] = value
            getHomePageData()
        }

        val manager1 =  GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
        recyclerViewMostPopular.layoutManager = manager1


        val manager2 =   GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
        recyclerViewNearBy.layoutManager = manager2


        val manager3 =  LinearLayoutManager(requireActivity(),LinearLayoutManager.HORIZONTAL,false)

          //  GridLayoutManager(requireActivity(), 4, GridLayoutManager.HORIZONTAL, false)
        recyclerViewCategory.layoutManager = manager3

        recyclerViewMostPopular.adapter = popularRestaurantAdapter
        recyclerViewNearBy.adapter = nearRestaurantAdapter
        recyclerViewCategory.adapter = categoryAdapter


        scrollView.viewTreeObserver
            .addOnScrollChangedListener(OnScrollChangedListener {

                if (scrollView != null) {
                    val bottom: Int =
                        scrollView.getChildAt(scrollView.childCount - 1)
                            .height - scrollView.height - scrollView.scrollY
//                if (scrollView.scrollY === 0) {
//                    //top detected
//                    SnackNotify.showMessage("Reached to top",relyMain,SnackNotify.MSGType.SUCCESS)
//                }

                    if (scrollView.scrollY == 120) {
                        hideKeyboard()
                    }

                    if (bottom == 0) {
                        //bottom detected
                        if (viewModel.isFilterApplied()) {
                            getHomePageData()
                        }
                        //SnackNotify.showMessage("Reached to Bottom",relyMain,SnackNotify.MSGType.SUCCESS)
                    }
                }
            })

        swipeRefreshLayout.setOnRefreshListener {
            viewModel.restaurants.clear()
            getHomePageData()
        }

        /// Ser view handler
//        etSearchView.

        setupSearchView()
        setUpFilerView()
        reloadList()
    }

    fun redirectToRestaurantDetails(restaurant: Restaurant) {
       var intent = Intent(requireActivity(),  ResturantsDetailsActivity::class.java)
        intent.putExtra(IntentKeys.RESTAURANT,restaurant)
        activity?.startActivity(intent)
    }

    fun setUpFilerView() {
        lnrPopular.setOnClickListener { view ->
            onFilterButtonClick(view)
        }

        lnrPromos.setOnClickListener { view ->
           onFilterButtonClick(view)
        }

        lnrLocation.setOnClickListener { view ->
            onFilterButtonClick(view)
        }


        txtNearByViewAll.setOnClickListener {
            onFilterButtonClick(lnrLocation)
        }

        txtPopularViewAll.setOnClickListener {
            onFilterButtonClick(lnrPopular)
        }

        txtDeliveringTo.setOnClickListener {
            (requireActivity() as? BaseActivity)?.openSetLocation()
        }
    }

    fun setupSearchView() {
        etSearchView.setOnTouchListener(View.OnTouchListener { _ , event ->
            val DRAWABLE_RIGHT = 2
            if (event.action == MotionEvent.ACTION_UP) {
                if (event.rawX >= etSearchView.right - etSearchView.compoundDrawables[DRAWABLE_RIGHT].bounds.width()
                ) {
                    viewModel.restaurants.clear()
                    getHomePageData()
                    true
                }
            }
            false
        })


        etSearchView.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                viewModel.restaurants.clear()
                getHomePageData()
                true
            } else false
        })
//        etSearchView.doOnTextChanged { text, start, before, count ->
//        }
    }

    fun getHomePageData() {
        hideKeyboard()
        viewModel.search = etSearchView.text?.toString()
        swipeRefreshLayout.isRefreshing = true
        viewModel.getHomeData {  success,errMsg ->
            swipeRefreshLayout.isRefreshing = false
            if (success) {
                reloadList()
            }else {
                SnackNotify.showMessage(errMsg,relyMain, SnackNotify.MSGType.ERROR)
                reloadList()
            }
        }
    }

    fun getSearchData() {

    }

    fun reloadList() {
        if (viewModel.isFilterApplied()) {

            if (nearRestaurantAdapter.scrollDirection != GridLayoutManager.VERTICAL) {
                val handler = nearRestaurantAdapter.onItemSelect
                nearRestaurantAdapter = ResturantAdapter(viewModel.restaurants,requireActivity(), GridLayoutManager.VERTICAL)
                nearRestaurantAdapter.onItemSelect = handler
                val manager2 =   GridLayoutManager(requireActivity(), 1, GridLayoutManager.VERTICAL, false)
                recyclerViewNearBy.layoutManager = manager2
                recyclerViewNearBy.adapter = nearRestaurantAdapter
          }


            lnrMostPopularContainer.visibility = View.GONE
            lnrTopCategoryContainer.visibility =
                if (viewModel.categories.count() == 0) View.GONE else View.VISIBLE

            lnrNearByContainer.visibility =
                if (viewModel.restaurants.count() == 0) View.GONE else View.VISIBLE

            viewNoRecordFound.visibility =
                if (viewModel.restaurants.count() != 0) View.GONE else View.VISIBLE

            //popularRestaurantAdapter.updateList(viewModel.popular_restaurant)
            nearRestaurantAdapter.updateList(viewModel.restaurants)
            categoryAdapter.updateList(viewModel.categories)

            txtNearByTitle.text =  getString(R.string.restaurants)
            txtNearByViewAll.visibility = View.GONE
            reloadFilterTab(true)
        }else{

            if (nearRestaurantAdapter.scrollDirection != GridLayoutManager.HORIZONTAL) {
                nearRestaurantAdapter = ResturantAdapter(viewModel.near_restaurants,requireActivity(), GridLayoutManager.HORIZONTAL)
                val manager2 =   GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
                recyclerViewNearBy.layoutManager = manager2
                recyclerViewNearBy.adapter = nearRestaurantAdapter
            }

            txtNearByTitle.text =  getString(R.string.near_by)
            txtNearByViewAll.visibility = View.VISIBLE

            viewNoRecordFound.visibility =  if (viewModel.near_restaurants.count() == 0 && viewModel.popular_restaurant.count() == 0)  View.VISIBLE else  View.GONE

            lnrMostPopularContainer.visibility =
                if (viewModel.popular_restaurant.count() == 0) View.GONE else View.VISIBLE
            lnrNearByContainer.visibility =
                if (viewModel.near_restaurants.count() == 0) View.GONE else View.VISIBLE
            lnrTopCategoryContainer.visibility =
                if (viewModel.categories.count() == 0) View.GONE else View.VISIBLE
            popularRestaurantAdapter.updateList(viewModel.popular_restaurant)
            nearRestaurantAdapter.updateList(viewModel.near_restaurants)
            categoryAdapter.updateList(viewModel.categories)
            reloadFilterTab(false)
        }
    }


    fun reloadFilterTab(filterApplied:Boolean) {
        if (filterApplied && viewModel.filterType != null)
        {
             when (viewModel.filterType!!) {

                 FilterType.popular -> {
                     lnrPopular.background = resources.getDrawable(R.drawable.filter_active_border)
                     lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
                 }


                 FilterType.promo -> {
                     lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrPromos.background = resources.getDrawable(R.drawable.filter_active_border)
                     lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
                 }


                 FilterType.location -> {
                     lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrLocation.background = resources.getDrawable(R.drawable.filter_active_border)
                 }

             }
        }else{
            lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
            lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
            lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
        }

    }

    override fun onBackClicked(): Boolean{
//        TODO("Not yet implemented")
        if (viewModel.isFilterApplied())
        {
            viewModel.clearFilter()
            getHomePageData()
            return true
        }

        return false
    }


    fun onFilterButtonClick(v: View) {
       when (v) {
           lnrPopular -> {
               viewModel.filterType = if( viewModel.filterType == FilterType.popular ) null else FilterType.popular
           }

           lnrPromos -> {
               viewModel.filterType = if( viewModel.filterType == FilterType.promo ) null else FilterType.promo
           }

           lnrLocation -> {
               viewModel.filterType = if( viewModel.filterType == FilterType.location ) null else FilterType.location
           }
       }

        reloadFilterTab(viewModel.filterType != null)
        viewModel.restaurants.clear()
        getHomePageData()
    }
}

标签: androidkotlingradleandroid-room

解决方案


推荐阅读