我通过传递汉堡和$ _POST ['category']并使用邮递员发送了邮寄请求,而iam则采用以下格式:
{
"items": [
{
"title": "Beef Burger",
"price": "10"
},
{
"title": "Pug Burger",
"price": "12"
},
{
"title": "Green-Chile Burger with Fried Eggs",
"price": "15"
},
{
"title": "Minetta Burger",
"price": "8"
},
{
"title": "Cheese Burger",
"price": "13"
}
]
}
<?php
$connection = mysqli_connect("localhost", "root", "", "mydb");
if(!$connection){
die("Connection Failure");
}
else{
$category = $_POST['category'];
$response['items'] = array();
$sql = "SELECT * FROM item WHERE category = '$category'";
$result = mysqli_query($connection, $sql);
if((mysqli_num_rows($result)) > 0){
while($rows = mysqli_fetch_assoc($result)){
$item['title'] = $rows['title'];
$item['price'] = $rows['price'];
array_push($response['items'], $item);
}
}
header('Content-Type: application/json');
echo json_encode($response);
mysqli_close($connection);
}
?>
public class Item extends AppCompatActivity {
List<DataInformation> informationList;
RequestQueue requestQueue;
ListView listView;
String URL = "http://192.168.137.1/MyMobileProject/getItem.php";
DataInformationAdapter adapter;
String category;//the post string
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.itemlayout);
Bundle bundle = getIntent().getExtras();
if(bundle != null) {
category = bundle.getString("category");//can be burger-pizza-drinks
}
informationList = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();
JSONArray items = response.getJSONArray("items");
for(int i = 0; i < items.length(); i++){
JSONObject item = items.getJSONObject(i);
String s1 = item.getString("title");
int s2 = item.getInt("price");
DataInformation dataInformation = new DataInformation(s1, s2);
informationList.add(dataInformation);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("category", category);//category value is taken from intent
return params;
}
};
requestQueue.add(jsonObjectRequest);
adapter = new DataInformationAdapter(Item.this, R.layout.itemlayout2, informationList);
listView = (ListView)findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
列表信息列表应使用php json编码构建,然后传递给CustomAdapter并构建列表视图。