2012-01-07 2 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(); 
     } 


    } 



} 

私は基本的にthedateがJSONObjectを含む配列であることを望んでいます。私のアプリは私が今持っているものでクラッシュします。あなたがこれを行うことができるかどうかはわかりません。 Javaにはpushやaddのようなものがありますか?あなたは初期化する前に配列を作成するのを忘れその日をキーとする多次元配列

答えて

1

(私はあなたのサンプルコードではNullPointerExceptionを得ていると思います):

monthArray = new JSONObject[32][32]; 

また、HashMapのは、そのタスクのために、より有用であろうことがあります。

UPD Opsと1つの質問、なぜ2次元配列が必要ですか?私は1つの次元で十分だと思う。

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

更新。 1日に複数のイベントが発生する場合は、提案したように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

+0

@Adam:複数のイベントが存在する可能性がある場合、なぜDateをインデックスとして使用したいのですか?これは面白いにおいがし始めています。 –

+0

その場合、HashMapを日付としてキーとListを値として使用する必要があります。 Javaでは、PHPのように配列の長さを動的に増やすことはできません。 – 4ndrew

0

配列インデックスとして日付を使用するのはちょっと狂っています。代わりにHashMap<Date, JSONObject>を使用してください。

あなたは1日は、おそらくあなたがリストを保持している地図を使用したい、その後、複数のJSONObjectsに関連付けられていることがしたい場合:HashMap<Date, List<JSONObject>>