0

所以我根据我找到的教程创建了一个日历。在我尝试自定义它之前它一直有效。

我想要做的是存储光标信息,private ArrayList<HashMap<String, String>> list;然后将其传递给日历片段,以便在那里显示/隐藏该日期的图像。但是,我在这一部分遇到了严重的失败:

    for (HashMap<String, String> map : list)
         for (Entry<String, String> mapEntry : map.entrySet()){
                String key = mapEntry.getKey();
                String value = mapEntry.getValue();
                Log.i("PROJECTCARUSO", "key: "+ key + " value:" + value);
         }

当然,我并不想在这里显示或隐藏,而只是遍历我的地图。任何人都可以帮忙吗?

public class CalendarFragment extends Fragment {

public GregorianCalendar month, itemmonth;// calendar instances.
public CalendarAdapter adapter;           // adapter instance
public Handler handler;                   // for grabbing some event values for showing the dot
                                          // marker.
public ArrayList<String> items;           // container to store calendar items which
                                          // needs showing the event marker

static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }     

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     
        View view = inflater.inflate(R.layout.fragment_calendar, null);

        Locale.setDefault( Locale.US );
        month = (GregorianCalendar) GregorianCalendar.getInstance();
        itemmonth = (GregorianCalendar) month.clone();

        items = new ArrayList<String>();
        adapter = new CalendarAdapter(getActivity(), month);

        GridView gridview = (GridView) view.findViewById(R.id.gridview);
        gridview.setAdapter(adapter);

        handler = new Handler();
        handler.post(calendarUpdater);

        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));

        RelativeLayout previous = (RelativeLayout) view.findViewById(R.id.previous);

        previous.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                setPreviousMonth();
                refreshCalendar();
            }
        });

        RelativeLayout next = (RelativeLayout) view.findViewById(R.id.next);
        next.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                setNextMonth();
                refreshCalendar();

            }
        });

        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {

                ((CalendarAdapter) parent.getAdapter()).setSelected(v);
                String selectedGridDate = CalendarAdapter.dayString
                        .get(position);
                String[] separatedTime = selectedGridDate.split("-");
                String gridvalueString = separatedTime[2].replaceFirst("^0*",
                        "");// taking last part of date. ie; 2 from 2012-12-02.
                int gridvalue = Integer.parseInt(gridvalueString);
                // navigate to next or previous month on clicking offdays.
                if ((gridvalue > 10) && (position < 8)) {
                    setPreviousMonth();
                    refreshCalendar();
                } else if ((gridvalue < 7) && (position > 28)) {
                    setNextMonth();
                    refreshCalendar();
                }
                ((CalendarAdapter) parent.getAdapter()).setSelected(v);

                showToast(selectedGridDate);

            }
        });
        return view;
    }

    protected void setNextMonth() {
        if (month.get(GregorianCalendar.MONTH) == month
                .getActualMaximum(GregorianCalendar.MONTH)) {
            month.set((month.get(GregorianCalendar.YEAR) + 1),
                    month.getActualMinimum(GregorianCalendar.MONTH), 1);
        } else {
            month.set(GregorianCalendar.MONTH,
                    month.get(GregorianCalendar.MONTH) + 1);
        }

    }

    protected void setPreviousMonth() {
        if (month.get(GregorianCalendar.MONTH) == month
                .getActualMinimum(GregorianCalendar.MONTH)) {
            month.set((month.get(GregorianCalendar.YEAR) - 1),
                    month.getActualMaximum(GregorianCalendar.MONTH), 1);
        } else {
            month.set(GregorianCalendar.MONTH,
                    month.get(GregorianCalendar.MONTH) - 1);
        }

    }

    protected void showToast(String string) {
        Toast.makeText(getActivity(), string, Toast.LENGTH_SHORT).show();

    }

    public void refreshCalendar() {
        TextView title = (TextView) getActivity().findViewById(R.id.title);

        adapter.refreshDays();
        adapter.notifyDataSetChanged();
        handler.post(calendarUpdater); // generate some calendar items

        title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
    }

    public Runnable calendarUpdater = new Runnable() {

        @SuppressWarnings("static-access")
        @Override
        public void run() {
            items.clear();

            // Print dates of the current week
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
            String itemvalue;


            //start date for cursor
            String startdate = df.format(month.getTime());

            //end date
            month.add(month.MONTH, 1);
            String enddate = df.format(month.getTime());
            month.add(month.MONTH, -1);

            // Get the data
            Cursor c = getActivity().getContentResolver().query(StatusProvider.CONTENT_URI_CHARTING, null, "? < " + StatusData.KEY_CHARTING_DATE + " AND ? > " + StatusData.KEY_CHARTING_DATE , new String[] {startdate, enddate}, null); //

            getActivity().startManagingCursor(c);
            c.moveToFirst();

            //int i = 0;
            if (c.getCount()>0 && c!=null) {
                while (c.isAfterLast() == false) 
                {

                itemvalue = df.format(itemmonth.getTime());
                itemmonth.add(GregorianCalendar.DATE, 1);
                items.add(c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_DATE)));

                c.moveToNext();
                } 
            }

            HashMap<String,String> temp = new HashMap<String,String>();  
            c.moveToFirst();
            while(c.moveToNext()){
                Log.i("PROJECTCARUSO", "Adding to HashMap");
                temp.put(StatusData.KEY_CHARTING_DATE, c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_DATE)));
                temp.put(StatusData.KEY_CHARTING_PERIOD, c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_PERIOD)));
                temp.put(StatusData.KEY_CHARTING_INTERCORSE, c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_INTERCORSE)));
                temp.put(StatusData.KEY_CHARTING_MOOD, c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_MOOD)));
                temp.put(StatusData.KEY_CHARTING_HEADACHE, c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_HEADACHE)));
                temp.put(StatusData.KEY_CHARTING_TEST, c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_TEST)));
                temp.put(StatusData.KEY_CHARTING_ENERGY, c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_ENERGY)));
                list.add(temp);
            } 

            adapter.setItems(items, list);
            adapter.notifyDataSetChanged();
        }
    };

}

帮手:

public class CalendarAdapter extends BaseAdapter {
    private Context mContext;
    ArrayList<Record> members = new ArrayList<Record>(); 
    private java.util.Calendar month;
    public GregorianCalendar pmonth; // calendar instance for previous month
    /**
     * calendar instance for previous month for getting complete view
     */
    public GregorianCalendar pmonthmaxset;
    private GregorianCalendar selectedDate;
    int firstDay;
    int maxWeeknumber;
    int maxP;
    int calMaxP;
    int lastWeekDay;
    int leftDays;
    int mnthlength;
    String itemvalue, curentDateString;
    DateFormat df;

    private ArrayList<String> items;
    public static List<String> dayString;
    private View previousView;
    private ArrayList<HashMap<String, String>> list;

    public CalendarAdapter(Context c, GregorianCalendar monthCalendar) {
        CalendarAdapter.dayString = new ArrayList<String>();
         Locale.setDefault( Locale.US );
        month = monthCalendar;
        selectedDate = (GregorianCalendar) monthCalendar.clone();
        mContext = c;
        month.set(GregorianCalendar.DAY_OF_MONTH, 1);
        this.items = new ArrayList<String>();
        df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        curentDateString = df.format(selectedDate.getTime());
        refreshDays();
    }

    public void setItems(ArrayList<String> items, ArrayList<HashMap<String, String>> list) {

        this.items = items;
        this.list = list;
    }

    public int getCount() {
        return dayString.size();
    }

    public Object getItem(int position) {
        return dayString.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new view for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        TextView dayView;
        if (convertView == null) { // if it's not recycled, initialize some
                                    // attributes
            LayoutInflater vi = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.calendar_item, null);

        }
        dayView = (TextView) v.findViewById(R.id.date);

        // separates daystring into parts.
        String[] separatedTime = dayString.get(position).split("-");

        // taking last part of date. ie; 2 from 2012-12-02
        String gridvalue = separatedTime[2].replaceFirst("^0*", "");
        // checking whether the day is in current month or not.
        if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
            // setting offdays to white color.
            dayView.setTextColor(Color.WHITE);
            dayView.setClickable(false);
            dayView.setFocusable(false);
        } else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
            dayView.setTextColor(Color.WHITE);
            dayView.setClickable(false);
            dayView.setFocusable(false);
        } else {
            // setting curent month's days in blue color.
            dayView.setTextColor(Color.BLUE);
        }

        if (dayString.get(position).equals(curentDateString)) {
            setSelected(v);
            previousView = v;
        } else {
            v.setBackgroundResource(R.drawable.list_item_background);
        }
        dayView.setText(gridvalue);

        // create date string for comparison
        String date = dayString.get(position);

        if (date.length() == 1) {
            date = "0" + date;
        }
        String monthStr = "" + (month.get(GregorianCalendar.MONTH) + 1);
        if (monthStr.length() == 1) {
            monthStr = "0" + monthStr;
        }



        for (HashMap<String, String> map : list)
             for (Entry<String, String> mapEntry : map.entrySet()){
                    String key = mapEntry.getKey();
                    String value = mapEntry.getValue();
                    Log.i("PROJECTCARUSO", "key: "+ key + " value:" + value);
                }


        return v;       
    }

    public View setSelected(View view) {


        if (previousView != null) {
            previousView.setBackgroundResource(R.drawable.list_item_background);
        }


        previousView = view;
        view.setBackgroundResource(R.drawable.calendar_cel_selectl);
        return view;
    }

    public void refreshDays() {
        // clear items
        list.clear();

        dayString.clear();
        Locale.setDefault( Locale.US );
        pmonth = (GregorianCalendar) month.clone();


        // month start day. ie; sun, mon, etc
        firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);


        // finding number of weeks in current month.
        maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);


        // allocating maximum row number for the gridview.
        mnthlength = maxWeeknumber * 7;
        maxP = getMaxP(); // previous month maximum day 31,30....
        calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...


        /**
         * Calendar instance for getting a complete gridview including the three
         * month's (previous,current,next) dates.
         */


        pmonthmaxset = (GregorianCalendar) pmonth.clone();
        /**
         * setting the start date as previous month's required date.
         */
        pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);

        /**
         * filling calendar gridview.
         */
        for (int n = 0; n < mnthlength; n++) {

            itemvalue = df.format(pmonthmaxset.getTime());
            pmonthmaxset.add(GregorianCalendar.DATE, 1);
            dayString.add(itemvalue);

        }
    }

    private int getMaxP() {
        int maxP;
        if (month.get(GregorianCalendar.MONTH) == month
                .getActualMinimum(GregorianCalendar.MONTH)) {
            pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
                    month.getActualMaximum(GregorianCalendar.MONTH), 1);
        } else {
            pmonth.set(GregorianCalendar.MONTH,
                    month.get(GregorianCalendar.MONTH) - 1);
        }
        maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);

        return maxP;
    }

}

下面的代码应该可以工作:

for (HashMap<String, String> map : list)
     for (String key : map.keySet()){
            String value = map.getValue();
            Log.i("PROJECTCARUSO", "key: "+ key + " value:" + value);
     }
4

2 回答 2

1

当您调用gridview.setAdapter(adapter);GridView准备显示元素时,它会getView在您的适配器上调用。

那时,list您的适配器内部是空的,您会得到一个NullPointerException,因为它发生在调用setItems.

“修复”它的最简单方法是初始化list

private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

或在循环之前检查 null:

if (list != null) {
    for (HashMap<String, String> map : list) {
        for (Entry<String, String> mapEntry : map.entrySet()){
            String key = mapEntry.getKey();
            String value = mapEntry.getValue();
            Log.i("PROJECTCARUSO", "key: "+ key + " value:" + value);
        }
    }
}
于 2013-06-13T22:12:41.787 回答
0

下面的代码应该可以工作:

for (HashMap<String, String> map : list)
     for (String key : map.keySet()){
            String value = map.getValue();
            Log.i("PROJECTCARUSO", "key: "+ key + " value:" + value);
     }
于 2013-06-13T22:07:11.250 回答