package
com.gtappdevelopers.kotlingfgproject
import
android.os.Bundle
import
android.text.TextUtils
import
android.util.Log
import
android.view.View
import
android.widget.*
import
androidx.appcompat.app.AppCompatActivity
import
com.android.volley.Request
import
com.android.volley.Response
import
com.android.volley.VolleyError
import
com.android.volley.toolbox.StringRequest
import
com.android.volley.toolbox.Volley
import
org.json.JSONException
import
org.json.JSONObject
class
MainActivity : AppCompatActivity() {
lateinit var nameEdt: EditText
lateinit var jobEdt: EditText
lateinit var updateBtn: Button
lateinit var resultTV: TextView
lateinit var loadingPB: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super
.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
nameEdt = findViewById(R.id.idEdtUserName)
jobEdt = findViewById(R.id.idEdtJob)
updateBtn = findViewById(R.id.idBtnUpdate)
resultTV = findViewById(R.id.idTVResponse)
loadingPB = findViewById(R.id.idPBLoading)
updateBtn.setOnClickListener {
if
(TextUtils.isEmpty(nameEdt.text) && TextUtils.isEmpty(jobEdt.text)) {
Toast.makeText(
this
,
"Please enter your data.."
, Toast.LENGTH_SHORT).show()
}
addData(nameEdt.text.toString(), jobEdt.text.toString())
}
}
private
fun addData(userName: String, job: String) {
loadingPB.visibility = View.VISIBLE
val queue = Volley.newRequestQueue(
this
@MainActivity
)
val request: StringRequest =
object : StringRequest(Request.Method.PUT, url, object : Response.Listener<String?> {
override fun onResponse(response: String?) {
loadingPB.visibility = View.GONE
jobEdt.setText(
""
)
nameEdt.setText(
""
)
Toast.makeText(
this
@MainActivity
,
"Data Updated.."
, Toast.LENGTH_SHORT).show()
try
{
val jsonObject = JSONObject(response)
val result =
"User Name : "
+ jsonObject.getString(
"name"
) +
"\n"
+
"Job : "
+ jsonObject.getString(
"job"
) +
"\n"
+
"Updated At : "
+ jsonObject.getString(
"updatedAt"
)
resultTV.setText(result)
}
catch
(e: JSONException) {
e.printStackTrace()
}
}
}, object : Response.ErrorListener {
override fun onErrorResponse(error: VolleyError?) {
Log.e(
"tag"
,
"error is "
+ error!!.message)
Toast.makeText(
this
@MainActivity
,
"Fail to update data.."
, Toast.LENGTH_SHORT)
.show()
}
}) {
override fun getParams(): Map<String, String>? {
val params: MutableMap<String, String> = HashMap()
params[
"name"
] = userName
params[
"job"
] = job
return
params
}
}
queue.add(request)
}
}