Panache Panache - 1 year ago 122
Android Question

Inserting Data to Mysql Server as json String - No Data uploading

Referring to various examples over stack, I wrote below code to send data to MySQL server table, but nothing is uploading there. Here is code for my Android method.

public void sendtoserver(final String data) {
Log.e("LWFAB", "Sending Data to Server");
//Send data to server now
new Thread(new Runnable() {
@Override
public void run() {
try {
URL bulkdataurl = new URL("http://myphp.php?");
HttpURLConnection bulkcon = (HttpURLConnection) bulkdataurl.openConnection();
bulkcon.setConnectTimeout(15000);
bulkcon.setReadTimeout(15000);
bulkcon.setRequestMethod("POST");
bulkcon.setDoOutput(true);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(bulkcon.getOutputStream());
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(bufferedOutputStream));
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
bufferedOutputStream.close();
bulkcon.connect();
//OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bulkcon.getOutputStream());
//outputStreamWriter.write(data);
//outputStreamWriter.flush();

//Get Server Response
BufferedReader bufferedReader;
bufferedReader = new BufferedReader(new InputStreamReader(bulkcon.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;

while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
System.out.println(stringBuilder.toString());
bufferedReader.close();

System.out.println("Sending Bulk Data " + bulkcon);


} catch (Exception e) {
e.printStackTrace();
}
}
}).start();

}
}


I m not getting any error. Below is my php code

<?php
require_once("../dbconnect.php");

$json = file_get_contents('php://input');
$obj = json_decode($json, true);
error_log(print_r($obj, true));
$array_data = $obj["data"];
print_r($obj["data"]);


foreach ($array_data as $row) {
print_r($row);
$sql = "INSERT INTO test (vid, name,branch,date,time) VALUES ('" . $row["vid"] . "', '" . $row["name"] . "','".$row["branch"]."','".$row["date"]."','".$row["time"]."')";

echo "$sql<br>";
$conn->query($sql);
}

$conn->close();
?>


And sample of data being sent as string is as below:

{"data":[{"vid":"1","name":"raj","branch":"mech","date":"2-Sep-2017","time":"13:03:24 PM"}]}


Can u guide if there is something to fix.

Answer Source

You are using cursor.getInt(1) which will return an integer from the cursor. You need to use cursor.getString() in Order to get the string and put them correctly in JSON.

This is a small example:

jsonObject.put("vid", curser.getString(cursor.getColumnIndex("vid")));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download