Обработка RecyclerView notifyDataSetChange () во фрагменте A из фрагмента B (Kotlin) - PullRequest
0 голосов
/ 26 апреля 2020

Эй, у меня есть 2 фрагмента:

  1. Фрагмент A
  2. Фрагмент B

Фрагмент A

class ListFragment : Fragment() {
    var adapter: CheckupRVAdapter? = null
    private var recyclerView: RecyclerView? = null
    private lateinit var checkupHolderModel: List<CheckupHolderModel>
    private var checkupIdRes:String = ""
    private var positionRes:Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val toolbar = requireActivity().findViewById<Toolbar>(R.id.toolbar_list)
        toolbar.inflateMenu(R.menu.search_menu)
        toolbar.setOnMenuItemClickListener(this::onOptionsItemSelected)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val mainView: View = inflater.inflate(R.layout.fragment_list, container, false)
        checkupHolderModel = ArrayList<CheckupHolderModel>()
        recyclerView = mainView.findViewById(R.id.rvList) as RecyclerView
        recyclerView!!.setHasFixedSize(true)
        val mLayoutManager: RecyclerView.LayoutManager = LinearLayoutManager(activity)
        recyclerView!!.layoutManager = mLayoutManager
        recyclerView!!.itemAnimator = DefaultItemAnimator()
        adapter = CheckupRVAdapter(checkupHolderModel, requireActivity().applicationContext, object :
        recyclerView!!.adapter = adapter

        doApiCall()
        return mainView
    }

    private fun doApiCall() {
        requireActivity().runOnUiThread {
            val apiService = ApiInterface.create()
            val call = apiService.dataCheckups()
            call.enqueue(object : Callback<CheckupModel> {
                override fun onResponse(call: Call<CheckupModel>, response: retrofit2.Response<CheckupModel>?) {
                    val jsonObject = response!!.body()
                    val returnedResponse = jsonObject.status
                    if (returnedResponse!!.trim { it <= ' ' } == "200") {
                        val mDataObject: List<CheckupArrayModel> = response.body().checkups
                        for (item: CheckupArrayModel in mDataObject.iterator()) {
                            val na = CheckupHolderModel()
                            na.no = item.no!!
                            na.checkupId = item.checkupId!!
                            na.patientName = item.patientName!!
                            (checkupHolderModel as ArrayList<CheckupHolderModel>).add(na)
                        }
                        activity!!.runOnUiThread { adapter!!.notifyDataSetChanged() }
                    } else {
                        Log.d("response", response.body().status.toString())
                    }
                }

                override fun onFailure(call: Call<CheckupModel>, t: Throwable) {
                    call.cancel()
                    Log.d("response", "canceled")
                }
            })
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val destination = when (item.itemId) {
            R.id.search -> R.id.action_search_list
            else -> null
        }

        return if (destination != null) findNavController().navigate(destination).let { true }
        else super.onOptionsItemSelected(item)
    }
}

Фрагмент B

class AddFragment : Fragment(), View.OnClickListener {
    private var patientBpjsId:String? = null
    private var patientName:String? = null
    private var patientBornDate:String? = null
    private var patientYearsOld:String? = null
    private var selectedGenre :Int? = null
    private var radioGenreButton:RadioButton? = null
    private var radioButtonText:CharSequence? = null
    var patientGenre:String? = null
    private var patientAddress:String? = null
    private var patientFamilyName:String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val toolbar = requireActivity().findViewById<Toolbar>(R.id.toolbar_add)
        toolbar.inflateMenu(R.menu.search_menu)
        toolbar.setOnMenuItemClickListener(this::onOptionsItemSelected)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val mainView: View = inflater.inflate(R.layout.fragment_add, container, false)
        mainView.btnPayMethodBPJS.setOnClickListener(this)
        mainView.btnPayMethodUmum.setOnClickListener(this)

        return mainView
    }

    override fun onClick(v: View?) {
        patientBpjsId = etNoBpjs.text.toString()
        patientName = etNama.text.toString()
        patientBornDate = etBornDate.text.toString()
        patientYearsOld = etYearsOld.text.toString()
        selectedGenre = rgGenre.checkedRadioButtonId
        radioGenreButton = requireActivity().findViewById(selectedGenre!!) as RadioButton
        radioButtonText = radioGenreButton!!.text
        patientGenre = if(radioButtonText=="Laki-laki"){
            "1"
        }else{
            "2"
        }
        patientAddress = etAddress.text.toString()
        patientFamilyName = etFamily.text.toString()
        if (v == btnPayMethodBPJS) {
            doApiCall("2", patientBpjsId!!, patientName!!, patientBornDate!!, patientYearsOld!!, patientGenre!!, patientAddress!!, patientFamilyName!!)
        }
        if (v == btnPayMethodUmum) {
            doApiCall("1", patientBpjsId!!, patientName!!, patientBornDate!!, patientYearsOld!!, patientGenre!!, patientAddress!!, patientFamilyName!!)
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val destination = when (item.itemId) {
            R.id.search -> R.id.action_search_add
            else -> null
        }

        return if (destination != null) findNavController().navigate(destination).let { true }
        else super.onOptionsItemSelected(item)
    }

    private fun doApiCall(paymentMethod: String, patientBpjsId:String, patientName:String, patientBornDate:String, patientYearsOld:String, patientGenre:String, patientAddress:String, patientFamilyName:String) {
        requireActivity().runOnUiThread {

            val apiService = ApiInterface.create()
            val call = apiService.checkupRegistration("new", paymentMethod, patientBpjsId, patientName, patientBornDate, patientYearsOld, patientGenre, patientAddress, patientFamilyName)
            call.enqueue(object : Callback<RegistrationModel> {
                override fun onResponse(call: Call<RegistrationModel>, response: retrofit2.Response<RegistrationModel>?) {
                    val jsonObject = response!!.body()
                    val returnedResponse = jsonObject.status
                    Log.d("response:", response.toString())
                    if (returnedResponse!!.trim { it <= ' ' } == "200") {
                        //I wanna notifyDataSetChange from here
                    } else {
                        Log.d("response", response.body().status.toString())
                    }
                }

                override fun onFailure(call: Call<RegistrationModel>, t: Throwable) {
                    call.cancel()
                    Log.d("response", "canceled")
                }
            })
        }
    }
}

Как передать notifyDataSetChange из RecyclerView на фрагмент A, когда после выполнения чего-либо во фрагменте B.

Перед этим я уже пытался вызвать notifyDataSetChange, который я включил в onResume в Фрагмент А, но не работает, это похоже на то, что Фрагмент А не включается, когда Фрагмент А не виден или когда я посещаю Фрагмент Б.

...