我想通过将参数传递给服务器并获取JSON数组来在sql中触发自定义查询。我使用Volley库来处理html请求。但是,使用以下代码我的应用程序冻结。我通过互联网搜索过,但我无法恢复。这是代码:
StringRequest postRequest = new StringRequest(Request.Method.POST, Config.serv_url, /*url to server*/ new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
int count = 0;
while(count<response.length()) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(count);
arrayList.add(new Album(jsonObject.getString("id")));
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new customImagesSwipe(arrayList,DisplayActivity.this);
viewPager.setAdapter(adapter);
}
}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DisplayActivity.this, "Error :- " + error, Toast.LENGTH_LONG).show();
}
}) {
// here is params will add to your url using post method
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("num", image); //value for param
//params.put("2ndParamName","valueoF2ndParam");
return params;
}
};
MySingleton.getMinstance(DisplayActivity.this).addToRequestQueue(postRequest);
这是PHP脚本:
<?php
$host = "localhost";
$user_name = "root";
$password = "";
$db_name = "imagesfromserver";
$con = mysqli_connect($host,$user_name,$password,$db_name);
$num = $_POST["num"];
$sql = "select * from album_info where (lower(id) LIKE 'num%');";
$result = mysqli_query($con,$sql);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array("id"=>$row["id"],"title"=>$row["title"]));
}
echo json_encode($response);
mysqli_close($con);
?>
我没有在客户端服务器上工作的先验知识。我是从互联网上搜索实现的。
更新
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, Config.serv_url, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
int count = 0;
while(count<response.length()){
try {
JSONObject jsonObject = response.getJSONObject(count);
arrayList.add(new Album(jsonObject.getString("id"), jsonObject.getString("title")));
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter = new customImagesSwipe(arrayList,DisplayActivity.this);
viewPager.setAdapter(adapter);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DisplayActivity.this,"NULL\n" + error,Toast.LENGTH_LONG ).show();
}
});
MySingleton.getMinstance(DisplayActivity.this).addToRequestQueue(jsonArrayRequest);