2012-01-07 63 views
0
public void buildArrayForMonth(int month, int year, int numOfDays, JSONArray array){ 
    JSONObject[][] monthArray = null; 

    SimpleDateFormat monthFormat = new SimpleDateFormat("M"); 
    SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy"); 
    SimpleDateFormat dateFormat = new SimpleDateFormat("d"); 

    for(int i=0;i<array.length();i++){ 

     try { 
      JSONObject event = array.getJSONObject(i); 
      String date_full = event.getString("date_full"); 

      Date date = new Date(HttpDateParser.parse(date_full)); 
      int theMonth = Integer.parseInt(monthFormat.format(date)) - 1; 
      int theYear = Integer.parseInt(yearFormat.format(date)); 
      int theDate = Integer.parseInt(dateFormat.format(date)); 

      if(theMonth == month && theYear == year){ 
       System.out.println("This Month" + date_full); 
       monthArray[theDate][monthArray[theDate].length] = event; //add event object to the month array and its respective date 

      } 


     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


    } 



} 

我基本上希望date是一個包含JSONObjects的數組。我的應用程序崩潰,現在我擁有了。我不確定你是否能夠做到這一點。 Java有沒有像推或添加?以天爲鍵的多維數組

回答

1

你忘了創建初始化,然後一個數組(我覺得你得到你的示例代碼NullPointerException異常):

monthArray = new JSONObject[32][32]; 

而且,可能是HashMap的將是這一任務更加有用。

UPD Ops和一個問題,爲什麼你需要二維數組?我認爲一個維度就夠了。

JSONObject monthArray = new JSONObject[32]; 
monthArray[theDate] = event 

UPD2,我建議使用Calendar,而不是日期和SimpleDateFormat的。這是比較正確的做法,例如:意見後

Calendar c = Calendar.getCalendar(); 
c.setTimeInMillis(HttpDateParser.parse(date_full)); 
int theMonth = c.get(Calendar.MONTH); 
int theYear = c.get(Calendar.YEAR); 
int theDate = c.get(Calendar.DAY_OF_MONTH); 

UPD3

更新。如果一天內可能發生多個事件,那麼您可以按照我的建議使用帶有List的HashMap。

HashMap<Integer, List<JSONObject>> monthArray = new HashMap<Integer, List>(); 
... 
if (...) { 
    ... 
    List l = monthArray.get(theDate); 
    if (l == null) { 
     l = new LinkedList<JSONObject>(); 
    } 

    l.add(event); 

    monthArray.put(theDate, l); 
} 
+0

有可能在某一特定日期多個事件。 – Adam 2012-01-07 20:57:44

+0

@Adam:如果可以有多個事件,那麼爲什麼要使用Date作爲索引?這開始聞起來很有趣。 – 2012-01-07 21:03:37

+0

在這種情況下,您需要使用HashMap,其中日期作爲鍵和List作爲值。在Java中,你不能動態增加數組的長度,例如在php中。 – 4ndrew 2012-01-07 21:04:26

0

使用Date作爲數組索引有點瘋狂。爲此,請使用HashMap<Date, JSONObject>

如果你想有一個日期與多個一個JSONObjects相關聯,那麼也許你想用持有列表的地圖:HashMap<Date, List<JSONObject>>