I have a JSONArray, retrieving from Android local SQLite database, which I want to send to MySQL database. The JSONArray structure is as following
[
{
"value1": "1518518041",
"value2": "90.390342",
"value3": "23.7758309"
},
{
"value1": "1518518071",
"value2": "90.3903512",
"value3": "23.7758192"
},
{
"value1": "1518518200",
"value2": "90.390342",
"value3": "23.7758309"
},
....
]
Now I am trying to send the data to MySQL using Volley JsonArrayRequest
here is the code
JSONArray jsonArray = db.getResults();
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest sendSqliteData = new JsonArrayRequest(Request.Method.POST, URL, jsonArray,
new Response.Listener<JSONArray>(){
@Override
public void onResponse(JSONArray jsonArray) {
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
try {
params.put("value1", jsonArray.getString("value1"));
params.put("value2", jsonArray.getString("value2"));
params.put("value3", jsonArray.getString("value3"));
} catch (JSONException e) {
e.printStackTrace();
}
return params;
}
};;
queue.add(sendSqliteData);
Here is the php script
<?php
// connect to database
$link = mysqli_connect($hostname, $username, $password);
mysqli_select_db($link, "myDatabase");
// get the JSONArray the app sends
$contents = file_get_contents('php://input');
$jsonArray = json_decode($contents, true);
$jsonCount = count($jsonArray);
for ($i = 0; $i < $jsonCount; $i++) {
$item = $jsonArray[$i];
$value1 = utf8_decode($item['value1']);
$value2 = utf8_decode($item['value2']);
$value3 = utf8_decode($item['value3']);
$query = "INSERT INTO dataTable VALUES('$value1', '$value2', '$value3')";
mysqli_query($link, $query);
}
Where I am doing wrong? Why the data is not writing in MySQL table?
EDIT: The problem I am getting in the Try/Catch block.
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
try {
params.put("value1", jsonArray.getString("value1"));
params.put("value2", jsonArray.getString("value2"));
params.put("value3", jsonArray.getString("value3"));
} catch (JSONException e) {
e.printStackTrace();
}
return params;
}
In the Try/Catch block I am retrieving String from the jsonArray
whereas I am requesting volley to make a JsonArray post. My problem is I have data already in jsonArray
variable in the format given upper JSON sample. How can I send that JSON to server using PHP. I am trying with this code but its not working. Please suggest me or edit the given code to do it properly.