我是通过php传递的,现在可以把全部数据传递过来,但是不知道怎么传递数据过去并且返回?而且listview不会刷新。
Android的代码:
private void getAdapter() {
String url = "http://192.168.21.46/Library/books_list.php";
HttpConnectionUtil connUtil = new HttpConnectionUtil();
connUtil.asyncConnect(url, HttpMethod.POST,
new HttpConnectionCallback() {
@Override
public void execute(String response) {
books = JsonToList(response);
setInAdapter();
listView.setAdapter(adapter);
}
});
}
/**
* 将数据配入ListView中
*/
protected void setInAdapter() {
List<Map<String, String>> lists = new ArrayList<Map<String, String>>();
// 将persons中的数据转换到ArrayList<Map<String,String>>中
// String>>中,因为SimpleAdapter要用这个类型的数据进行适配
Map<String, String> map;
for (Book b : books) {
map = new HashMap<String, String>();
map.put("id", b.getId());
map.put("author", b.getAuthor());
map.put("name", b.getName());
map.put("press", b.getPress());
lists.add(map);
}
// HashMap<String, String>中的key
String[] from = { "id", "author", "name", "press" };
// list_item.xml中对应的控件ID
int[] to = { R.id.lb_lv_id, R.id.lb_lv_author, R.id.lb_lv_bookname,
R.id.lb_lv_press };
adapter = new SimpleAdapter(this, lists, R.layout.listview, from, to);
}
protected List<Book> JsonToList(String response) {
List<Book> list = new ArrayList<Book>();
try {
JSONObject jObiect = new JSONObject(response);
JSONArray array = jObiect.getJSONArray("books");
// // 将字符串转换为Json数组
// JSONArray array = new JSONArray(response);
// 数组长度
length = array.length();
for (int i = 0; i < length; i++) {
// 将每一个数组再转换成Json对象
JSONObject obj = array.getJSONObject(i);
book = new Book();
book.setId(obj.getString("id"));
book.setAuthor(obj.getString("author"));
book.setName(obj.getString("name"));
book.setPress(obj.getString("press"));
list.add(book);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
PHP的代码:
if(isset($_GET['classify'])){
$classify = $_GET['classify'];
if($classify == "全部"){
$sql_select = mysql_query("select * from books");
}
else{
$sql_select = mysql_query("select * from books where b_classify = '$classify'");
}
if(!empty($sql_select)){
if(mysql_num_rows($sql_select) > 0) {
// looping through all results
// products node
$response["books"] = array();
while(!!$row= mysql_fetch_array($sql_select)) {
// temp user array
$book= array();
$book["id"] = $row["b_id"];
$book["name"] = $row["b_name"];
$book["author"] = $row["b_author"];
$book["press"] = $row["b_press"];
// push single product into final response array
array_push($response["books"], $book);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
}
如图,就是可以把”计算机“的字符传递过去,然后返回计算机类的数据填写在listview,并且listview刷新!!!