I’m fairly inexperienced with Android programming and am having issues sending a JSONArray to my PHP server. I am using the following code to generate the JSONArray from my cursor:
public JSONArray matrixJSON(){ Cursor cursor = db.rawQuery("SELECT columnID,rowID,value FROM Matrix WHERE PolicyID=" + curPolicy,null); JSONArray resultSet = new JSONArray(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { int totalColumn = cursor.getColumnCount(); JSONObject rowObject = new JSONObject(); for (int i = 0; i < totalColumn; i++) { if (cursor.getColumnName(i) != null) { try { rowObject.put(cursor.getColumnName(i), cursor.getString(i)); } catch (Exception e) { Log.d(TAG, e.getMessage()); } } } resultSet.put(rowObject); cursor.moveToNext(); } cursor.close(); return resultSet; }
I believe I am misunderstanding how to properly send data via JsonARrayRequest. Here is the following code that I am using to send the data.
public void sendData(JSONArray data) { RequestQueue queue = Volley.newRequestQueue(this); String url = "http://10.123.20.180:8080/insertmatrix.php"; JsonArrayRequest dataReq = new JsonArrayRequest(Request.Method.POST, url, data, response -> Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show(), error -> Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show()){ @Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { if (response.data == null || response.data.length == 0) { return Response.success(null, HttpHeaderParser.parseCacheHeaders(response)); } else { return super.parseNetworkResponse(response); } } }; queue.add(dataReq); }
Instead of sending the data, I am left with a blank array. The cursor to JSONarray function is working properly as I can see in debug, but the php server is receiving a blank array. I assume there is some essential functions I am missing.
Advertisement
Answer
Fixed it by switching my array into a string and then using a StringRequest
to send the data.
Updated function:
public void sendData(JSONArray data) { RequestQueue queue = Volley.newRequestQueue(this); String url = "http://10.123.20.180:8080/insertmatrix.php"; String json = data.toString(); StringRequest dataReq = new StringRequest(Request.Method.POST,url,response -> Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show(), error -> Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show()){ @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String,String>(); params.put("data",json); return params; } }; queue.add(dataReq); }