Im using Restful Java to parse data json with POST method and Volley in android. When I try to insert data from Advanced REST Client, it insert data into db success, but in Android, when I insert data and see that it happen an exception as below:
My Restful (UPDATED):
#Path("/bookticket")
public class BookServiceCalled {
#POST
#Path("/json")
#Produces("application/json;charset=utf-8")
#Consumes("application/x-www-form-urlencoded") // MediaType.APPLICATION_JSON
public static void bookFromUser(#QueryParam("fullname") String fullname,
#QueryParam("birthday") Date birthday,
#QueryParam("address") String address) throws Exception {
Connection connection = null;
PreparedStatement statement = null;
try {
// Config connect mydb
String query = "INSERT INTO order "
+ "(fullname, birthday, address) VALUES "
+ "(?,?,?) ";
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setString(1, fullname);
statement.setDate(2, birthday);
statement.setString(3, address);
statement.executeUpdate();
System.out.println("Work !");
}
catch (Exception e) {
// TODO Auto-generated catch block
if (connection != null) {
connection.close();
}
throw e;
}
finally {
if (connection != null) {
connection.close();
}
}
}
}
My activity class:
private static final String URL_BOOK = "http://192.168.1.221:9999/bookticket_service/bookticket/json";
EditText fullname, birthday, address;
fullname = (EditText) findViewById(R.id.fullname);
birthday = (EditText) findViewById(R.id.birthday);
address = (EditText) findViewById(R.id.address);
btnBook = (Button) findViewById(R.id.btnBook);
requestQueue = Volley.newRequestQueue(getApplicationContext());
btnBook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringRequest request = new StringRequest(Request.Method.POST, URL_BOOK, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams() throws AuthFailureError {
Map<String, String> parameter = new HashMap<String, String>();
parameter.put("Content-Type", "application/json; charset=utf-8");
parameter.put("fullname", fullname.getText().toString());
parameter.put("birthday", birthday.getText().toString());
parameter.put("address", address.getText().toString());
return parameter;
}
};
// volley saves the response in its cache and this behavior may cause some strange problem
// request.setShouldCache(false);
requestQueue.add(request);
}
});
Logcat:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'fullname' cannot be null
How to fix the exception, thanks for the help
Related
I am new to new android programming and currently working with the Volley POST request library for a login page. I already have a working API which gives a String token when you make a post request. For now I have hard coded the username and password just to see if the post request works by creating a Toast. However, when I click on the submit button it prints out 200 in toast which doesnt make sense because the token is very big. It takes a few seconds for the toast to appear. This is what the API gives(I need the token):
{
"status": true,
"result": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjI4OTkiLCJvdGhlciI6eyJ1c2VyX2lkIjoiMjg5OSIsImRvbWFpbl9saXN0X2ZrIjoiMSIsInV1aWQiOiIxNTY4NzA2Mjg4ODk5IiwidXNlcl90eXBlIjoiNCIsInJlZ190eXBlIjoiMSIsImVtYWlsIjoiZmFpc2FsY2t5ZkBnbWFpbC5jb20iLCJwYXNzd29yZCI6ImY0NjY4Mjg4ZmRiZjk3NzNkZDk3NzlkNDEyOTQyOTA1Iiwic3RhdHVzIjoiMSIsImRhdGVfb2ZfYmlydGgiOm51bGwsImltYWdlIjpudWxsLCJ0aXRsZSI6bnVsbCwiYWdlbmN5X25hbWUiOm51bGwsImFnZW50X25hbWUiOm51bGwsImFnZW5jeV9lbWFpbCI6IiIsImZpcnN0X25hbWUiOiJGYWlzYWwiLCJtaWRkbGVfbmFtZSI6IiIsImxhc3RfbmFtZSI6bnVsbCwiYWRkcmVzcyI6IjMxIEQiLCJjaXR5IjoiUmFzaGlkaXlhIiwic3RhdGUiOiJEdWJhaSIsImNvdW50cnlfY29kZSI6IjIxMiIsImNvdW50cnlfbmFtZSI6IlVuaXRlZCBBcmFiIEVtaXJhdGVzIiwicGhvbmUiOiIwNTY2OTkzNzA5IiwicGhvbmVfY29kZSI6Iis5NzEiLCJvZmZpY2VfcGhvbmUiOm51bGwsInBpbl9jb2RlIjoiMTE0MTYwIiwicGFuX251bWJlciI6bnVsbCwicGFzc3BvcnRfbnVtYmVyIjoiIiwiY291bnRyeV9pc3N1ZSI6IjAiLCJwYXNzX2V4cGlyZV9kYXRlIjoiMDAwMC0wMC0wMCIsImNyZWF0aW9uX3NvdXJjZSI6InBvcnRhbCIsImNyZWF0ZWRfZGF0ZXRpbWUiOiIyMDE5LTA5LTE3IDA3OjQ0OjQ4IiwiY3JlYXRlZF9ieV9pZCI6IjAiLCJsYW5ndWFnZV9wcmVmZXJlbmNlIjoiZW5nbGlzaCIsInNpZ25hdHVyZSI6bnVsbCwic3ViX2FkbWluX3ByZXZpbGFnZSI6bnVsbCwicHJvbW9fY29kZSI6bnVsbCwiaG90ZWxfcHJvbW9fY29kZSI6bnVsbCwiY2FyX3Byb21vX2NvZGUiOm51bGwsImdyb3VwIjoiMCJ9LCJBUElfVElNRSI6MTU3MjQwMzU2Nn0.rU3NIqiHxsgOS7zeeuSCmPZP9Sc7RMXVGKWXni4JBLM"
}
}
Here is the current code that I have :
public class Login extends AppCompatActivity {
EditText username, password;
Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
this.username = findViewById(R.id.editTextUsername);
this.password = findViewById(R.id.editTextPassword);
this.loginButton = findViewById(R.id.buttonLogin);
this.loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(Login.this, "I just clicked the button",
Toast.LENGTH_LONG).show();
RequestQueue requestQueue =
Volley.newRequestQueue(getApplicationContext());
String URL =
"http://apidev.travelhouse.world/api/v1/user/login?
username=faisalckyf#gmail.com&password=faisal";
final JSONObject jsonBody = new JSONObject();
// jsonBody.put("username", "faisalckyf#gmail.com");
// jsonBody.put("password", "faisal");
final String requestBody = jsonBody.toString();
JsonArrayRequest jsonObjectRequest = new
JsonArrayRequest(Request.Method.POST, URL, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
String token = "";
for (int i = 0; i < response.length(); i++)
{
try {
JSONObject hit =
response.getJSONObject(i);
token = hit.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(Login.this, token,
Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.toString(),
Toast.LENGTH_LONG).show();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#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
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(response,
HttpHeaderParser.parseCacheHeaders(response));
}
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-API-KEY", "CODEX#123");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
//
});
//
}
}
You are parsing status code instead of result token in your parseNetworkResponse() function:
#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));
}
You need to change the return statement to this:
return Response.success(response, HttpHeaderParser.parseCacheHeaders(response));
As you can see, in your function you are taking the response but you are only passing the status code(responseString) to result.
Secondly your response is actually JSON object. You need to parse it to JsonObject (or use JsonObjectRequest) and then read value token nested in result.
In my project, i pass the firstname of a user in a params from the JSONobject request. It would then get the response and fill the textviews. however i cant figure out why my code does not work.I checked my php and it works fine when i put a predefined firstname in it, so i ruled out a web service problem. does it get the response first and then pass the params? please help
public class ProfileActivity extends AppCompatActivity {
TextView Username, Firstname, Lastname, Birthdate, Barangay;
String firstname;
String json_url = "http://localhost/android/getprofileinfo.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Username = (TextView)findViewById(R.id.usernameprofile);
Firstname = (TextView)findViewById(R.id.firstnameprofile);
Lastname = (TextView)findViewById(R.id.lastnameprofile);
Birthdate = (TextView)findViewById(R.id.birthdayprofile);
Barangay = (TextView)findViewById(R.id.barangayprofile);
final Bundle bundle = getIntent().getExtras();
firstname = bundle.getString(firstname);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, json_url, (String) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Username.setText(response.getString("username"));
Firstname.setText(response.getString("firstname"));
Lastname.setText(response.getString("lastname"));
Birthdate.setText(response.getString("birthdate"));
Barangay.setText(response.getString("barangay"));
}
catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProfileActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
error.printStackTrace();
} //end of method onErrorResponse
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("firstname", firstname);
return params;
}
};
MySingleton.getmInstance(ProfileActivity.this).addTorequestque(jsonObjectRequest);
}
}
this is the getpropileinfo.php
<?php
$firstname =$_POST["firstname"];
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','mydb');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$sql = "SELECT username,firstname,lastname,birthdate,barangay FROM users
WHERE firstname LIKE '".$firstname."'; ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
echo json_encode(array("username"=>$row['username'],
"firstname"=>$row['firstname'],
"lastname"=>$row['lastname'], "birthdate"=>$row['birthdate'],
"barangay"=>$row['barangay']));
}
?>
You are not properly taking the getExtras(), provide the key name which you pass using putExtra() from your calling activity, like this
In the calling activity pass intent like
Intent i = new Intent(FirstActivity.this, ProfileActivity.class);
String strName = "some_name";
i.putExtra("key_username", strName);
startActivity(i);
Then in ProfileActivity,
final Bundle bundle = getIntent().getExtras();
firstname = bundle.getString("key_username");
Convert to JsonArrayRequest
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url, (String) null,
new com.android.volley.Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject person = (JSONObject) response
.get(0);
Username.setText(person.getString("username"));
Firstname.setText(person.getString("firstname"));
Lastname.setText(person.getString("lastname"));
Birthdate.setText(person.getString("birthdate"));
Barangay.setText(person.getString("barangay"));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProfileActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
error.printStackTrace();
} //end of method onErrorResponse
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("firstname", firstname);
return params;
}
};
May be its issue with your localhost, Go through Genymotion is using your PC IP address. to get your IP address go to:
start -> cmd -> ipconfig
then search for IPv4, copy the IP and paste it in your URL. It should looks like the following:
String YourURL = "http://192.168.0.106:8888/android/getprofileinfo.php";
Hope this works too for you.
Inside the method parameters, remove the string casting for the json object.
null instead of (String) null.
Change your JSONRequest to a StringRequest.
I wanna upadate recyclerview child item when itself clicked.It takes the data from server and updates it self. kindly provide any solution for this scenario.Here i have tried as i know but it is not updating.
myHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
SQLiteHandler db = new SQLiteHandler(context);
HashMap<String, String> user = db.getUserDetails();
String tag_string_req = "req_login";
final String uid = user.get("uid");
Log.d("hello", uid);
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.Upvote, new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String upvote_no = jObj.getString("upcount");
String text = "Upvoted " + upvote_no;
((TextView) v).setText(text);
//Log.d("resp", upvote);
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(context,
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(context, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("qries_user_id", uid);
params.put("qries_answer_id", answered_id);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
});
In the above code i am trying to taking response from Json and updating to self child item as ((TextView) v).setText(text); but it is not updating.Thanks in Advance!
Try to cast your clicked view in TextView
myHolder.upvote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) v).setText("something");
}
});
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
In my android app, I am sending a volley POST request and it's not working. Rather it is sending empty parameters.
If I enter the url (https://blogurl.com/wp-json/wp/v2/comments?post=20081&author_name=Ozuf&author_email=myemail#my.com&content=This_is_a_sampe_comment) in postman and send a POST request it yields the desired result.
And the code generated by Postman looks like this for JAVA OKHttp:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://blogurl.com/wp-json/wp/v2/comments?post=20081&author_name=Ozuf&author_email=myemail#my.com&content=This_is_a_sampe_comment")
.post(null)
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "23f2c2587-e9eb-5446-3d73-a1a1a6814683")
.build();
Response response = client.newCall(request).execute();
This is the code I am using to send the POST request:
public void submitComment() {
final String comment = commentContent.getText().toString().trim();
final String name = commentName.getText().toString().trim();
final String email = commentEmail.getText().toString().trim();
Log.d(TAG, "submitComment called");
if (allFieldsAreValid()) {
Log.d(TAG, "All fields are valid");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?";
final PostingComment postingComment = PostingComment.newInstance();
postingComment.show(getFragmentManager(), "fragmentDialog");
JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
parseResponse(response);
postingComment.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getPost called");
VolleyLog.d(TAG, "Error: " + error.getMessage());
postingComment.dismiss();
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("post", comtUrl);
params.put("author_name", name);
params.put("author_email", email);
params.put("content", comment);
return params;
}
};
int retrytimes = 10;
RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postDetails.setRetryPolicy(policy);
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(postDetails);
Log.d(TAG, "Data sent is " + comment + name + email);
} else {
Log.d(TAG, "All fields are not valid");
}
}
And Like I said before, the request goes true but the parameters are not sent along with it.
EDIT
After applying djodjo answer
public void submitComment() {
String comment = null;
try {
comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String name = null;
try {
name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String email = null;
try {
email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d(TAG, "submitComment called");
if (allFieldsAreValid()) {
Log.d(TAG, "All fields are valid");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?post="+comtUrl+"&content="+comment+"&author_name="+name+"&author_email="+email;
final PostingComment postingComment = PostingComment.newInstance();
postingComment.show(getFragmentManager(), "fragmentDialog");
JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
parseResponse(response);
postingComment.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getPost called");
VolleyLog.d(TAG, "Error: " + error.getMessage());
postingComment.dismiss();
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
int retrytimes = 10;
RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postDetails.setRetryPolicy(policy);
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(postDetails);
Log.d(TAG, "Data sent is " + comment + name + email);
} else {
Log.d(TAG, "All fields are not valid");
}
}
After applying his solution, that's how my codes looks like. But I am constantly getting error 409.
06-20 19:13:26.405 25586-27084/com.jozuf.blog E/Volley: [6168] BasicNetwork.performRequest: Unexpected response code 409 for https://blog.url/wp-json/wp/v2/comments?post=20081content=Yyggggbbhhgggggg&author_nameRrrauthor_emailgf%40ff.com
After the debugging in chat, the issue found was that it is a POST request but the parameters are still being sent in the request url.
In your case sending a POST response will make the param to go in the body as a multipart form which needs to be fixed. Update you code with below
public void submitComment() {
String comment = null;
try {
comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String name = null;
try {
name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String email = null;
try {
email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d(TAG, "submitComment called");
if (allFieldsAreValid()) {
Log.d(TAG, "All fields are valid");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?post="+comtUrl+"&content="+comment+"&author_name="+name+"&author_email="+email;
final PostingComment postingComment = PostingComment.newInstance();
postingComment.show(getFragmentManager(), "fragmentDialog");
JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
parseResponse(response);
postingComment.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getPost called");
VolleyLog.d(TAG, "Error: " + error.getMessage());
postingComment.dismiss();
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
});
int retrytimes = 10;
RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postDetails.setRetryPolicy(policy);
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(postDetails);
Log.d(TAG, "Data sent is " + comment + name + email);
} else {
Log.d(TAG, "All fields are not valid");
}
}
The duplicate issue is explained in this thread
Just change the request to have this retry policy and it will work
request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
getParams() are not called for JsonRequests.
What you can do is just append to
postComment the extra params. for example:
final String comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
final String name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
final String email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?comment="+comment+"&name="+name+"&email="+email;
You can send the parameters as JSONObject like this:
JSONObject params = new JSONObject("{\"post\":\"" + comtUrl + "\"," +
...
+ "}"
and in JsonObjectRequest you pass it as the third parameter.. you will not need getBodyContentType and getParams anymore