我以 json 形式获取数据,如
{"Users":[
{"category_id":"1","user_email":"a@a.com"},
{"category_id":"5","user_email":"a@b.com"},
{"category_id":"1","user_email":"a@c.com"},
{"category_id":"5","user_email":"a@d.com"},
{"category_id":"3","user_email":"a@d.com"}]}
现在我的问题是可以在 android 中过滤这个json基于category_id ,例如,如果我从我的微调器中选择1那么它应该返回满足category_id = 1示例的数据
{"Users":[{"category_id":"1","user_email":"a@a.com"},
{"category_id":"1","user_email":"a@c.com"}]}
如果选择3,那么它应该返回内容为category_id = 3
的用户{"Users":[
{"category_id":"3","user_email":"a@d.com"}]}
我只是想知道Android中是否有任何方法可用,所以我可以轻松过滤掉 数据
答案 0 :(得分:3)
首先,您需要在活动中创建变量
//URL to get JSON
private static String url = "your url to parse data";
//JSON Node Names
private static final String TAG_USERS = "users";
private static final String TAG_CATEGORY_ID = "category_id";
private static final String TAG_USER_EMAIL = "user_email";
// Data JSONArray
JSONArray users = null;
//HashMap to keep your data
ArrayList<HashMap<String, String>> userList;
在onCreate()函数中实例化你的userList
userList = new ArrayList<HashMap<String, String)>>();
然后你需要解析你的数据并在doInBackground()函数中填充这个ArrayList
//Create service handler class instance
ServiceHandler sh = new ServiceHandler();
//Url request and response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if(jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
//Get Json Array Node
users = jsonObj.getJSONArray(TAG_USERS);
// Looping through all data
for(int i = 0; i < users.length(); i++) {
JSONObject u = users.getJSONObject(i);
String category_id = u.getString(TAG_CATEGORY_ID);
String user_email = u.getString(TAG_USER_EMAIL);
// Temporary HashMap for single data
HashMap<String, String> user = new HashMap<String, String>();
// Adding each child node to Hashmap key -> value
user.put(TAG_CATEGORY_ID, category_id);
user.put(TAG_USER_EMAIL, user_email);
//Adding user to userList
userList.add(user);
}
}catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from url");
}
现在您将数据存储在userList中。您可以根据需要使用userList。要获取列表中的category_id字段,您可以使用此语法
// i being the counter of your loop
String catId = userList.get(i).get("category_id");
if(catId == 3) {
... your code
}
答案 1 :(得分:0)
使用Android SDK中的JSONObject。查看文档:
http://developer.android.com/reference/org/json/JSONObject.html
您基本上需要解析JSON,然后循环遍历并仅对具有指定类别ID的项目进行操作。
对于较大的数据集,如果正确编写,使用JsonReader将更具性能。
http://developer.android.com/reference/android/util/JsonReader.html
答案 2 :(得分:0)
最后我得到了答案..
private void applySearch(String searchStr) {
ArrayList<User> searchEmail = new ArrayList<User>();
for (int i = 0; i < UserArray.size(); i++) {
if(UserArray.get(i).getcategory_id().toLowerCase().contains(searchStr.toLowerCase())) {
searchEmail.add(UserArray.get(i));
}
}
// set the adapter hear
}
没有 for循环,这是不可能的...... UserArray 是我的数组列表内容用户对象