Adam
Adam

Reputation: 9049

Multidimensional arrays with the day as a key

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


    }



}

I essentially want thedate to be an array containing JSONObjects. My app crashes with what I have now. I'm not sure if you're able to do this. Does Java have anything like push or add?

Upvotes: 0

Views: 384

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

It's a bit crazy to use a Date as an array index. Use a HashMap<Date, JSONObject> instead for this.

If you want to have one Date be associated with multiple JSONObjects, then perhaps you want to use a Map that holds a List: HashMap<Date, List<JSONObject>>

Upvotes: 0

4ndrew
4ndrew

Reputation: 16252

You forgot to create an array before initialize (I think you are getting NullPointerException in your sample code):

monthArray = new JSONObject[32][32];

Also, may be HashMap will be more useful for that task.

UPD Ops, and one question, why do you need two dimensional array? I think one dimension is enough.

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

UPD2 And I recommend to use Calendar instead of Date and SimpleDateFormat. It is more correct way, for example:

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

Update after comments. If more than one event can occurs in one day then you have use HashMap with List as I proposed.

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

Upvotes: 1

Related Questions