Sending the Data from a RecyclerView Adapter to Fragment/Activity
//for suppose there are input textfields and ListViews in an adapter from which we have to send the data that is to be entered rather than just displaying the data.
//the following implementation would be easier.
custom ModelClass
/*firstly to send the data from an adapter to an activity or fragment we have to send ot through json format , this can be done by creating a custom model class for which we have to send the data */ package modelclass data class SalesLineitemsList( val itemsList: List<CategoryItems>, val agreedRateList:List<AgreedRate>, ) data class CategoryItems( val categoryid:Int ) data class AgreedRate( val agreedrate:String )
Adapter.kt
package adapters lateinit var sales_line_items: sales_line_items lateinit var sales_line_unit: sales_line_items_units lateinit var categoryArray:ArrayList<String> lateinit var unitArray:ArrayList<String> private lateinit var sharedPreference: SharedPreference /*then in adapter wee have to initialise those list */ var categoryids = ArrayList<CategoryItems>() var agreedrates = ArrayList<AgreedRate>() class SalesLineItemsAdapter(private var SalesItems: List<Items>, private val context: Context) : RecyclerView.Adapter<SalesLineItemsAdapter.ViewHolder>() { class ViewHolder( private val binding: SalesLineItemsCardlayoutBinding, private val context: Context, ) : RecyclerView.ViewHolder(binding.root) { fun bind(data: Items) { sharedPreference = SharedPreference(context) var agentrateText = binding.txtAgentRateCard.text.toString().trim() /* for an input text field to send the data or to append the data to the list from adapter we have to use text change listeners*/ binding.txtAgreedRateCard.addTextChangedListener(object : TextWatcher { val adapter: ArrayAdapter<String> = ArrayAdapter<String>( context, android.R.layout.simple_list_item_1 ) override fun beforeTextChanged( s: CharSequence?, start: Int, count: Int, after: Int ) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { adapter.filter.filter(s) agreedrateText = s.toString() } override fun afterTextChanged(s: Editable?) { if (agreedrateText.isNotEmpty()) { try { var aid = (agreedrateText) if(adapterPosition+1 == agreedrates.size){ agreedrates[adapterPosition] = (AgreedRate(aid)) } else { agreedrates.add(AgreedRate(aid)) //here we add the entered data to the list } } catch (e: NumberFormatException) { // Handle the case where the text cannot be parsed into a Double Log.e("NumberFormatException", "Error parsing quantity: $agreedrateText") // You can show an error message or take appropriate action here } } else { // Handle the case where the text is empty (optional) } } }) category() } fun setupSpinnerCategory(items:ArrayList<String>) { binding.txtCategoryCard.setOnClickListener { // Initialize dialog val dialog = Dialog(context) // Set custom dialog layout dialog!!.setContentView(R.layout.searchablespinnerlayout) // Set custom height and width dialog!!.window?.setLayout(1000, 1000) // Set transparent background dialog!!.window?.setBackgroundDrawableResource(R.color.light_pale_blue) // Show dialog dialog!!.show() // Initialize variables from dialog val editText = dialog!!.findViewById<EditText>(R.id.edit_text) val listView = dialog!!.findViewById<ListView>(R.id.list_view) // Initialize custom adapter // val customAdapter = CustomProductsSoinnerAdapter(items, this) val adapter: ArrayAdapter<String> = ArrayAdapter<String>( context, android.R.layout.simple_list_item_1, items ) // Set adapter listView.adapter = adapter editText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged( s: CharSequence?, start: Int, count: Int, after: Int ) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { adapter.filter.filter(s) } override fun afterTextChanged(s: Editable?) {} }) listView.setOnItemClickListener { parent, view, position, id -> binding.txtCategoryCard.text = Editable.Factory.getInstance().newEditable(adapter.getItem(position).toString()) for (i in sales_line_items.items_list) { if(i.product_name==binding.txtCategoryCard.text.toString()) { var id = (i.imasterid) categoryids.add(CategoryItems(id)) saveCategoryIds(categoryids) Units(i.imasterid) Toast.makeText(context,id.toString(),Toast.LENGTH_LONG).show() } } dialog!!.dismiss() } } } private fun saveCategoryIds(categoryIds: ArrayList<CategoryItems>) { val sharedPreferences = context.getSharedPreferences("MySharedPreferences", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() val categoryIdsJson = Gson().toJson(categoryIds) // Gson is a library for JSON serialization/deserialization editor.putString("categoryIds", categoryIdsJson) editor.apply() } }
Fragment.kt
CustomerOrderBinding.btnSubmitSalesOrder.setOnClickListener { val gson = Gson() val CategoryDataGSON:String = gson.toJson(adapters.categoryids) val AgreedRateGSON:String = gson.toJson(adapters.agreedrates) // Customer_Order( unit = UnitDataGSON.toString(), agreed_rate = AgreedRateGSON.toString(), ) // Log.d("quantities","Quantities":${adapters.qid}) // val fragmentManager = requireActivity().supportFragmentManager // fragmentManager.beginTransaction() // .replace(R.id.frameLayout,Dashboard()) // .commit() // (requireActivity() as AppCompatActivity).supportActionBar?.title = "Dashboard" // (requireActivity() as AppCompatActivity).supportActionBar?.setHomeButtonEnabled(true) // (requireActivity() as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true) // val navigationView = requireActivity().findViewById<NavigationView>(R.id.navigationView) // val menu = navigationView.menu // val dashboardItem = menu.findItem(R.id.menudashboard) // dashboardItem.isChecked = true } return root;root2 } }
Tagged: