POST json array to Mysql database using JsonArrayRequest using volley in android? - java

This is my code for JsonArrayRequest I think either it is incomplete or incorrect. The problem is nothing getting added into the database and I am not getting any errors. I am new to programming so I have no idea as to where I might be going wrong.
private void insertToDb() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, INVEST_URL,
itemSelectedJson, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(AddInvEst.this, "The echoed response is "+response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type","application/json");
headers.put("Accept", "application/json");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
This is code for creating a jsonArray
private void selectedItems() {
billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
.getText().toString();
itemselected.put("custInfo", custSelected.toString());
itemselected.put("invoiceNo", textViewInvNo.getText().toString());
itemselected.put("barcode", barCode.getText().toString());
itemselected.put("desc", itemDesc.getText().toString());
itemselected.put("weight", weightLine.getText().toString());
itemselected.put("rate", rateAmount.getText().toString());
itemselected.put("makingAmt", makingAmount.getText().toString());
itemselected.put("net_rate", netRate.getText().toString());
itemselected.put("itemTotal", itemtotal.getText().toString());
itemselected.put("vat", textViewVat.getText().toString());
itemselected.put("sum_total", textViewSum.getText().toString());
itemselected.put("bill_type", billType);
itemselected.put("date", textViewCurrentDate.getText().toString());
//Add the map to the Array
itemSelectedJson.put(itemselected);
index++;
}
And this is my php code.
<?php
require "init.php";
$json = file_get_contents('php://input');
//$data = json_decode($json,true);
// remove the ,true so the data is not all converted to arrays
$data = json_decode($json);
// Now process the array of objects
foreach ( $data as $inv ) {
$custInfo = $inv->custInfo;
$rate = $inv->rate;
$weight= $inv->weight;
$desc= $inv->desc;
$makingAmt= $inv->makingAmt;
$vat= $inv->vat;
$itemTotal= $inv->itemTotal;
$sum_total= $inv->sum_total;
$barcode= $inv->barcode;
$net_rate= $inv->net_rate;
$date= $inv->date;
$invoiceNo= $inv->invoiceNo;
$bill_type= $inv->bill_type;
$sql = "INSERT INTO selected_items
(custInfo, invoiceNo, barcode, desc,
weight, rate, makingAmt,net_rate,
itemTotal,vat,sum_total,bill_type,date)
VALUES
('$custInfo','$invoiceNo','$barcode','$desc',
'$weight','$rate','$makingAmt','$net_rate',
'$itemTotal','$vat','$sum_total','$bill_type','$date')";
$res = mysql_query($sql,$con);
if(!$res){
$result = new stdClass();
$result->status = false;
$result->msg = mysql_error();
echo json_encode($result);
exit;
}
}
?>

You missed to add a method getParams() inside the post request, it should have this structure
StringRequest stringRequest = new StringRequest(Request.Method.POST, "url",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
errorHandler(error);
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("KEY1", key1);
params.put("KEY2", key2);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

Related

Volley - BasicNetwork.performRequest: Unexpected response code 400 POST

Postman Header
[{"key":"Content-Type","name":"Content-Type","type":"text","value":"application/json"},{"key":"token","type":"text","value":"ffBJpLW55i"}]
even if i put token value instead of the token string it wont work
headers.put("Content-Type", "application/json");
headers.put("token", "ffBJpLW55i");
2019-03-15 21:51:15.384 20577-20620/com.sleepyhitman.ab4_internship_2019try2 E/Volley: [816] BasicNetwork.performRequest: Unexpected response code 400 for https://tralalala.com/api-spot-get-all
private void loadRecyclerViewData(final String token){
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest listRequest = new StringRequest(Request.Method.POST,URL_DATA+"api-spot-get-all",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("result");
for (int i =0; i<array.length(); i++) {
JSONObject o = array.getJSONObject(i);
ListItem list = new ListItem(
o.getString("id"),
o.getString("name"),
o.getString("country"),
o.getString("whenToGo"),
o.getBoolean("isFavorite")
);
listItems.add(list);
}
ListItemAdapter listItemAdapter = new ListItemAdapter(getApplicationContext(), listItems);
recyclerView.setAdapter(listItemAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
//
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("token", token);
return headers;
}
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", "");
params.put("windProbability", "");
return params;
}
};
requestQueue.add(listRequest);
}
This part is the error part of your volley request,
URL_DATA+"api-spot-get-all"
There should be a URL in string format as you are using StringRequest.

Send Header And Data(Body) as String in Volley

I am trying to send a post request to my server
my server read Headers of the request in String Format but getHeaders() in Volley return : Map< String, String >
Is there any way to send headers of request in string Format ?!
this is my Code Request :
Map<String, String> params = new HashMap<String, String>();
params.put("MY_FIRST_DATA_KEY", "MY_FIRST_DATA_VALUE");
params.put("MY_SECOND_DATA_KEY", "MY_SECOND_DATA_VALUE");
String url = "http://MY_URL.com";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "onResponse: " + response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: " + error.toString() );
error.printStackTrace();
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("MY_KEY","MY_VALUE");
/* HERE i need to return a String Value */
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(20000 , 3 , 3));
Volley.newRequestQueue(context).add(request);
try overriding getParams()
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("MY_FIRST_DATA_KEY", "MY_FIRST_DATA_VALUE");
params.put("MY_SECOND_DATA_KEY", "MY_SECOND_DATA_VALUE");
return params;
}
You can add getParams() in the JsonObjectRequest()
#Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Parameter1", "value");
params.put("Parameter2", "value");
return params;
}
Hope it helps.
This is how I made a volley POST request adding headers and body
private void call_api(final String url){
if(!this.isFinishing() && getApplicationContext() != null){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
resultsTextView.setVisibility(View.INVISIBLE);
loader.setVisibility(View.VISIBLE);
}
});
Log.e("APICALL", "\n token: " + url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("APICALL", "\n response: " + response);
if(!FinalActivity.this.isFinishing()){
try {
JSONObject response_json_object = new JSONObject(response);
JSONArray linkupsSuggestionsArray = response_json_object.getJSONObject("data").getJSONArray("package");
final JSONObject k = linkupsSuggestionsArray.getJSONObject(0);
final String result = k.getJSONArray("action").getJSONObject(0).getString("url");
last_results = result;
last_results_type = k.getString("type");
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
loader.setVisibility(View.INVISIBLE);
resultsTextView.setText(result);
resultsTextView.setVisibility(View.VISIBLE);
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "An unexpected error occurred.", Toast.LENGTH_LONG).show();
finish();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("APICALL", "\n error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Check your internet connection and try again", Toast.LENGTH_LONG).show();
finish();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("apiUser", "user");
headers.put("apiKey", "key");
headers.put("Accept", "application/json");
//headers.put("Contenttype", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("location", "10.12 12.32");
return map;
}
};
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}

Android: How to call put method in Volley?

When i call URL on postman, it returns expected result. I use PUT method using Volley, but it does not work.
StringRequest reg=new StringRequest(Request.Method.PUT, AppConfig.Registration, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("USER_REG",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("USER_REG","-------------"+error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(name1,Name);
params.put(client_id1,CID);
params.put(email1,Email);
params.put(mobile1,Mobile);
params.put(password1,Password);
params.put(device_id1,"123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(reg);
Here's the postman output.
Currently you are sending the data from your Android using Volley as path parameters which should be sent as JSON like the following.
RequestQueue queue = Volley.newRequestQueue(this);
private void makeJsonObjReq() {
Map<String, String> postParam= new HashMap<String, String>();
postParam.put(name1,Name);
postParam.put(client_id1,CID);
postParam.put(email1,Email);
postParam.put(mobile1,Mobile);
postParam.put(password1,Password);
postParam.put(device_id1,"123456");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.PUT,
Const.YOUR_URL, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setTag(TAG);
queue.add(jsonObjReq);
You need to add the Content-Type as application/json in the header as well.

Send int and String as param in volley

Am trying to send String and int as params in volley. But it show error on String if i use Map<String,Integer> params = new HashMap<String, String>(); and show error on int if i use Map<String,String> params = new HashMap<String, String>(); So how can i send int and String as a param in post request.
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://www.aaa.com/insert/signup" ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("sign_up_res", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error" , error.toString());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("firstname" , PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString(Local_Preference.FIRSTNAME, "Not Set") );
params.put("number" , "123");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(SignUp2Activity.this);
requestQueue.add(stringRequest);
In Sql table is like firstname (varchar) and number(int). I don't want to change the int type to varchar in sql. Is there any way to send int and String in a single params.
you can do this create a
Map params = new HashMap();
then
params.put(key,value); // for string
params.put(key,String.valueOf(value)); // for int As suggested
Please follow the code using this my problem is solved
String tag_json_obj = "json_obj_req";
String url = "https://api.androidhive.info/volley/person_object.json";
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Androidhive");
params.put("email", "abc#androidhive.info");
params.put("password", "password123");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

How to send request Header is "Content-Type":"application/json" when GET on Volley

I try to use GET on Volley , but i need send request to application/json .
I take a look for some answers , i try to use jsonBody , but it shows error:
null com.android.volley.ServerError
Here is my code:
public class MainActivity extends AppCompatActivity {
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
JSONObject jsonBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");
} catch (JSONException ex) {
ex.printStackTrace();
}
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});
mQueue.add(jsonObjectRequest);
}
}
Is any one can teach me how to fix this , any help would be appreciated.
Here is my url:
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
Implementation in your's
public class MainActivity extends AppCompatActivity {
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}) { //no semicolon or coma
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
mQueue.add(jsonObjectRequest);
}
}
In general for setting a custom header you need to override getHeaders and set the custom header manually. However, volley handles content type headers differently and getHeaders way does not always work.
So for your case you need to override getBodyContentType. So your code will look like
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}){
#Override
public String getBodyContentType(){
return "application/json";
}
};
I try to use GET on Volley
The docs for the method you are calling says this
Constructor which defaults to GET if jsonRequest is null, POST otherwise
You can't GET with an HTTP JSON body. Maybe that's the error.
//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");
That's not the header, so pass in null here to do GET
new JsonObjectRequest(url, null,
And towards the end of your request, override a method to request JSON
...
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}) { // Notice no semi-colon here
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
Use String request instead of jsonrequest like this
StringRequest loginMe = new StringRequest(Request.Method.GET, "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("LoginActivity -- onResponse --> " + response);
if (progressDialog != null) {
progressDialog.dismiss();
}
try {
JSONObject jsonObject = new JSONObject(response);
} catch (Exception e) {
CommonUtility.somethingWentWrongDialog(activity,
"LoginActivity -- onResponse-- Exception --> ".concat(e.getMessage()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (progressDialog != null) {
progressDialog.dismiss();
}
CommonUtility.somethingWentWrongDialog(activity,
"LoginActivity -- onErrorResponse --> ".concat(error.getMessage()));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
System.out.println("LoginActivity -- LoginParams --> " + params.toString());
return params;
}
};
loginMe.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(activity).add(loginMe);

Categories