我想将自定义日历中的事件显示为点图像。事件日期来自 json 解析,我已将该日期添加到 hashmap arraylist。然后,在我将该数组列表设置为我的日历适配器之后,但在那一刻它给了我空指针,并且在我的自定义日历中没有任何显示。所以请任何标准解决方案来解决这个问题?
public class Event extends Fragment implements OnClickListener {
GridView gv;
public GregorianCalendar month, itemmonth;
String itemvalue;
int Category_id;
public CalendarAdapter adapter;
public Handler handler;
public ArrayList<String> items;
RelativeLayout previous, next;
private static final int ID_ADD_EVENT = 1;
private static final int ID_PERSONAL = 2;
private static final int ID_BUSINESS = 3;
private static final int ID_MISC = 4;
private static final int ID_TODAY = 5;
Button btnSlideMenu, btnAction;
QuickAction quickAction;
InputStream is;
View v;
HashMap<String, String> map;
public static ArrayList<HashMap<String, String>> eventList = new ArrayList<HashMap<String, String>>();
String success, message, feed_id, feedtitle, description, type, eventDate,
categoryId, userid, username;
InterNetConnectionDetector isNet = new InterNetConnectionDetector(
getActivity());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.events, container, false);
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stp);
}
try {
new EventData().execute();
} catch (Exception e) {
// TODO: handle exception
}
Locale.setDefault(Locale.US);
month = (GregorianCalendar) GregorianCalendar.getInstance();
itemmonth = (GregorianCalendar) month.clone();
items = new ArrayList<String>();
Log.v("Size", eventList.size() + "");
adapter = new CalendarAdapter(getActivity(), month, eventList);
gv = (GridView) v.findViewById(R.id.calendar);
previous = (RelativeLayout) v.findViewById(R.id.previous);
next = (RelativeLayout) v.findViewById(R.id.next);
btnAction = (Button) v.findViewById(R.id.btnAction);
btnSlideMenu = (Button) v.findViewById(R.id.btnSildeMenu);
TextView title = (TextView) v.findViewById(R.id.title);
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
previous.setOnClickListener(this);
next.setOnClickListener(this);
btnAction.setOnClickListener(this);
btnSlideMenu.setOnClickListener(this);
gv.setAdapter(adapter);
handler = new Handler();
handler.post(calendarUpdater);
gv.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);
/*
* if (desc.size() > 0) { for (int i = 0; i < desc.size(); i++)
* { TextView rowTextView = new TextView(CalendarView.this);
*
* // set some properties of rowTextView or something
* rowTextView.setText("Event:" + desc.get(i));
* rowTextView.setTextColor(Color.BLACK);
*
* // add the textview to the linearlayout
* rLayout.addView(rowTextView);
*
* }
*
* }
*/
// desc = null;
}
});
ActionItem nextItem = new ActionItem(ID_ADD_EVENT, "Add New Event",
getResources().getDrawable(R.drawable.plus));
ActionItem prevItem = new ActionItem(ID_PERSONAL, "Personal", null);
ActionItem searchItem = new ActionItem(ID_BUSINESS, "Business", null);
ActionItem infoItem = new ActionItem(ID_MISC, "Misc", null);
ActionItem todayItem = new ActionItem(ID_TODAY, "Today", null);
prevItem.setSticky(true);
nextItem.setSticky(true);
quickAction = new QuickAction(getActivity(), QuickAction.VERTICAL);
// add action items into QuickAction
quickAction.addActionItem(nextItem);
quickAction.addActionItem(prevItem);
quickAction.addActionItem(searchItem);
quickAction.addActionItem(infoItem);
quickAction.addActionItem(todayItem);
// Set listener for action item clicked
quickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
@Override
public void onItemClick(QuickAction source, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
if (actionId == ID_ADD_EVENT) {
Intent n = new Intent(getActivity(),
Add_Event.class);
startActivity(n);
} else if (actionId == ID_PERSONAL) {
} else if (actionId == ID_BUSINESS) {
Toast.makeText(getActivity(),
"Let's do some search action",
Toast.LENGTH_SHORT).show();
} else if (actionId == ID_MISC) {
Toast.makeText(getActivity(),
"I have no info this time",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),
actionItem.getTitle() + " selected",
Toast.LENGTH_SHORT).show();
}
quickAction.dismiss();
}
});
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
@Override
public void onDismiss() {
/*
* Toast.makeText(getApplicationContext(), "Dismissed",
* Toast.LENGTH_SHORT).show();
*/
}
});
return v;
}
/*
* @Override protected void onCreate(Bundle savedInstanceState) { // TODO
* Auto-generated method stub super.onCreate(savedInstanceState);
* setContentView(R.layout.events);
*
* if (Build.VERSION.SDK_INT >= 8) { getActionBar().hide(); } if
* (android.os.Build.VERSION.SDK_INT > 8) {
*
* StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
* .permitAll().build(); StrictMode.setThreadPolicy(stp);
*
* }
*
* try { new EventData().execute(); } catch (Exception e) { // TODO: handle
* exception }
*
* Locale.setDefault(Locale.US); month = (GregorianCalendar)
* GregorianCalendar.getInstance(); itemmonth = (GregorianCalendar)
* month.clone();
*
* items = new ArrayList<String>(); adapter = new CalendarAdapter(this,
* month);
*
* gv = (GridView) this.findViewById(R.id.calendar); previous =
* (RelativeLayout) findViewById(R.id.previous); next = (RelativeLayout)
* findViewById(R.id.next); btnAction = (Button)
* findViewById(R.id.btnAction); btnSlideMenu = (Button)
* findViewById(R.id.btnSildeMenu); TextView title = (TextView)
* findViewById(R.id.title);
* title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
* previous.setOnClickListener(this); next.setOnClickListener(this);
* btnAction.setOnClickListener(this);
* btnSlideMenu.setOnClickListener(this); gv.setAdapter(adapter); handler =
* new Handler(); handler.post(calendarUpdater);
*
* gv.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);
*
* } }); ActionItem nextItem = new ActionItem(ID_ADD_EVENT, "Add New Event",
* getResources().getDrawable(R.drawable.plus)); ActionItem prevItem = new
* ActionItem(ID_PERSONAL, "Personal", null); ActionItem searchItem = new
* ActionItem(ID_BUSINESS, "Business", null); ActionItem infoItem = new
* ActionItem(ID_MISC, "Misc", null); ActionItem todayItem = new
* ActionItem(ID_MISC, "Today", null);
*
* prevItem.setSticky(true); nextItem.setSticky(true);
*
* quickAction = new QuickAction(this, QuickAction.VERTICAL);
*
* // add action items into QuickAction quickAction.addActionItem(nextItem);
* quickAction.addActionItem(prevItem);
* quickAction.addActionItem(searchItem);
* quickAction.addActionItem(infoItem);
* quickAction.addActionItem(todayItem);
*
* // Set listener for action item clicked quickAction
* .setOnActionItemClickListener(new QuickAction.OnActionItemClickListener()
* {
*
* @Override public void onItemClick(QuickAction source, int pos, int
* actionId) { ActionItem actionItem = quickAction.getActionItem(pos);
*
* if (actionId == ID_ADD_EVENT) {
*
* Intent n = new Intent(getApplicationContext(), Add_Event.class);
* startActivity(n);
*
* } else if (actionId == ID_PERSONAL) {
*
* } else if (actionId == ID_BUSINESS) {
* Toast.makeText(getApplicationContext(), "Let's do some search action",
* Toast.LENGTH_SHORT).show(); } else if (actionId == ID_MISC) {
* Toast.makeText(getApplicationContext(), "I have no info this time",
* Toast.LENGTH_SHORT).show(); } else {
* Toast.makeText(getApplicationContext(), actionItem.getTitle() +
* " selected", Toast.LENGTH_SHORT).show(); }
*
* quickAction.dismiss(); }
*
* });
*
* quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
*
* @Override public void onDismiss() {
*
* Toast.makeText(getApplicationContext(), "Dismissed",
* Toast.LENGTH_SHORT).show();
*
* } }); }
*/
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) v.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() {
@Override
public void run() {
items.clear();
// Print dates of the current week
/*
* SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",
* Locale.US);
*
* for (int i = 0; i < 7; i++) { itemvalue =
* df.format(itemmonth.getTime());
* itemmonth.add(GregorianCalendar.DATE, 1);
* items.add("2012-09-12"); items.add("2012-10-07");
* items.add("2012-10-15"); items.add("2012-10-20");
* items.add("2012-11-30"); items.add("2012-11-28"); }
*/
// adapter.setMoreItems(eventList);
adapter.setItems(items);
adapter.notifyDataSetChanged();
}
};
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.previous:
setPreviousMonth();
refreshCalendar();
break;
case R.id.next:
setNextMonth();
refreshCalendar();
break;
case R.id.btnAction:
quickAction.show(v);
break;
case R.id.btnSildeMenu:
try {
Sliding.viewActionsContentView.showActions();
} catch (Exception e) {
}
break;
default:
break;
}
}
public class EventData extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
SharedPreferences pref = getActivity()
.getSharedPreferences("ID", 0);
Category_id = pref.getInt("catId", 1);
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/all_events.php?&fromdate='2013-05-26'&todate='2013-07-06'&category_id="
+ Category_id;
Log.v("Event URL", url);
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
JSONArray jArray = jdata.getJSONArray("Eventdetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject meJson = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
feed_id = meJson.getString("feedid");
feedtitle = meJson.getString("feedtitle");
description = meJson.getString("description");
type = meJson.getString("type");
eventDate = meJson.getString("eventdate");
categoryId = meJson.getString("categoryid");
userid = meJson.getString("userid");
username = meJson.getString("username");
eventList.add(map);
}
Log.v("EvenitList Size", eventList.size() + "");
Log.v("Json Data:", jArray + "");
// int status = Integer.parseInt(success);
// if (status == 1) {
// } else {
// Toast.makeText(getApplicationContext(), status = 0,
// Toast.LENGTH_LONG).show();
// }
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
我的适配器类:
public class CalendarAdapter extends BaseAdapter {
private Context mContext;
private java.util.Calendar month;
public GregorianCalendar pmonth; // calendar instance for previous month
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;
ArrayList<HashMap<String, String>> events;
private View previousView;
public CalendarAdapter(Context c, GregorianCalendar monthCalendar,
ArrayList<HashMap<String, String>> eventList) {
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>();
this.events = eventList;
df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}
public void setItems(ArrayList<String> items) {
for (int i = 0; i != items.size(); i++) {
if (items.get(i).length() == 1) {
items.set(i, "0" + items.get(i));
}
}
this.items = items;
}
public void setMoreItems(ArrayList<HashMap<String, String>> events) {
for (int i = 0; i < events.size(); i++) {
if (events.get(i).size() == 1) {
HashMap<String, String> mydata = new HashMap<String, String>();
items.set(i, "0" + items.get(i));
mydata.values().add(items.toString());
events.add(mydata);
}
}
this.events = events;
}
public int getCount() {
return dayString.size() & events.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// 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.parseColor("#98AFC7"));
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.parseColor("#98AFC7"));
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.parseColor("#6D7B8D"));
}
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;
}
/*
* ImageView iw = (ImageView) v.findViewById(R.id.date_icon); if
* (date.length() > 0 && events != null && events.contains(date)) {
* iw.setVisibility(View.VISIBLE); } else {
* iw.setVisibility(View.INVISIBLE); }
*/
for (int i = 0; i < events.size(); i++) {
ImageView iw = (ImageView) v.findViewById(R.id.date_icon);
if (date.length() > 0 && events != null
&& events.get(i).get("eventdate").equalsIgnoreCase(date)) {
iw.setVisibility(View.VISIBLE);
} else {
iw.setVisibility(View.INVISIBLE);
}
}
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
items.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();
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
pmonthmaxset = (GregorianCalendar) pmonth.clone();
pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);
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;
}