I want to pass the following JSON object in a volley string request:
{
"command":"connect",
"port":"VIRTUAL",
"baudrate":115200,
"printerProfile":"_default",
"save":true,
"autoconnect":false
}
The response is 1.
How can I implement this in Android studio using Kotlin and Volley?
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("command","connect");
params.put("port","VIRTUAL");
params.put("baudrate", "115200");
params.put("save","true");
params.put("autoconnect","false");
return params;
}
};
queue.add(sr);
Related
I want to change my StringRequest to a JsonArrayRequest in order to separate the return into different variables.
As I run this code below:
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("res", response);
if (response.equals("failure")) {
Toast.makeText(MainActivity.this, "Ungültige Anmeldedaten", Toast.LENGTH_SHORT).show();
} else {
TV.setText(response);
//ID = Integer.parseInt(response);
//switchToMain();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("email", email);
data.put("password", password);
return data;
}
};
requestQueue.add(stringRequest);
I return the response:
[{"id":"6","Username":"a","Email":"a","Password":"0cc175b9c0f1b6a831c399e269772661","Status":"Online"}]
, which is a JsonArray, isn´t it?
When I try to make a JsonArrayRequest I receive errors:
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonArrayRequest queue = new JsonArrayRequest(Request.Method.POST,URL,null,new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
if (response.equals("null")) {
Toast.makeText(MainActivity.this, "Ungültige Anmeldedaten", Toast.LENGTH_SHORT).show();
} else {
//ID = Integer.parseInt(response);
//switchToMain();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("email", email);
data.put("password", password);
return data;
}
};
requestQueue.add(queue);
I receive the following error:
com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of
Where is my mistake?
I am using volley library to send data on server as a json. My server response successfully. Data is saving in database. But Volley execute the ErrorResponse, here is my code
private void upload(final Context context) {
String url = BASE_URL + "upload.php";
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Intent intent=new Intent(ProfilePictureActivity.this,HomeActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.i("Error", "" + error);
Toast.makeText(context, "Cannot save", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> stringMap = new HashMap<>();
stringMap.put("name", names);
stringMap.put("date_of_birth",dobs);
stringMap.put("address", presentAddress);
stringMap.put("phone",phone);
stringMap.put("email", email);
stringMap.put("image",phone+".jpg");
stringMap.put("photo",imageToString(bitmap));
return stringMap;
}
};
requestQueue.add(stringRequest);
}
I'm a programming student building an Android App that uses a api json url and I'm getting a no suitable constructor found for JsonArrayRequest
Here is the error:
C:\Users\jerma\AndroidStudioProjects\VolleyParsing\app\src\main\java\com\jermainebjonesgmail\volleyparsing\MainActivity.java:37:
error: no suitable constructor found for
JsonArrayRequest(int,String,>,)
JsonArrayRequest arrayRequest = new JsonArrayRequest(Method.GET,
^
constructor JsonArrayRequest.JsonArrayRequest(String,Listener,ErrorListener)
is not applicable
(actual and formal argument lists differ in length)
constructor JsonArrayRequest.JsonArrayRequest(int,String,JSONArray,Listener,ErrorListener)
is not applicable
Here is my code:
public class MainActivity extends AppCompatActivity {
private final static String URL = "https://age-of-empires-2-api.herokuapp.com/api/v1/units";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest arrayRequest = new JsonArrayRequest(Method.GET,
URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Response: ", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error", error.getMessage());
}
});
queue.add(arrayRequest);
}
}
You are creating JsonArrayRequest in a wrong way. see java docs, for constructor.
Constructor Summary
JsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener)
Creates a new request.
JsonArrayRequest can be created as below:
Request request = new JsonArrayRequest(httpMethod, url, params, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
serverCallback.onAPIResponse(apiTag, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverCallback.onErrorResponse(apiTag, error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
};
Please find sample code here
I am able to consume api via volley library which use normal get post method but my php team just changed my api which accept json . i know there is is JsonObjectrequest in volley but i don't know how to put parameters in `JsonObjectRequest. Any help is appriciated.
PHP API
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$data_back = json_decode(file_get_contents('php://input'));
header("Content-type: application/json");
require "conn.php";
$id = $data_back->{"id"};
$address = $data_back->{"address"};
$pincode = $data_back->{"pincode"};
$name = $data_back->{"name"};
$mobile = $data_back->{"mobile"};
$sql = "UPDATE tbl_addressbook SET name = '$name', address = '$address', pincode = '$pincode', mobile = '$mobile' WHERE id = $id";
if(mysqli_query($conn,$sql)){
echo 'Address Book Updated Successfully';
}
else{
echo 'Could Not Update Your Address Book';
}
}
?>
Volley Request
StringRequest stringRequest=new StringRequest(Request.Method.POST, Config.UPDATE_ADDRESS_BOOK,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mContext,"Address Changed",Toast.LENGTH_LONG).show();
list.set(getAdapterPosition(),new AddressBookModel(bookModel.getId(),
etName.getText().toString(),
etAddress.getText().toString(),
etPinCode.getText().toString(),
etPhone.getText().toString(),
bookModel.getDefAddress()));
d.dismiss();
progress.dismiss();
((Activity)mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext,"Something Went Wrong \n ttry again later",Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map=new HashMap<String, String>();
map.put("id",bookModel.getId());
map.put("name",etName.getText().toString());
map.put("address",etAddress.getText().toString());
map.put("pincode",etPinCode.getText().toString());
map.put("phone",etPhone.getText().toString());
return checkParams(map);
}
private Map<String, String> checkParams(Map<String, String> map){
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
if(pairs.getValue()==null){
map.put(pairs.getKey(), "");
}
}
return map;
}
};
VolleySingleton.getInstance(mContext).addToRequestQueue(stringRequest);
Easy cheesy lemon squeezy!
Some code
HashMap<String, String> params = new HashMap<String, String>();
params.put("id", "300");
params.put("address", "Mars");
params.put("pincode", "***");
params.put("name", "Jon Skeet");
params.put("mobile", "911");
JsonObjectRequest request = new JsonObjectRequest(
/*URL*/,
new JSONObject(params),
new Response.Listener<JSONObject>(){/*...*/});
First Create your JsonObject like
JSONObject js = new JSONObject();
try {
js.put("email", "adasda");
js.put("address", "adasd");
js.put("pincode", "adadasd");
}catch (JSONException e) {
e.printStackTrace();
}
Then your JSON request, take a careful look at get headers.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#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;
}
private void getWalletDetails(){
final ProgressDialog pDialog; // = new ProgressDialog(mcontext);
StringRequest stringRequest;
pDialog = GifDialog.ctor(mcontext);
pDialog.show();
stringRequest = new StringRequest(Request.Method.POST, place your url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
pDialog.dismiss();
//Showing toast message of the response
try {
JSONObject jsonObject = new JSONObject(s);
totbal.setText("\u20B9 "+jsonObject.getString("avail_balance"));
JSONArray jsonArray = jsonObject.getJSONArray("tx_detail");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
mode = new Model_Wallet_Transaction();
mode.setStr1(object.getString("date"));
mode.setStr4(object.getString("insert_time"));
mode.setStr2(object.getString("name"));
mode.setStr3(object.getString("transaction_id_no"));
mode.setAmount(object.getString("amount"));
mode.setTxtype(object.getString("tx_type"));
modlist.add(mode);
}
// Collections.sort(modlist, new StringDateComparator());
adp = new CustomAdapter_Wallet_Transaction(getApplicationContext(), modlist);
list.setAdapter(adp);
} catch (Exception e) {
Log.e("Error", e.toString());
}
// Toast.makeText(Wallet_Transaction.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
pDialog.dismiss();
//Showing toast
//Toast.makeText(Wallet_Transaction.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put("user_id", UserId);
params.put("deviceId", DeviceId);
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
I'm trying to make a http-post request to my localhost server. The problem I have Is that I'm not getting any response when I make the request.
I'm doing the request from a fragment class:
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i(TAG, " Button clickde");
fLogin.setCallback(loginButton); //Let's register a callback
final RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
String url = "http://127.0.0.1/create_row.php";
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url,new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, error.getMessage());
}
});
fLogin.setFacebookListener(new FacebookLogin.OnFacebookListener() {
#Override
public void onFacebookLoggedIn(JSONObject parameters) {
}
});
}
});
Nothing is printed out from the onResponse or Response.ErrorListener.
You did't add the jsObjRequest to the queue, so the request wasn't executed, add it to the queue by:
queue.add(jsObjRequest);
see the tutorial on developer.android.com.