Как выполнять вычисления при изменении фокуса полей в Koltin

#android #kotlin

#Android #kotlin

Вопрос:

Доброе утро, братья. Я работаю над формой Android в Koltin, которая сохранит данные в MySQL. Проблема, с которой я сталкиваюсь, заключается в том, как я могу сохранить вычисленные данные в поле EditText при вводе данных. Я попытался добавить вычисление в экземпляр oCreate, но сбой намерения приводит к возникновению исключения с нулевой точкой, поскольку созданная форма содержит пустые значения. Мой код добавлен ниже. Любая помощь будет оценена по достоинству. Спасибо.

Я пытаюсь вычислить значение стоимости проекта * ITRation / 100 и установить значение editTextITAMount, но я не могу этого сделать.

 class ProjectActivity : AppCompatActivity() {

    //edittext and spinner
    private var editTextProjectName: EditText? = null
    private var spinnerProjectType: Spinner? = null
    private var editTextDepartment: EditText? = null
    private var editTextDateAwarded: EditText? = null
    private var editTextProjectLocation: EditText? = null
    private var editTextProjectCity: EditText? = null
    private var editTextProjectDistrict: EditText? = null
    private var spinnerJointVenture: Spinner? = null
    private var editTextJointVentureCoy: EditText? = null
    private var spinnerProjectStatus: Spinner? = null
    private var editTextProjectCost: EditText? = null
    private var spinnerITRatio: Spinner? = null
    private var editTextITAmount: EditText? = null
    private var spinnerGSTBST: Spinner? = null
    private var editTextGSTBSTAmount: EditText? = null






    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_project)

        //getting it from xml
        editTextProjectName = findViewById(R.id.editTextProjectName) as EditText
        spinnerProjectType = findViewById(R.id.spinnerProjectType) as Spinner
        editTextDepartment = findViewById(R.id.editTextDepartment) as EditText
        val mPickTimeBtn = findViewById<ImageButton>(R.id.imageButton)
        editTextDateAwarded = findViewById(R.id.editTextDateAwarded) as EditText
        editTextProjectLocation = findViewById(R.id.editTextProjectLocation) as EditText
        editTextProjectCity = findViewById(R.id.editTextProjectCity) as EditText
        editTextProjectDistrict = findViewById(R.id.editTextProjectDistrict) as EditText
        spinnerJointVenture = findViewById(R.id.spinnerJointVenture) as Spinner
        editTextJointVentureCoy = findViewById(R.id.editTextJointVentureCoy) as EditText
        spinnerProjectStatus = findViewById(R.id.spinnerProjectStatus) as Spinner
        editTextProjectCost = findViewById(R.id.editTextProjectCost) as EditText
        spinnerITRatio = findViewById(R.id.spinnerITRatio) as Spinner
        editTextITAmount = findViewById(R.id.editTextITAmount) as EditText
        spinnerGSTBST = findViewById(R.id.spinnerGSTBST) as Spinner
        editTextGSTBSTAmount = findViewById(R.id.editTextGSBSTAmount) as EditText



        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH)
        val day = c.get(Calendar.DAY_OF_MONTH)

        mPickTimeBtn.setOnClickListener {

            val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                // Display Selected date in TextView
                editTextDateAwarded!!.setText(""   dayOfMonth   "/"   month   "/"   year)
            }, year, month, day)
            dpd.show()

        }
        //adding a click listener to button
        this.findViewById<Button>(R.id.buttonAddProject).setOnClickListener { addProject() }

        //in the second button click
        //opening the activity to display all the artist
        //it will give error as we dont have this activity so remove this part for now to run the app
    }

    private fun calculation() {

    }

    //adding a new record to database
    private fun addProject() {
        //getting the record values
        val projectName = editTextProjectName?.text.toString()
        val projectType = spinnerProjectType?.selectedItem.toString()
        val department = editTextDepartment?.text.toString()
        val dateAwarded = editTextDateAwarded?.text.toString()
        val projectLocation = editTextProjectLocation?.text.toString()
        val projectCity = editTextProjectCity?.text.toString()
        val projectDistrict = editTextProjectDistrict?.text.toString()
        val jointVenture = spinnerJointVenture?.selectedItem.toString()
        val jointVentureWith = editTextJointVentureCoy?.text.toString()
        val projectStatus = spinnerProjectStatus?.selectedItem.toString()
        val projectCost= editTextProjectCost?.text.toString()
        val ITRatio = spinnerITRatio?.selectedItem.toString()
        val ITAmount= editTextITAmount?.text.toString()
        val GSTBST = spinnerGSTBST?.selectedItem.toString()
        val GSTBSTAmount= editTextGSTBSTAmount?.text.toString()

        val a: Int = findViewById<TextView>(R.id.editTextProjectCost).getText().toString().toInt()
        val b: Int = findViewById<Spinner>(R.id.spinnerITRatio).getSelectedItem().toString().toInt()


        val multiplication = a * b / 100
        editTextITAmount!!.setText(""   multiplication)
        //creating volley string request
        val stringRequest = object : StringRequest(
            Request.Method.POST, EndPoints.URL_ADD_PROJECT,
            Response.Listener<String> { response ->
                try {
                    val obj = JSONObject(response)
                    Toast.makeText(applicationContext, obj.getString("message"), Toast.LENGTH_LONG)
                        .show()
                    val intent = Intent(applicationContext, ProjectsViewActivity::class.java)
                    startActivity(intent)
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            },
            object : Response.ErrorListener {
                override fun onErrorResponse(volleyError: VolleyError) {
                    Toast.makeText(applicationContext, volleyError.message, Toast.LENGTH_LONG)
                        .show()
                }
            }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String> {
                val params = HashMap<String, String>()
                params.put("projectName", projectName)
                params.put("projectType", projectType)
                params.put("department", department)
                params.put("dateAwarded", dateAwarded)
                params.put("projectLocation", projectLocation)
                params.put("projectCity", projectCity)
                params.put("projectDistrict", projectDistrict)
                params.put("jointVenture", jointVenture)
                params.put("jointVentureWith", jointVentureWith)
                params.put("projectStatus", projectStatus)
                params.put("projectCost", projectCost)
                params.put("ITRatio", ITRatio)
                params.put("ITAmount", ITAmount)
                params.put("GSTBST", GSTBST)
                params.put("GSTBSTAmount", GSTBSTAmount)
                return params
            }
        }

        //adding request to queue
        VolleySingleton.instance?.addToRequestQueue(stringRequest)
    }
}
 

Комментарии:

1. пожалуйста, предоставьте полную трассировку стека и код с импортом?