2017-07-12 156 views
-1

我正在開發它由一個新聞應用程序來顯示項目:數組列表排序按日期

標題,描述,時間,日期

的日期格式爲:2017年12月7日

當我添加多重新聞時,他們隨機顯示在recyclerview上。

什麼是使用比較對象按日期排序ArrayList中,所以當我添加的新聞必須在recyclerview頂部顯示的最佳途徑。

這是我的工作代碼:

JSONArray array = new JSONArray(response); 
      JSONObject jsonObject = null; 
      post_array2.clear(); 
      Simplenews_data p; 
      for (int i = 0; i < array.length(); i++) { 
       jsonObject = array.getJSONObject(i); 

       int id_simplenews = jsonObject.getInt("id_simplenews"); 
       String name_simplenews = jsonObject.getString("name_simplenews"); 
       String image_simplenews = jsonObject.getString("image_simplenews"); 
       String desc_simplenews = jsonObject.getString("desc_simplenews"); 
       String time_simplenews = jsonObject.getString("time_simplenews"); 
       String date_simplenews = jsonObject.getString("date_simplenews"); 



       p = new Simplenews_data(); 
       p.setId_simplenews(id_simplenews); 
       p.setName_simplenews(name_simplenews); 
       p.setImage_simplenews(image_simplenews); 
       p.setDesc_simplenews(desc_simplenews); 
       p.setTime_simplenews(time_simplenews); 
       p.setDate_simplenews(date_simplenews); 

       post_array2.add(p); 

我已搜查,發現這個代碼,如果u有比較兩個整數,對於其他問題的工作原理:

Collections.sort(post_array, new Comparator<Standings_data>(){ 
       public int compare(Standings_data s1, Standings_data s2) { 
        return s1.getPts().compareToIgnoreCase(s2.getPts()); 
       } 
      }); 

但實際上我別有任何想法如何按這種日期格式排序,所以當消息來臨時,它顯示在recyclerview頂部而不是隨機的。

的現狀進行了簡單的截圖:

enter image description here

+2

使用SimpleDateFormat.parse()從字符串中創建Date對象,然後使用date的compareTo方法。 – Vucko

+0

請您發佈一些代碼 –

+0

我不會。你可以只爲谷歌我所說的,並輕鬆找到答案。但你寧願讓別人爲你做所有事情。爲此,還有一些網站,但您通常需要付費。乾杯。 – Vucko

回答

1

提取年,月,日的劈裂你的字符串:

String[] parts = date.split("/");

轉換成整數,然後比較年,月和一天。

是否應有效。

(Vucko答案是更好,如果你可以用SimpleDateFormat的解析)

+0

如果我這樣做,我怎樣才能讓recyclerview顯示了比較日期的項目? –

+0

那麼,RecyclerView顯示在同一順序上較ArrayList的項目。所以在顯示ArrayList之前排序ArrayList,或者在ArrayList排序後調用notifyDataSetChanged函數。 – Sigma

1

您可以在String秒值進行轉換,以Date就像Vucko建議,或者你可以將日期轉換爲ISO 8601格式,它們按字母順序排序。

ISO 8601的樣子YYYY-MM-DD所以按字母順序排序,這些爲字符串將由年,月,日,從而有效地按時間順序排序的字符串進行排序。

isodate = date.subString(5) + date.subString(0,2) + date.substring(3,4) 這會給你帶來1或2個數字(7對17)的日期的邊緣情況,但是這應該會鼓勵你使用更好的日期格式。您可以瞭解如何在這裏對ArrayList進行排序Sorting a collection of objects

+0

請給我看一些代碼 –

+0

我已經發布了一些代碼 –