0

I have an adapter code, but since I'm new to android I wrote some activity code in adapter class. Now I want to change it to the activity class.But I don't know the proper way to do it.

This is my adapter code

class OrderAdapter(
    val context: Context,
    val btn: Button,
    val res_name: TextView,
    val progress_bar: RelativeLayout,
    val order_placed: ConstraintLayout,
    val user_id: String
) : RecyclerView.Adapter<OrderAdapter.OrderViewHolder>() {
    var total = 0
    val jsonArr = JSONArray()
    var list: List<Cart_Items> = CartData(
        context,
        Cart_Items(0, "", "", "", ""), "getall"
    ).execute().get() as List<Cart_Items>

    class OrderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var finalPrice:Int = 0
        var name: TextView = itemView.findViewById<TextView>(R.id.ord_item_item_name)
        var price: TextView = itemView.findViewById<TextView>(R.id.ord_item_item_price)
        private var spinner: Spinner = itemView.findViewById<Spinner>(R.id.spinner)

                init {
            price.text = "10"
            val array: IntArray = itemView.context.resources.getIntArray(R.array.quantity)
            val intArray = arrayOfNulls<Int>(array.size)
            for (i in array.indices) {
                intArray[i] = array[i]
            }
            val adapter =
                ArrayAdapter<Int>(itemView.context, android.R.layout.simple_spinner_item, intArray)
            spinner.adapter = adapter

            spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onNothingSelected(parent: AdapterView<*>?) {
                }

                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                     val quantity = intArray[position]!!
                    val currentPrice= price.text.toString().toInt()
                     finalPrice = (currentPrice * quantity!!)
                    price.text = finalPrice.toString()

                    }

            }
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OrderViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.single_item, parent, false)
        res_name.text = "Ordering From " + list[0].itemRes
        return OrderViewHolder(view)
    }

    override fun getItemCount(): Int {
        return list.size
    }


    override fun onBindViewHolder(holder: OrderViewHolder, position: Int) {
        val data = list[position]
        holder.name.text = data.itemName
        holder.price.text = "₹ " + data.itemPrice + "/-"
        total+=data.itemPrice.toInt()
        btn.setText("Place Order ( Total : "+total+")")
        val dataOBj = JSONObject()
        dataOBj.put("food_item_id",data.item_id)
        jsonArr.put(dataOBj)
        btn.setOnClickListener {
            btn.setBackgroundResource(R.color.grey)
            Handler().postDelayed(Runnable {
                if(Connection().checkConnectivity(context)) {
                    val q = Volley.newRequestQueue(context)
                    val url = "http://13.235.250.119/v2/place_order/fetch_result/"
                    try{
                        progress_bar.visibility = View.VISIBLE
                        val jsonObj = JSONObject()
                        jsonObj.put("user_id",user_id)
                        jsonObj.put("restaurant_id",data.itemResId)
                        jsonObj.put("total_cost",total.toString())
                        jsonObj.put("food",jsonArr)
                        val jsonreq = object : JsonObjectRequest(
                            Request.Method.POST,url,jsonObj,
                            Response.Listener {
                                if(it.getJSONObject("data").getBoolean("success")){
                                    order_placed.visibility = View.VISIBLE
                                    order_placed.findViewById<Button>(R.id.ord_ok).setOnClickListener {
                                        order_placed.findViewById<Button>(R.id.ord_ok).setBackgroundResource(R.color.red)
                                        Handler().postDelayed(Runnable {
                                            if(CartData(context,Cart_Items(0,"","","",""),"deleteall").execute().get() as Boolean){
                                                order_placed.visibility = View.GONE
                                                order_placed.findViewById<Button>(R.id.ord_ok).setBackgroundResource(R.color.grey)
                                                context.startActivity(Intent(context,MainActivity::class.java))
                                            }
                                        },200)
                                    }
                                }
                            },
                            Response.ErrorListener {
                                progress_bar.visibility = View.GONE
                                context.startActivity(Intent(context,OrderPlaceActivity::class.java))
                                Toast.makeText(context,"Please Try Again Later.", Toast.LENGTH_SHORT).show()
                            }){
                            override fun getHeaders(): MutableMap<String, String> {
                                val headers = HashMap<String, String>()
                                headers["Content-type"] = "application/json"
                                headers["token"] = "c3acf1e14c21f9"
                                return headers
                            }
                        }
                        q.add(jsonreq)
                    }catch (e: Exception){
                        progress_bar.visibility = View.GONE
                        context.startActivity(Intent(context,OrderPlaceActivity::class.java))
                        Toast.makeText(context,"Please Try Again Later.", Toast.LENGTH_SHORT).show()
                    }
                }
                else{
                    Toast.makeText(context,"Please Check your Internet Connection", Toast.LENGTH_SHORT).show()
                    context.startActivity(Intent(context,OrderPlaceActivity::class.java))
                }
                btn.setBackgroundResource(R.color.colorPrimary)
            }
                ,200)

        }
    }
}

This is my Activity code:

class OrderPlaceActivity : AppCompatActivity() {
    lateinit var recl_view: RecyclerView
    lateinit var place_order_button:Button
    lateinit var ord_res_name:TextView
    lateinit var prgs:RelativeLayout
    lateinit var order_placed:ConstraintLayout
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_place_order)
        val details = getSharedPreferences("details", Context.MODE_PRIVATE)
        recl_view = findViewById(R.id.ord_recl_view)
        ord_res_name = findViewById(R.id.ord_res_name)
        prgs = findViewById(R.id.ord_prgs)
        order_placed = findViewById(R.id.ord_placed)
        place_order_button = findViewById(R.id.ord_place_order)
        recl_view.layoutManager = LinearLayoutManager(this)
        recl_view.adapter = OrderAdapter(this,place_order_button,ord_res_name,prgs,order_placed,details.getString("user_id","") as String)
    }
}

Please help me with this, how should I change the code in a proper way. I'm sorry if this is too easy to answer, but I'm new to android so please do help me.

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
yazhini
  • 57
  • 1
  • 6
  • Create a [Listener](https://stackoverflow.com/a/31671289/4168607) and after performing action just notify the adapter for changes . – ADM Jul 05 '21 at 05:07

1 Answers1

0

Make OrderAdapter inner class, then you can move some codes to Activity, and call it from OrderAdapter's code, e.g., onBindViewHolder();

inner class OrderAdapter(
    ....
)
AIMIN PAN
  • 1,563
  • 1
  • 9
  • 13