0

我的应用程序有问题,它显示了一个网格视图/日历并在一个列表中。在加载此片段时进行调试时会崩溃,并且会出现 logcat。这是我的代码:

public class Fragment3 extends ListFragment implements OnClickListener
{
    private static final String tag = "SimpleCalendarViewActivity";

    private ImageView calendarToJournalButton;
    private Button selectedDayMonthYearButton;
    private Button currentMonth;
    private ImageView prevMonth;
    private ImageView nextMonth;
    private GridView calendarView;
    private GridCellAdapter adapter;
    private Calendar _calendar;
    private int month, year;
    private final DateFormat dateFormatter = new DateFormat();
    private static final String dateTemplate = "MMMM yyyy";
    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    // All static variables
    static final String URL = "http://www.testtesttest.netsons.org/Calendario.xml";
    // XML node keys
    static final String KEY_ITEM = "item";
    static final String KEY_ID = "ID";
    static final String KEY_DATA = "data";
    static final String KEY_TESTO = "testo";// parent node
    ListView list;

    /** Called when the activity is first created. */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 //CALENDARIO
        _calendar = Calendar.getInstance(Locale.ITALIAN);
        month = _calendar.get(Calendar.MONTH) + 1;
        year = _calendar.get(Calendar.YEAR);
        Log.d(tag, "Calendar Instance:= " + "Month: " + month + " " + "Year: " + year);

       /* selectedDayMonthYearButton = (Button) this.findViewById(R.id.selectedDayMonthYear);
        selectedDayMonthYearButton.setText("Selected: ");
*/
            prevMonth = (ImageView)this.getActivity().findViewById(R.id.prevMonth);
      //  prevMonth.setOnClickListener();

        currentMonth = (Button)this.getActivity().findViewById(R.id.currentMonth);
//            currentMonth.setText(dateFormatter.format(dateTemplate, _calendar.getTime()));

        nextMonth = (ImageView)this.getActivity().findViewById(R.id.nextMonth);
   //     nextMonth.setOnClickListener(this);

        calendarView = (GridView)this.getActivity().findViewById(R.id.calendar);

        // Initialised
        adapter = new GridCellAdapter(getActivity().getApplicationContext(), R.id.calendar_day_gridcell, month, year);
        adapter.notifyDataSetChanged();
        calendarView.setAdapter(adapter);
//LISTA
        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_ITEM);
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_DATA, parser.getValue(e, KEY_DATA));
            map.put(KEY_TESTO, parser.getValue(e, KEY_TESTO));

            // adding HashList to ArrayList
            menuItems.add(map);
        }
        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,R.layout.listcalendar,new String[] { KEY_DATA, KEY_TESTO }, new int[] {R.id.data, R.id.testo });

        setListAdapter(adapter);
        View V =inflater.inflate(R.layout.simple_calendar_view,null);
        list=(ListView)V.findViewById(android.R.id.list);

        // Getting adapter by passing xml data ArrayList


        // selecting single ListView item
        // listening to single listitem click
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting values from selected ListItem
          /*  String not = ((TextView) view.findViewById(R.id.not)).getText().toString();
            String testo = ((TextView) view.findViewById(R.id.testo)).getText().toString();


            // Starting new intent
            Intent in = new Intent(getActivity().getApplicationContext(), ImageGridActivity.class);
            in.putExtra(KEY_NOT, not);
            in.putExtra(KEY_TESTO, testo);
            getActivity().startActivity(in);
*/            }

        });

        return inflater.inflate(R.layout.simple_calendar_view, container, false);

    }

    /*
     *
     * @param month
     * @param year
     */
   private void setGridCellAdapterToDate(int month, int year)
{
    adapter = new GridCellAdapter(getActivity(), R.id.calendar_day_gridcell, month, year);
    _calendar.set(year, month - 1, _calendar.get(Calendar.DAY_OF_MONTH));
    currentMonth.setText(dateFormatter.format(dateTemplate, _calendar.getTime()));
    adapter.notifyDataSetChanged();
    calendarView.setAdapter(adapter);
}

@Override
public void onClick(View v)
{
    if (v == prevMonth)
    {
        if (month <= 1)
        {
            month = 12;
            year--;
        }
        else
        {
            month--;
        }
        Log.d(tag, "Setting Prev Month in GridCellAdapter: " + "Month: " + month + " Year: " + year);
        setGridCellAdapterToDate(month, year);
    }
    if (v == nextMonth)
    {
        if (month > 11)
        {
            month = 1;
            year++;
        }
        else
        {
            month++;
        }
        Log.d(tag, "Setting Next Month in GridCellAdapter: " + "Month: " + month + " Year: " + year);
        setGridCellAdapterToDate(month, year);
    }

}

@Override
public void onDestroy()
{
    Log.d(tag, "Destroying View ...");
    super.onDestroy();
}

// ///////////////////////////////////////////////////////////////////////////////////////
// Inner Class
public class GridCellAdapter extends BaseAdapter implements OnClickListener
{
    private static final String tag = "GridCellAdapter";
    private final Context _context;

    private final List<String> list;
    private static final int DAY_OFFSET = 1;
    private final String[] weekdays = new String[]{"Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"};
    private final String[] months = {"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"};
    private final int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    private final int month, year;
    private int daysInMonth, prevMonthDays;
    private int currentDayOfMonth;
    private int currentWeekDay;
    private Button gridcell;
    private TextView num_events_per_day;
    private final HashMap eventsPerMonthMap;
    private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy");

    // Days in Current Month
    public GridCellAdapter(Context context, int textViewResourceId, int month, int year)
    {
        super();
        this._context = context;
        this.list = new ArrayList<String>();
        this.month = month;
        this.year = year;

        Log.d(tag, "==> Passed in Date FOR Month: " + month + " " + "Year: " + year);
        Calendar calendar = Calendar.getInstance();
        setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
        setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
        Log.d(tag, "New Calendar:= " + calendar.getTime().toString());
        Log.d(tag, "CurrentDayOfWeek :" + getCurrentWeekDay());
        Log.d(tag, "CurrentDayOfMonth :" + getCurrentDayOfMonth());

        // Print Month
        printMonth(month, year);

        // Find Number of Events
        eventsPerMonthMap = findNumberOfEventsPerMonth(year, month);
    }
    private String getMonthAsString(int i)
    {
        return months[i];
    }

    private String getWeekDayAsString(int i)
    {
        return weekdays[i];
    }

    private int getNumberOfDaysOfMonth(int i)
    {
        return daysOfMonth[i];
    }

    public String getItem(int position)
    {
        return list.get(position);
    }

    @Override
    public int getCount()
    {
        return list.size();
    }

    /**
     * Prints Month
     *
     * @param mm
     * @param yy
     */
    private void printMonth(int mm, int yy)
    {
        Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy);
        // The number of days to leave blank at
        // the start of this month.
        int[] weekDaysToTraling = { 6, 0, 1, 2, 3, 4, 5 };

        int leadSpaces = 0;
        int daysInPrevMonth = 0;
        int prevMonth = 0;
        int prevYear = 0;
        int nextMonth = 0;
        int nextYear = 0;

        int currentMonth = mm - 1;
        String currentMonthName = getMonthAsString(currentMonth);
        daysInMonth = getNumberOfDaysOfMonth(currentMonth);

        Log.d(tag, "Current Month: " + " " + currentMonthName + " having " + daysInMonth + " days.");

        // Gregorian Calendar : MINUS 1, set to FIRST OF MONTH
        GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);
        Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());

        if (currentMonth == 11)
        {
            prevMonth = currentMonth - 1;
            daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
            nextMonth = 0;
            prevYear = yy;
            nextYear = yy + 1;
            Log.d(tag, "*->PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
        }
        else if (currentMonth == 0)
        {
            prevMonth = 11;
            prevYear = yy - 1;
            nextYear = yy;
            daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
            nextMonth = 1;
            Log.d(tag, "**--> PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
        }
        else
        {
            prevMonth = currentMonth - 1;
            nextMonth = currentMonth + 1;
            nextYear = yy;
            prevYear = yy;
            daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
            Log.d(tag, "***---> PrevYear: " + prevYear + " PrevMonth:" + prevMonth + " NextMonth: " + nextMonth + " NextYear: " + nextYear);
        }

        // Compute how much to leave before before the first day of the
        // month.
        // getDay() returns 0 for Sunday.
        int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
        int trailingSpaces = weekDaysToTraling[currentWeekDay];

        Log.d(tag, "Week Day:" + currentWeekDay + " is " + getWeekDayAsString(currentWeekDay));
        Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
        Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);

        if (cal.isLeapYear(cal.get(Calendar.YEAR)) && mm == 1)
        {
            ++daysInMonth;
        }

        // Trailing Month days
        for (int i = 0; i < trailingSpaces; i++)
        {
            Log.d(tag, "PREV MONTH:= " + prevMonth + " => " + getMonthAsString(prevMonth) + " " + String.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET) + i));
            list.add(String.valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET) + i) + "-GREY" + "-" + getMonthAsString(prevMonth) + "-" + prevYear);
        }

        // Current Month Days
        for (int i = 1; i <= daysInMonth; i++)
        {
            Log.d(currentMonthName, String.valueOf(i) + " " + getMonthAsString(currentMonth) + " " + yy);
            if (i == getCurrentDayOfMonth())
            {
                list.add(String.valueOf(i) + "-BLUE" + "-" + getMonthAsString(currentMonth) + "-" + yy);
            }
            else
            {
                list.add(String.valueOf(i) + "-WHITE" + "-" + getMonthAsString(currentMonth) + "-" + yy);
            }
        }

        // Leading Month days
        for (int i = 0; i < list.size() % 7; i++)
        {
            Log.d(tag, "NEXT MONTH:= " + getMonthAsString(nextMonth));
            list.add(String.valueOf(i + 1) + "-GREY" + "-" + getMonthAsString(nextMonth) + "-" + nextYear);
        }
    }

    /**
     * NOTE: YOU NEED TO IMPLEMENT THIS PART Given the YEAR, MONTH, retrieve
     * ALL entries from a SQLite database for that month. Iterate over the
     * List of All entries, and get the dateCreated, which is converted into
     * day.
     *
     * @param year
     * @param month
     * @return
     */
    private HashMap findNumberOfEventsPerMonth(int year, int month)
    {
        HashMap map = new HashMap<String, Integer>();
        // DateFormat dateFormatter2 = new DateFormat();
        //
        // String day = dateFormatter2.format("dd", dateCreated).toString();
        //
        // if (map.containsKey(day))
        // {
        // Integer val = (Integer) map.get(day) + 1;
        // map.put(day, val);
        // }
        // else
        // {
        // map.put(day, 1);
        // }
        return map;
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        if (row == null)
        {
            LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.calendar_day_gridcell, parent, false);
        }

        // Get a reference to the Day gridcell
        gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
        gridcell.setOnClickListener(this);

        // ACCOUNT FOR SPACING

        Log.d(tag, "Current Day: " + getCurrentDayOfMonth());
        String[] day_color = list.get(position).split("-");
        String theday = day_color[0];
        String themonth = day_color[2];
        String theyear = day_color[3];
        if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap != null))
        {
            if (eventsPerMonthMap.containsKey(theday))
            {
                num_events_per_day = (TextView) row.findViewById(R.id.num_events_per_day);
                Integer numEvents = (Integer) eventsPerMonthMap.get(theday);
                num_events_per_day.setText(numEvents.toString());
            }
        }

        // Set the Day GridCell
        gridcell.setText(theday);
        gridcell.setTag(theday + "-" + themonth + "-" + theyear);
        Log.d(tag, "Setting GridCell " + theday + "-" + themonth + "-" + theyear);

        if (day_color[1].equals("GREY"))
        {
            gridcell.setTextColor(Color.LTGRAY);
        }
        if (day_color[1].equals("WHITE"))
        {
            gridcell.setTextColor(Color.WHITE);
        }
        if (day_color[1].equals("BLUE"))
        {
            gridcell.setTextColor(getResources().getColor(R.color.static_text_color));
        }
        return row;
    }
    @Override
    public void onClick(View view)
    {
        String date_month_year = (String) view.getTag();
       // selectedDayMonthYearButton.setText("Selected: " + date_month_year);

        try
        {
            Date parsedDate = dateFormatter.parse(date_month_year);
            Log.d(tag, "Parsed Date: " + parsedDate.toString());

        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
    }

    public int getCurrentDayOfMonth()
    {
        return currentDayOfMonth;
    }

    private void setCurrentDayOfMonth(int currentDayOfMonth)
    {
        this.currentDayOfMonth = currentDayOfMonth;
    }
    public void setCurrentWeekDay(int currentWeekDay)
    {
        this.currentWeekDay = currentWeekDay;
    }
    public int getCurrentWeekDay()
    {
        return currentWeekDay;
    }
}

}

和空指针异常:

 calendarView.setAdapter(adapter);

这是日志猫:

java.lang.NullPointerException
    at com.example.scoutgo3.Fragment3.onCreateView(Fragment3.java:92)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1064)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
    at android.support.v4.view.ViewPager$3.run(ViewPager.java:242)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
    at android.view.Choreographer.doCallbacks(Choreographer.java:562)
    at android.view.Choreographer.doFrame(Choreographer.java:531)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)

希望任何人都可以帮助我,因为这个错误非常令人沮丧!!!!谢谢!

4

0 回答 0