我从向我的服务器发送参数时收到一个错误,好像我的参数根本没有传递到我的服务器...我得到的是:
D/Searching: Error: org.json.JSONException: Value {"error_msg":"please choose city to view taxi list"}
只有在我的服务器端设置($_POST['from'] 等)时才会出现该消息
这是我的代码:
// 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);
这是 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
}
]
这里是我服务器中的 php 代码:
<?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);
}
?>
代码中有语法错误吗?
编辑 这是我使用 CustomJsonRequest 后的 logcat
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: []
最佳答案
前几天我遇到了同样的问题。这不是您的代码的问题。实际上,JsonArrayRequest 类扩展了 JsonRequest,后者扩展了 Request。 在 JsonRequest 类中,getBody() 方法已被覆盖,看起来是这样
@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;
}
}
如果你仔细观察getParams()
方法未被调用。
所以我所做的就是创建一个 new CLASS
延伸 Request<JsonArrayRequest>
像这样
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);
}
}
您可以覆盖此类中的 getParams() 方法,并像这样将其用于您的请求。
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) {
}
});
希望对您有所帮助。谢谢
关于android - Volley ,不在 JsonArrayRequest 中传递任何参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36277467/