/** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_events);

    getUIElements();
    setupActionBar();

    Calendar c = Calendar.getInstance(); // Current time
    listviewAdapter = new EventAdapter(this, listData, c.getTime());
    listview.setAdapter(listviewAdapter);

    events = Event.readAll(dbWriteable);
    if (events.isEmpty()) {
      new DownloadEvents().execute();
    } else {
      iterateThroughEvents();
    }

    listview.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            EventRow eventRow = listData.get(position);
            if (!eventRow.isHeader()) {
              localyticsSession.tagEvent(LocalyticsPreferences.EVENTS_ACTIVITY_CLICK_SINGLE_EVENT);
              Intent i = new Intent(EventsActivity.this, SingleEventActivity.class);
              i.putExtra("event_id", eventRow.getEvent().getId());
              startActivity(i);
            }
          }
        });
  }
    @Override
    protected Integer doInBackground(String... params) {
      BestHrApi api = new BestHrApi(EventsActivity.this);
      events = api.getEvents();
      if (!events.isEmpty()) {
        if (clear) events.clear();

        for (Event event : events) {
          event.setDatabase(EventsActivity.this.dbWriteable);
          if (!event.exists()) {
            event.insertOrUpdate();
            nothingAdded = false;
          }
        }
      }

      return null;
    }
  /** Display refreshed data. */
  private void iterateThroughEvents() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean showPastEvents = prefs.getBoolean("show_past_events", false);

    int month = 0;
    for (Event event : events) {
      Calendar c = Calendar.getInstance();
      if (!showPastEvents && (c.getTime().getTime() > event.getEndDate().getTime())) continue;
      c.setTime(event.getStartDate());
      if (c.get(Calendar.MONTH) != month) {
        month = c.get(Calendar.MONTH);
        listData.add(
            new EventRow(DateUtils.getMonthName(month) + " " + c.get(Calendar.YEAR) + "."));
      }
      listData.add(new EventRow(event));
    }
    listviewAdapter.notifyDataSetChanged();
  }