'Android Volley getParams() method not getting called for JsonObjectRequest
I have overrided getParams()
, and mEmail
, mUsername
etc. are globally declared.
@Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new Hashtable<String, String>();
params.put("Email", mEmail.getText().toString().trim());
params.put("Username",mUsername.getText().toString().trim());
params.put("Password",mPassword.getText().toString().trim());
params.put("BirthDay",mBirthday.getText().toString().replaceAll("\\s","-"));
params.put("Sex",SelectedRadio());
params.put("Bitmap",getEncodedBitmap());
return params;
}
This is my server side code:
<?php
require "init1.php";
$email = $_POST["Email"];
$password = $_POST["Password"];
$Username = $_POST["Username"];
$Sex = $_POST["Sex"];
$ProfilePicture = $_POST["Bitmap"];
$timestamp = strtotime($_POST["BirthDay"]);
$BirthDay = date('Y-m-d',$timestamp);
$sql = "select * from Registered_Users where Username='$Username'";
$sqle = "select * from Registered_Users where Email='$email'";
try{
$result1 = mysqli_query($con, $sqle) or die(mysqli_error($con));;
$result = mysqli_query($con, $sql) or die(mysqli_error($con));;
} catch(Exception $e) {
echo $e->getMessage();
}
if (mysqli_num_rows($result) > 0){
$myclass = new stdClass();
$myclass->status="Not Ok";
echo json_encode($myclass);
} else if(mysqli_num_rows($result1) > 0) {
$myclass = new stdClass();
$myclass->status="Not Ok";
echo json_encode($myclass);
} else{
try{
$sql_query = "insert into Registered_Users (Email, Password, BirthDay, Sex, Username, ProfilePicture) values('$email', '$password', '$BirthDay', '$Sex', '$Username', '$ProfilePicture')";
if(mysqli_query($con,$sql_query)){
$obj1 = new stdClass();
$obj1->status="Ok";
echo json_encode($obj1);
} else {
$obj1 = new stdClass();
$obj1->status="Not Ok ";
}
} catch(Exception $e) {
echo $e->getMessage();
}
}
?>
The response I am getting is always not ok
, becasuse I already have an empty row in my database, and I am trying upload an empty row again. Can someone tell why I am not able to get the data? Why am I getting empty data?
Solution 1:[1]
use this Custom volley request class
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.Map;
public class CustomJsonRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomJsonRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomJsonRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
@Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
return params;
}
;
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
you can use it with
Map<String,String> params = new Hashtable<String, String>();
params.put("Email", mEmail.getText().toString().trim());
params.put("Username",mUsername.getText().toString().trim());
params.put("Password",mPassword.getText().toString().trim());
params.put("BirthDay",mBirthday.getText().toString().replaceAll("\\s","-"));
params.put("Sex",SelectedRadio());
params.put("Bitmap",getEncodedBitmap());
CustomJsonRequest request = new CustomJsonRequest(Request.Method.POST, url, params,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().getRequestQueue().add(request);
Actually this a issue with sending parameters with volley. Check this answer https://stackoverflow.com/a/27091088/1320616
EDIT: Explanation for this behaviour
your JsonObjectRequest class extends from JsonRequest which extends from Request.
inside your Request class there is a method
/**
* Returns the raw POST or PUT body to be sent.
*
* <p>By default, the body consists of the request parameters in
* application/x-www-form-urlencoded format. When overriding this method, consider overriding
* {@link #getBodyContentType()} as well to match the new body format.
*
* @throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
notice that this method is calling getParams() method. It is the same method that you are overriding while making the call.
But if you look inside JsonRequest class, there is a method
@Override
public byte[] getBody() {
try {
return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, PROTOCOL_CHARSET);
return null;
}
}
it means the getBody() of Request has been overridden by getBody() of JsonRequest class which means your getParams() will never get called. So you need a custom class which directly extends Request class and doesn't override the getBody() method of Request class.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |