排序 ArrayList<HashMap<String,String>> 基于日期时间
Sort ArrayList<HashMap<String,String>> based on datetime
我是 android 编程的新手,仍在学习它的概念,我目前正在构建一个应用程序,它将从在线数据库中获取一些数据并将其存储在 ArrayList> 类型中,然后我会显示数据,
我已经成功地从数据库中获取数据并成功地在 ListView 上显示了它,现在我想根据它的日期对数据进行排序(hashmap 中存储了一个日期值),
我已经阅读了如何在这些问题中做到这一点:
How to sort data of ArrayList of hashmap on The Basis of Date
我不太明白这个概念,仍然不知道如何使用我当前的代码。希望你能帮助我的代码,
这是我的代码:
public class Notification extends Activity {
userSessionManager session;
String Username, clickedId, clickedTitle, toastMessage;
String urlUpdateGroupConfirmation, urlGetNotif;
JSONParser jsonParser;
ProgressDialog pd;
JSONArray jsonArray = null;
private ArrayList<HashMap<String, String>> whatsNew;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
getActionBar().setDisplayShowHomeEnabled(false);
sessionAndDeclaration();
new AttemptParseNotification().execute();
}
private void sessionAndDeclaration() {
// TODO Auto-generated method stub
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
Username = user.get(userSessionManager.KEY_USERNAME);
myIP ip = new myIP();
String publicIp = ip.getIp();
String thisPhp = "viewMyNotification.php";
String updateGConf = "doUpdateGroupDetail.php";
urlGetNotif = publicIp + thisPhp;
urlUpdateGroupConfirmation = publicIp + updateGConf;
jsonParser = new JSONParser();
whatsNew = new ArrayList<HashMap<String, String>>();
}
class myMapComparator implements Comparator<Map<String, String>> {
@Override
public int compare(Map<String, String> lhs, Map<String, String> rhs) {
// TODO Auto-generated method stub
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return df.parse(lhs.get("date")).compareTo(
df.parse(rhs.get("date")));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
}
class AttemptParseNotification extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(Notification.this);
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.setMessage("Loading...");
pd.show();
}
@Override
protected Boolean doInBackground(Void... arg0) {
// TODO Auto-generated method stub
int success = 0;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
Log.d("Request!", "Passing Username to server");
JSONObject json = jsonParser.makeHttpRequest(urlGetNotif,
"POST", params);
success = json.getInt("success");
if (success == 1) {
Log.d("Response", "Getting todays");
jsonArray = json.getJSONArray("array");
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String newId = c.getString("id");
String newType = c.getString("type");
String newTitle = c.getString("title");
String newDisplayed = newTitle + "(" + newType
+ ")";
String newDate = c.getString("date");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", newId);
map.put("title", newTitle);
map.put("date", newDate);
map.put("type", newType);
map.put("displayed", newDisplayed);
whatsNew.add(map);
Collections.sort(whatsNew, new myMapComparator());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
if (whatsNew.size() > 0) {
viewNews();
} else {
Toast.makeText(getBaseContext(), "No new notification",
Toast.LENGTH_LONG).show();
}
}
}
public void viewNews() {
// TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.lv_notif);
ListAdapter adapter = new SimpleAdapter(this, whatsNew,
R.layout.notificationlist_item, new String[] { "title", "type",
"date" }, new int[] { R.id.title_notif,
R.id.type_notif, R.id.date_notif });
lv.setAdapter(adapter);
}
}
在将所有数据添加到 "whatsNew" 列表的循环之后,您需要调用比较器对列表进行排序。
将此行添加到 "doInBackground" 之前 "return null"...
Collections.sort(whatsNew, new myMapComparator());
(旁注:您可能已经知道,在 Java 中,约定是以大写字母开头的 class 名称)
正如我建议使用 TreeSet
而不是 Collections.sort
,
这是粗略的例子,
public static Set<HashMap<String, String>> mySet = new TreeSet<>(new Comparator<HashMap<String, String>>() {
@Override
public int compare(HashMap<String, String> o1, HashMap<String, String> o2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return df.parse(o1.get("date")).compareTo(
df.parse(o2.get("date")));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
} }
});
b/w Collections.sort
和 TreeSet
的区别在于 TreeSet
使您的数据始终保持排序,而 Collections.sort()
方法会在您进行排序时对数据进行排序在您的 Set 上调用该方法。
例如,如果您在其中添加数据,即 mySet.add(yourData);
,它将按排序顺序添加。
我是 android 编程的新手,仍在学习它的概念,我目前正在构建一个应用程序,它将从在线数据库中获取一些数据并将其存储在 ArrayList> 类型中,然后我会显示数据,
我已经成功地从数据库中获取数据并成功地在 ListView 上显示了它,现在我想根据它的日期对数据进行排序(hashmap 中存储了一个日期值),
我已经阅读了如何在这些问题中做到这一点:
How to sort data of ArrayList of hashmap on The Basis of Date
我不太明白这个概念,仍然不知道如何使用我当前的代码。希望你能帮助我的代码,
这是我的代码:
public class Notification extends Activity {
userSessionManager session;
String Username, clickedId, clickedTitle, toastMessage;
String urlUpdateGroupConfirmation, urlGetNotif;
JSONParser jsonParser;
ProgressDialog pd;
JSONArray jsonArray = null;
private ArrayList<HashMap<String, String>> whatsNew;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
getActionBar().setDisplayShowHomeEnabled(false);
sessionAndDeclaration();
new AttemptParseNotification().execute();
}
private void sessionAndDeclaration() {
// TODO Auto-generated method stub
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
Username = user.get(userSessionManager.KEY_USERNAME);
myIP ip = new myIP();
String publicIp = ip.getIp();
String thisPhp = "viewMyNotification.php";
String updateGConf = "doUpdateGroupDetail.php";
urlGetNotif = publicIp + thisPhp;
urlUpdateGroupConfirmation = publicIp + updateGConf;
jsonParser = new JSONParser();
whatsNew = new ArrayList<HashMap<String, String>>();
}
class myMapComparator implements Comparator<Map<String, String>> {
@Override
public int compare(Map<String, String> lhs, Map<String, String> rhs) {
// TODO Auto-generated method stub
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return df.parse(lhs.get("date")).compareTo(
df.parse(rhs.get("date")));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
}
class AttemptParseNotification extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(Notification.this);
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.setMessage("Loading...");
pd.show();
}
@Override
protected Boolean doInBackground(Void... arg0) {
// TODO Auto-generated method stub
int success = 0;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
Log.d("Request!", "Passing Username to server");
JSONObject json = jsonParser.makeHttpRequest(urlGetNotif,
"POST", params);
success = json.getInt("success");
if (success == 1) {
Log.d("Response", "Getting todays");
jsonArray = json.getJSONArray("array");
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String newId = c.getString("id");
String newType = c.getString("type");
String newTitle = c.getString("title");
String newDisplayed = newTitle + "(" + newType
+ ")";
String newDate = c.getString("date");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", newId);
map.put("title", newTitle);
map.put("date", newDate);
map.put("type", newType);
map.put("displayed", newDisplayed);
whatsNew.add(map);
Collections.sort(whatsNew, new myMapComparator());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
if (whatsNew.size() > 0) {
viewNews();
} else {
Toast.makeText(getBaseContext(), "No new notification",
Toast.LENGTH_LONG).show();
}
}
}
public void viewNews() {
// TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.lv_notif);
ListAdapter adapter = new SimpleAdapter(this, whatsNew,
R.layout.notificationlist_item, new String[] { "title", "type",
"date" }, new int[] { R.id.title_notif,
R.id.type_notif, R.id.date_notif });
lv.setAdapter(adapter);
}
}
在将所有数据添加到 "whatsNew" 列表的循环之后,您需要调用比较器对列表进行排序。
将此行添加到 "doInBackground" 之前 "return null"...
Collections.sort(whatsNew, new myMapComparator());
(旁注:您可能已经知道,在 Java 中,约定是以大写字母开头的 class 名称)
正如我建议使用 TreeSet
而不是 Collections.sort
,
这是粗略的例子,
public static Set<HashMap<String, String>> mySet = new TreeSet<>(new Comparator<HashMap<String, String>>() {
@Override
public int compare(HashMap<String, String> o1, HashMap<String, String> o2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return df.parse(o1.get("date")).compareTo(
df.parse(o2.get("date")));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
} }
});
b/w Collections.sort
和 TreeSet
的区别在于 TreeSet
使您的数据始终保持排序,而 Collections.sort()
方法会在您进行排序时对数据进行排序在您的 Set 上调用该方法。
例如,如果您在其中添加数据,即 mySet.add(yourData);
,它将按排序顺序添加。