Java 排序数组列表<;HashMap<;字符串,字符串>&燃气轮机;基于日期时间

Java 排序数组列表<;HashMap<;字符串,字符串>&燃气轮机;基于日期时间,java,android,sorting,arraylist,hashmap,Java,Android,Sorting,Arraylist,Hashmap,我是android编程新手,还在学习它的概念,我正在构建一个应用程序,它将从在线数据库中获取一些数据,并将其存储在ArrayList>Type中,然后我将显示数据 我已经成功地从数据库中获取了数据,并成功地在ListView上显示了数据,现在我想根据数据的日期对数据进行排序(hashmap中存储了一个日期值) 我在这些问题中读到了如何做到这一点: 我并不真正理解这个概念,也不知道如何使用我当前的代码。希望你能帮我写代码 这是我的代码: public class Notification ext

我是android编程新手,还在学习它的概念,我正在构建一个应用程序,它将从在线数据库中获取一些数据,并将其存储在ArrayList>Type中,然后我将显示数据

我已经成功地从数据库中获取了数据,并成功地在ListView上显示了数据,现在我想根据数据的日期对数据进行排序(hashmap中存储了一个日期值)

我在这些问题中读到了如何做到这一点:

我并不真正理解这个概念,也不知道如何使用我当前的代码。希望你能帮我写代码

这是我的代码:

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);

}
}
公共类通知扩展活动{
用户会话管理器会话;
字符串用户名、clickedId、clickedTitle、toastMessage;
字符串urlUpdateGroupConfirmation,urlGetNotif;
JSONParser JSONParser;
进展性帕金森病;
JSONArray JSONArray=null;
私人ArrayList whatsNew;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
getActionBar().setDisplayShowHomeEnabled(false);
会议和宣言();
新建AttemptParseNotification().execute();
}
私有无效会话和声明(){
//TODO自动生成的方法存根
session=newusersessionmanager(getApplicationContext());
HashMap user=session.getUserDetails();
Username=user.get(userSessionManager.KEY\u用户名);
myIP=新的myIP();
字符串publicIp=ip.getIp();
String thisPhp=“viewMyNotification.php”;
字符串updateconf=“doUpdateGroupDetail.php”;
urlGetNotif=publicIp+thisPhp;
urlUpdateGroupConfirmation=publicIp+updateGConf;
jsonParser=新的jsonParser();
whatsNew=newarraylist();
}
类myMapComparator实现Comparator{
@凌驾
公共整数比较(地图左侧、地图右侧){
//TODO自动生成的方法存根
DateFormat df=新的简化格式(“yyyy-MM-dd HH:MM:ss”);
试一试{
返回df.parse(lhs.get(“日期”)).compareTo(
解析(rhs.get(“日期”));
}捕获(解析异常){
抛出新的IllegalArgumentException(e);
}
}
}
类AttemptParseNotification扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
super.onPreExecute();
pd=新进度对话框(通知。此);
pd.SetUndeterminate(假);
pd.可设置可取消(真);
pd.setMessage(“加载…”);
pd.show();
}
@凌驾
受保护的布尔doInBackground(无效…arg0){
//TODO自动生成的方法存根
int成功=0;
试一试{
List params=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,用户名));
d(“请求!”,“将用户名传递给服务器”);
JSONObject json=jsonParser.makeHttpRequest(urlGetNotif,
“POST”,params);
success=json.getInt(“success”);
如果(成功==1){
Log.d(“回复”、“今日获得”);
jsonArray=json.getJSONArray(“数组”);
试一试{
for(int i=0;i0){
查看新闻();
}否则{
Toast.makeText(getBaseContext(),“无新通知”,
Toast.LENGTH_LONG).show();
}
}
}
公共新闻{
//TODO自动生成的方法存根
ListView lv=(ListView)findViewById(R.id.lv_notif);
ListAdapter=new SimpleAdapter(此,whatsNew,
R.layout.notificationlist_项,新字符串[]{“title”,“type”,
“date”},新int[]{R.id.title_notif,
R.id.type_notif,R.id.date_notif});
低压设置适配器(适配器);
}
}

在将所有数据添加到“whatsNew”列表的循环之后,您需要调用比较器对列表进行排序

将此行添加到“返回null”之前的“doInBackground”


(旁注:您可能已经知道,在Java中,惯例是以大写字母开头类名)

正如我建议使用
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);
            }       }
    }); 
publicstaticset mySet=newtreeset(newcomparator(){
@凌驾
公共int比较(HashMap o1、HashMap o2){
DateFormat df=新的简化格式(“yyyy-MM-dd HH:MM:ss”);
试一试{
返回df.parse(o1.get(“日期”)).compareTo(
df.p
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);
            }       }
    });