2

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.'));
        }
}

?>

2 Answers2

3
    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()
            }
        }
}
moallemi
  • 2,448
  • 2
  • 25
  • 28
0

Make sure it's your php file you are reading the document, for done reason most totals don't add this but php no longer sees android post and get headers. I'll update with a link for reference here in about 15 min when I go on break.

https://stackoverflow.com/a/39508364/6915690

Vahalaru
  • 380
  • 4
  • 15
  • my php file was fine when i run it on postman, it can pass data from postman. But i confused when i want to input the data from kotlin app. – Faris Nurrachman Feb 27 '19 at 03:57
  • That's what I'm saying when you run those tests such as postman ect.... it will test good. When you connect from android to a url that points to a php file the headers and request method are sent differently than they used to. Unsure why. Your never getting a response code 200 because to your php file its reading blank. So it sends error code everytime since there is nothing to put into database. Post your php code and I'll try to help. I went through this for a gruelling week or two before I figured it out. – Vahalaru Feb 27 '19 at 04:11
  • Thank you. And I've posted my php code on my edited question. – Faris Nurrachman Feb 27 '19 at 09:46