hello everyone im facing a problem with volley delete request .
i working on task in user add or remove some contacts by it's id .
im using volley library for it.
API is tested with postman and working fine.
private void AddContactInList(final Contacts contacts,int RequestMethod) {
JSONArray ContactArray = new JSONArray();
ContactArray.put(StoredContactid);
final String jsonStr = ContactArray.toString();
String URl = OrganizationModel.getApiBaseUrl() + getOrgId() + "/lists/" + contacts.getId()+"/contacts";
Log.i(TAG,URl);
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(RequestMethod,URl,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG,response.toString());
try {
JSONArray mJSONArray = response.getJSONArray("contactIds");
contacts.setCode(String.valueOf(mJSONArray.length()));
long time = System.currentTimeMillis();
sqliteDataBaseHelper.changeContactUpdatedON(StoredContactid, String.valueOf(time));
sqliteDataBaseHelper.updateListContactsAndLength(contacts.getId(), mJSONArray.toString(), (mJSONArray.length()));
dataAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,error.toString());
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 400:
case 405:
json = new String(response.data);
json = dataHelper.trimMessage(json, "message");
if (json != null) dataHelper.displayMessage(json);
break;
}
}
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() {
try {
return jsonStr == null ? null : jsonStr.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
jsonStr, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Basic " + GetApiAccess());
return headers;
}
};
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
9000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonArrayRequest);
}
In my SQLite Database , the below code is working. Hope it may help you..
public void DeleteData(){
btnDltData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deleteRows = myDB.deleteData(editId.getText().toString());
if(deleteRows > 0)
Toast.makeText(MainActivity.this, "Task Clear..", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Task not Clear..", Toast.LENGTH_SHORT).show();
editId.setText("");
}
}
);
}
http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
try this, if problem didnt solve yet
Related
I have an array which is contain image quantity for image and another is image size array which is contain image size, also an image array. I'm trying to send them to server but i failed every time. I'm trying many example but nothing was worked for me. Is there any other way to do this ? Please give me some hints or link.
how to send array of params using volley in android
public void uploadMultipleImage(String url, final List<SelectedImageModel> selectedImageModels)
{
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
responseListener.onResultSuccess(resultResponse);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String result = new String(networkResponse.data);
responseListener.onResultSuccess(result);
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<>(selectedImageModels.size());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("size["+i+"]",selectedImageModels.get(i).getPhotoSize());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("quantity["+i+"]",selectedImageModels.get(i).getPhotoQuantity());
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer "+requiredInfo.getAccessToken());
headers.put("Accept", "application/json");
headers.put("Content-Type", "x-www-form-urlencoded");
return headers;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>(selectedImageModels.size());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("image["+i+"]",new DataPart("imageName",UserProfile.getFileDataFromDrawable(selectedImageModels.get(i).getPhoto())));
return params;
}
};
requestQueue.add(multipartRequest);
}
Every time i'm getting com.android.volley.server error 500 this error
Make a method for send array of params.
private String makeJsonObjectParams() {
//In mediaData,I am sending image to AWS and I will get the download link and I
// am storing the downloadurl in downloadurl arrayslist.
JSONArray mediaData = new JSONArray();
try {
if(img1 != 1) {
JSONObject temp = new JSONObject();
temp.put("file", download_url.get(0));
temp.put("type", "signature");
mediaData.put(temp);
}
if(img2 != 1){
JSONObject temp1 = new JSONObject();
temp1.put("file", download_url.get(1));
temp1.put("type", "id proof");
mediaData.put(temp1);
}
} catch (JSONException e) {
e.printStackTrace();
}
//for sending normal details like text
JSONObject updateDetails = new JSONObject();
try {
updateDetails.put("status", 2);
updateDetails.put("userId", sharedPreferences.getString("user_ID",""));
updateDetails.put("deviceToken", splash_screen.android_id);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonVerificationDetails = new JSONObject();
try {
jsonVerificationDetails.put("type", verificatin_type);
jsonVerificationDetails.put("durationOfStay", durationOfStay.getText().toString());
jsonVerificationDetails.put("media", mediaData);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("verificationDetails", jsonVerificationDetails);
jsonBody.put("updateDetails", updateDetails);
} catch (JSONException e) {
e.printStackTrace();
}
final String mRequestBody = jsonBody.toString();
return mRequestBody;
}
}
Through the below code send the code to server.
void submitData(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
final String mRequestBody = makeJsonObjectParams();
StringRequest stringRequest = new StringRequest(Request.Method.POST, completedTaskUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//do whatever you want
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
// return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
return super.parseNetworkResponse(response);
}
};
requestQueue=Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
} catch (Exception e) {//JSONException e
e.printStackTrace();
}
}
I am making a new android application and i am a beginner. starting with my Login Activity, i am trying to use POST for sending parameters. but when i debug i found no parameters being passed. Tried almost many answers in stack overflow, none solved my issue. Can anyone help
private void jsonRequestLogin() {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = Constants.LOGIN_URL;
JSONObject jsonBody = new JSONObject();
jsonBody.put("Username", uName.getText().toString().trim());
jsonBody.put("Password", paswd.getText().toString().trim());
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Use getParams() method for requesting the parameters
private void check() {
StringRequest stringRequest = new StringRequest(Request.Method.POST,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Log.d(TAG, "onResponse:" + response);
try {
JSONArray responseArray = new JSONArray(response);
JSONObject jsonObject = responseArray.getJSONObject(0);
//Log.d(TAG, "onResponse: jsonArray " + responseArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Log.d(TAG, "onErrorResponse: " + error);
Toast.makeText(SplashScreenActivity.this, "Some error occurred try after sometimes", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("param1",param1);
params.put("param2", param2;
//Log.d(TAG, "getParams: " + params);
return params;
}
};
addToRequestQueue(stringRequest, "");
}
Try to override the headers method and put content type init.
#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;
}
I think you should use retrofit
Retrofit
Retrofit 2
String url_save = "http://13.210.238.81:8080/freelance-api/gig/addGig";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject obj=new JSONObject();
try {
obj.put("categoryId",categoryId);
obj.put("gigDescription",edt_describeProject.getText().toString());
obj.put("revision",edt_revision.getText().toString());
obj.put("gigRate",edt_rate.getText().toString());
obj.put("expectedDuration",expected_delivery.getSelectedItem().toString());
obj.put("gigTitle",edt_uniqueTitle.getText().toString());
obj.put("subCategoryId",sub_Category);
JSONArray array=new JSONArray();
JSONObject objp=new JSONObject();
objp.put("skillId",id);
objp.put("skillTitle",edt_skills.getQuery().toString());
array.put(objp);
obj.put("gigSkills",array);
} catch (JSONException e) {
e.printStackTrace();
}
final String requestBody = obj.toString();
Toast.makeText(getApplicationContext(), "params-"+obj, Toast.LENGTH_LONG).show();
Log.d("params", ""+obj);
/*final Map<String, String> params = new HashMap<String, String>();
params.put("categoryId", categoryId);
params.put("gigDescription",edt_describeProject.getText().toString());
params.put("skillTitle",edt_skills.getQuery().toString());
params.put("skillId",id);
params.put("gigTitle",edt_uniqueTitle.getText().toString());
params.put("subCategoryId",sub_Category);
params.put("expectedDuration",expected_delivery.getSelectedItem().toString());
params.put("revision",edt_revision.getText().toString());
params.put("gigRate",edt_rate.getText().toString());
Toast.makeText(getApplicationContext(), "params-"+params, Toast.LENGTH_LONG).show();
Log.d("params", ""+params);*/
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url_save,new JSONObject(requestBody), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(),
"response-"+response, Toast.LENGTH_LONG).show();
Log.d("response",""+response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
"error"+error.toString(), Toast.LENGTH_LONG).show();
Log.d("VolleyError","Volley"+error);
VolleyLog.d("JSONPost", "Error: " + error.getMessage());
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
Log.e("Status code", String.valueOf(networkResponse.data));
}
/*if (error.networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
Toast.makeText(getApplicationContext(),
"Failed to save. Please try again.", Toast.LENGTH_LONG).show();
}
}*/
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "applications/json");
headers.put("Authorization", "Bearer"+" "+sharedPreferenceConfig.ReadToken(getString(R.string.token_preference)));
return headers;
}
/*#Override
public byte[] getBody() {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}*/
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
requestQueue.add(jsonObjectRequest);
Json data is looks like below want to send data to the server Using JsonObjectRequest .
{
"categoryId":"3",
"gigDescription":"test",
"revision":"3",
"gigRate":"20",
"expectedDuration":"10",
"gigTitle":"test",
"subCategoryId":"10",
"gigSkills":
[
{
"skillId":"1",
"skillTitle":"Javaaa"
}
]
}
You can check status code of volly error like this. It will tell why you are getting com.android.volley.ClientError.
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 401:
//Session expired or token expired
break;
case 400:
break;
}
}
public void userLogin() {
try {
String URL = "http://influence360.in/orezmiapp/index.php/mobile/login";
System.out.println("Arun URL :- " + URL);
final JSONObject jsonBody = new JSONObject();
jsonBody.put("type", "2");
jsonBody.put("email", email);
jsonBody.put("password", password);
final String mRequestBody = jsonBody.toString();
Log.e("JSON String is :- ", " " + mRequestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("LOG_VOLLEY", response);
try {
Toast.makeText(activity, "loginactivity entered", Toast.LENGTH_LONG).show();
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
Toast.makeText(activity, status, Toast.LENGTH_LONG).show();
if (status == 1000) {
JSONObject data = jsonBody.getJSONObject("data");
//sessionManager.setUserid(data.getString("Cust_id"));
// sessionManager.setBirthday(data.getString("Dob"));
sessionManager.setUserfirstname(data.getString("Cust_Name"));
startActivity(new Intent(LoginScreen.this, Profile.class));
finish();
} else {
Toast.makeText(activity, "Hello", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(activity, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
Log.e("Response String : -", " " + responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
RequestQueue requestQueue = Volley.newRequestQueue(activity);
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new
DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
I got the error
value of type 200 org.json.Integer cant be converted into JSONObject. Please help me to solve this. I didnt get any solution regarding this. Thankyou in advance.Please help me out.I will be highly obliged if anybody give the solution.Thank you in advance. If anybody has the solution please give me that.
I am trying to learn Volley library for posting data into webservices. I need to implement user registration form, following is the image of postman with parameters and header...
now problem is, i am getting below error
com.android.volley.ServerError
this is my code for volley post method.
public void postNewComment(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://myurl/api/users";
JSONObject jsonBody = new JSONObject();
jsonBody.put("email", "test1#gmail.com");
jsonBody.put("user_type", "C");
jsonBody.put("company_id", "0");
jsonBody.put("status", "A");
jsonBody.put("password", "123456");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + "My_auth_key");
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
please suggest where am i getting wrong. URL is working correct with postman, also as you can see i need to set 2 headers. I also tried this Url post method with AsyncTask and its working good. Now i need to implement this using volley library. kindly suggest. thank you.
this is my logcat error:
E/Volley: [81910] BasicNetwork.performRequest: Unexpected response code 405 for "Myurl"
**Try this one **
private void sendWorkPostRequest() {
try {
String URL = "";
JSONObject jsonBody = new JSONObject();
jsonBody.put("email", "abc#abc.com");
jsonBody.put("password", "");
jsonBody.put("user_type", "");
jsonBody.put("company_id", "");
jsonBody.put("status", "");
JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "Response: " + response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
onBackPressed();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + "c2FnYXJAa2FydHBheS5jb206cnMwM2UxQUp5RnQzNkQ5NDBxbjNmUDgzNVE3STAyNzI=");//put your token here
return headers;
}
};
VolleyApplication.getInstance().addToRequestQueue(jsonOblect);
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}
}
I have an alternative answer that works pretty well for Android Volley+ library by dworks and Google: See HERE