我不知道这是否可行,但我想问一下,如何只使用一部分arraylist来填充listview。我的arraylist的内容来自mySQL数据库(我正在使用凌空)。它是具有category和item_name的项目列表。我想要做的是每当按下一个按钮(类别名称)时,与该类别相关联的item_names将显示在arrayList中。抱歉我的英语不好。
这是我的代码:这会显示我的listView中的所有项目。
import ...
public class Menu extends AppCompatActivity implements Response.Listener<String> {
final String TAG = this.getClass().getSimpleName();
public ListView itemList;
public ArrayList<myItem> itemList;
public myItemAdapter adapter;
Button Fruit, Meat, Dairy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
String category = "http://10.0.2.2/myPHP/item.php";
StringRequest stringRequestCategory = new StringRequest(Request.Method.GET, category, this, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error retrieving data", Toast.LENGTH_SHORT).show();
}
});
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequestCategory);
Fruit = (Button)findViewById(R.id.Fruit);
Fruit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//display the items with the category FRUIT
}
});
}
@Override
public void onResponse(String response) {
Log.d(TAG, response);
itemList = new JsonConverter<myItem>().toArrayList(response, myItem.class);
adapter = new myCategoryAdapter(getApplicationContext(), itemList);
itemList.setAdapter(adapter);
}
}
PHP代码:
<?php
include_once ("init.php");
$query = "SELECT * FROM tbl_item ORDER BY itemID ASC";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
echo json_encode($data);
?>
答案 0 :(得分:0)
在将列表发送到适配器之前,您必须先过滤列表。
假设您只想显示类别水果。
Fruit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ArrayList<myItem> filteredItems = new ArrayList<myItem>();
for (myItem item : itemList) {
// Not sure how your myItem class looks like but check category here.
if ("fruit".equals(item.getCategory())) {
filteredItems.add(item);
}
}
adapter.updateContent(filteredItems);
}
});
将此方法添加到适配器类,以便更新ListView中显示的项目。
public void updateContent(List<myItem> items) {
currentItems.clear();
currentItems.addAll(items);
notifyDataSetChanged();
}