Kotlin POST request


Question

I'm new in Kotlin. I wanna ask about POST request.

I want to pass "nim", "nama", and "address" edittext.text to database. But on my code, the Toast "Error Occured" is still appear and database didn't get any data. What should i do then?

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

    val jsonobj = JSONObject()

    jsonobj.put("nim", nim_editText.text)
    jsonobj.put("nama", nama_editText.text)
    jsonobj.put("address", address_editText.text)

    val queue = Volley.newRequestQueue(this)
    val url = "http://192.168.100.7/simplecrud/create.php"

    val req = JsonObjectRequest(Request.Method.POST,url,jsonobj,
        Listener {
            Toast.makeText(this@MainActivity, "Success", Toast.LENGTH_SHORT).show()
        },
        ErrorListener {
            Toast.makeText(this@MainActivity, "Error Occured", Toast.LENGTH_SHORT).show()
        })


    val btn = findViewById<Button>(R.id.button1)

    btn.setOnClickListener(object : View.OnClickListener {
        override fun onClick(v: View?) {
            queue.add(req)
        }
    })

this is my create.php code

    <?php

require_once('connection.php');

$nim        = $_POST['nim'];
$name       = $_POST['name'];
$address    = $_POST['address'];
$gender     = $_POST['gender'];

if(!$nim || !$name || !$address || !$gender ){
    echo json_encode(array('message'=>'required field is empty.'));
}
    else{
        $query = mysqli_query($CON, "INSERT INTO tb_student VALUES ('$nim','$name','$address','$gender')");

    if($query){
        echo json_encode(array('message'=>'student data successfully added.'));
    }
        else{
            echo json_encode(array('message'=>'student data failed to add.'));
        }
}

?>
1
2
2/27/2019 9:44:45 AM

    fun post(url: String, body: String): String {
    return URL(url)
        .openConnection()
        .let {
            it as HttpURLConnection
        }.apply {
            setRequestProperty("Content-Type", "application/json; charset=utf-8")
            requestMethod = "POST"

            doOutput = true
            val outputWriter = OutputStreamWriter(outputStream)
            outputWriter.write(body)
            outputWriter.flush()
        }.let {
            if (it.responseCode == 200) it.inputStream else it.errorStream
        }.let { streamToRead ->
            BufferedReader(InputStreamReader(streamToRead)).use {
                val response = StringBuffer()

                var inputLine = it.readLine()
                while (inputLine != null) {
                    response.append(inputLine)
                    inputLine = it.readLine()
                }
                it.close()
                response.toString()
            }
        }
}
2
2/26/2019 8:25:34 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon