问题
I got an error from post parameters to my server, its like my params are not passing to my server at all...all I got is:
D/Searching: Error: org.json.JSONException: Value {"error_msg":"please choose city to view taxi list"}
that message only come out if isset($_POST['from'] so on in my serverside
here is my code:
// Creating volley request obj
JsonArrayRequest taxiReq = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Taxi taxi = new Taxi();
taxi.settaxiname(obj.getString("taxiname"));
taxi.setThumbnailUrl(obj.getString("image"));
taxi.setdeparture(obj.getString("departure"));
taxi.setarrive(obj.getString("arrive"));
taxi.setseat(obj.getInt("seat"));
taxi.setcost(obj.getInt("cost"));
// adding taxi to taxi array
taxiList.add(taxi);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
})
{
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("from", textfrom_btn);
params.put("to", textto_btn);
params.put("seat", totalpassenger);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(taxiReq);
here is the json:
[
{
"image": "http://localhost/androidapp/taxiprofile/1.jpg",
"taxiname": "Taxi 1",
"from": "PTK",
"to": "SGU",
"departure": "08:00:00",
"arrive": "13:00:00",
"seat": 7,
"cost": 12
},
{
"image": "http://localhost/androidapp/taxiprofile/default.jpg",
"taxiname": "Taxi 2",
"from": "PTK",
"to": "SGU",
"departure": "08:00:00",
"arrive": "13:00:00",
"seat": 2,
"cost": 15
},
{
"image": "http://localhost/androidapp/taxiprofile/2.jpg",
"taxiname": "Taxi Untung Selalu",
"from": "PTK",
"to": "SGU",
"departure": "09:00:00",
"arrive": "14:00:00",
"seat": 3,
"cost": 13
}
]
here my php code in my server:
<?php
include './include/DbHandler.php';
$db = new DbHandler();
// json response array
$response = array();
if (isset($_POST['from']) && isset($_POST['to']) && isset($_POST['totalpassenger'])) {
// receiving the post params
$from = $_POST['from'];
$to = $_POST['to'];
$totalpassenger = $_POST['totalpassenger'];
// get the user by email and password
$taxilist = $db->getTaxi($from, $to, $totalpassenger);
if ($taxilist != false) {
// taxi is found
foreach( $taxilist as $data ){
$response[] = array(
"image" => "http://".$_SERVER['SERVER_NAME'].dirname($_SERVER['REQUEST_URI']).$data["image"],
"taxiname" => $data["taxiname"],
"from" => $data["from"],
"to" => $data["to"],
"departure" => $data["departure"],
"arrive" => $data["arrive"],
"seat" => $data["seat"],
"cost" => $data["cost"]
);
}
echo json_encode($response);
} else {
$response["error_msg"] = "Sorry taxi is not listed";
echo json_encode($response);
}
} else {
$response["error_msg"] = "please choose city to view taxi list";
echo json_encode($response);
}
?>
is there any wrong syntax in code?
EDIT here is the logcat after I used CustomJsonRequest
03-29 16:11:06.070 25258-25258/com.testing W/EGL_genymotion: eglSurfaceAttrib not implemented
03-29 16:11:06.078 25258-25258/com.testing D/OpenGLRenderer: TextureCache::get: create texture(0xb85fe538): name, size, mSize = 389, 5184, 173360
03-29 16:11:06.082 25258-25258/com.testing D/OpenGLRenderer: TextureCache::get: create texture(0xb8489018): name, size, mSize = 391, 19264, 192624
03-29 16:11:55.714 25258-25258/com.testing D/Searching: []
回答1:
Day's before I had Faced the same problem. it's not the problem with your code. Actually JsonArrayRequest class extends JsonRequest which extends Request. In JsonRequest class getBody() method has been overrided and it looks so
@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;
}
}
If you look closely getParams() method is not called.
So what I did was to create a new CLASS which extends Request<JsonArrayRequest> like this
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<JSONArray> {
private Listener<JSONArray> 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<JSONArray> 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<JSONArray> 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(JSONArray response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
You can override the getParams() method in this class an use this for Your Request like this.
CustomJsonRequest request = new CustomJsonRequest(Request.Method.POST, url, params,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONArray response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
I hope this is helpful. ThankYou
回答2:
I had this problem last week and it had something to do with Volley not setting POST parameters in a correct way. Instead of fixing it i just went with a GET request and it looks like you could do the same since the parameters don't seem to be so very sensitive.
If you want to try a GET request you could do like this. Of course you have to switch from POST to GET in PHP as well!
The URL is created like this:
URL url = null;
String query = "?from=" + textfrom_btn +
"&to=" + textto_btn +
"&seat=" + totalpassenger;
try {
url = new URL("http", "www.Foo.com", "Bar.php" + query);
}catch (MalformedURLException ex){
ex.printStackTrace();
}
Request looks like this:
JsonArrayRequest taxiReq = new JsonArrayRequest(Request.Method.GET, url.toString(), null, new Response.Listener<JSONArray>(){
@Override
public void onResponse(JSONArray response){
for(int i = 0; i < response.length(); i++){
try{
JSONObject obj = response.getJSONObject(i);
Taxi taxi = new Taxi();
taxi.settaxiname(obj.getString("taxiname"));
taxi.setThumbnailUrl(obj.getString("image"));
taxi.setdeparture(obj.getString("departure"));
taxi.setarrive(obj.getString("arrive"));
taxi.setseat(obj.getInt("seat"));
taxi.setcost(obj.getInt("cost"));
// adding taxi to taxi array
taxiList.add(taxi);
}catch(JSONException e){
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
error.printStackTrace();
}
});
MyApplication.getInstance().addToRequestQueue(taxiReq);
}
来源:https://stackoverflow.com/questions/36277467/volley-not-passing-any-parameters-in-jsonarrayrequest