Skip to content

Instantly share code, notes, and snippets.

@DipoAreoye
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DipoAreoye/94439e44afa5e85bbb79 to your computer and use it in GitHub Desktop.
Save DipoAreoye/94439e44afa5e85bbb79 to your computer and use it in GitHub Desktop.

I decided to build an android app aiming to improve the week one experience for freshers at my university.

Events tab app

Due to the short time frame I had to launch to the app I wasn't able to work with an API and had to scrape the data for the events from a (horribly formatted) raw xml file. I had to parse all this information asynchronously from 8 different URLS which java provides great functionality for and then display it in a clean user friendly format. The code for the Events fragment(screen) can be seen below

package com.dise.weekone.adapters;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.dise.weekone.R;
import com.dise.weekone.ui.MainActivity;
import com.dise.weekone.ui.eventsTab.Event;
import com.dise.weekone.util.Const;
import java.util.List;
public class EventAdapter extends ArrayAdapter<Event> {
protected Context mContext;
protected List<Event> mEvents;
protected ViewHolder holder;
protected Typeface tf;
protected Resources r;
protected Typeface fontTime;
protected Typeface fontTitle;
public EventAdapter(Context context, List<Event> events) {
super(context, R.layout.event_item, events);
fontTitle = Typeface.createFromAsset(context.getAssets(),
Const.FONT_PRIMER_PRINT);
fontTime = Typeface.createFromAsset(context.getAssets(),
Const.FONT_MOCKUP);
mContext = context;
mEvents = events;
r = mContext.getResources();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(
R.layout.event_item, null);
holder = new ViewHolder();
holder.eventTitle = (TextView) convertView
.findViewById(R.id.eventTitle);
holder.eventTitle.setTypeface(fontTitle);
holder.eventTime = (TextView) convertView
.findViewById(R.id.eventTime);
holder.eventTime.setTypeface(fontTime);
holder.tagsLayout = (LinearLayout) convertView
.findViewById(R.id.tagsContainer);
holder.reminderInicator = (ImageView) convertView
.findViewById(R.id.reminderLabel);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Event event = mEvents.get(position);
String title = event.getTitle();
holder.eventTitle.setText(title);
String time = event.getTime();
String location = event.getLocation();
location = location.replace("Location:", "");
List<String> categories = event.getCategories();
holder.tagsLayout.removeAllViews();
for (String category : categories) {
addCategoryTags(category);
}
holder.eventTime.setText(time + " : " + location);
if (((MainActivity) mContext).isReminderSet(event.getId())) {
holder.reminderInicator.setVisibility(View.VISIBLE);
} else {
holder.reminderInicator.setVisibility(View.INVISIBLE);
}
return convertView;
}
protected void addCategoryTags(String category) {
int shortTag = Event.getCategoryShort(category);
if (shortTag == 0) {
return;
}
TextView t = new TextView(mContext);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
int px;
px = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
6, r.getDisplayMetrics()));
layoutParams.setMargins(px, 0, px, 0);
px = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
25, r.getDisplayMetrics()));
t.setWidth(px);
t.setHeight(px);
t.setTextSize(10);
t.setTypeface(fontTime);
t.setTextColor(Color.WHITE);
t.setGravity(Gravity.CENTER);
t.setLayoutParams(layoutParams);
t.setText(mContext.getResources().getString(shortTag));
GradientDrawable drawable = (GradientDrawable) (mContext.getResources()
.getDrawable(R.drawable.circle_shape));
drawable.setColor(mContext.getResources().getColor(
Event.getCategoryColour(category)));
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
t.setBackground(drawable);
else
t.setBackgroundDrawable(drawable);
holder.tagsLayout.addView(t);
}
private static class ViewHolder {
LinearLayout tagsLayout;
TextView eventTitle;
TextView eventTime;
ImageView reminderInicator;
}
}
package com.dise.weekone.ui.eventsTab;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.dise.weekone.R;
import com.dise.weekone.adapters.EventAdapter;
import com.dise.weekone.util.BaseFragment;
import com.dise.weekone.util.Const;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
public class EventsFragment extends BaseFragment {
protected String eventsData[] = { "", "", "", "", "", "", "", "" };
protected List<List<Event>> eventsLists;
protected List<Event> selectedDate;
protected String day = Const.START_DAY;
protected ProgressBar progressBar;
protected LinearLayout linearLayout;
protected Typeface font;
protected SharedPreferences spfEventsData;
protected GetEventsTask gEventsTask;
protected TextView emptyList;
protected Button prevSelectedButton;
@Override
public void onStart() {
super.onStart();
EasyTracker.getInstance(getActivity()).activityStart(getActivity());
}
@Override
public void onStop() {
super.onStop();
EasyTracker.getInstance(getActivity()).activityStop(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_events, container,
false);
ab.setTitle(Const.TAB_TITLE_EVENTS);
font = Typeface.createFromAsset(mainActivity.getAssets(),
Const.FONT_PRIMER_PRINT);
linearLayout = (LinearLayout) rootView.findViewById(R.id.linearLayout);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar1);
emptyList = (TextView) rootView.findViewById(android.R.id.empty);
addEventButtons();
spfEventsData = mainActivity.getSharedPreferences(
Const.KEY_EVENTS_DATA, Context.MODE_PRIVATE);
if (eventsLists == null) {
progressBar.setVisibility(View.VISIBLE);
}
return rootView;
}
@Override
public void onDetach() {
super.onDetach();
if (gEventsTask != null)
gEventsTask.cancel(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
eventsData = loadArray();
if (eventsData.length > 1) {
handleEventsResponse();
}
if (mainActivity.isNetworkAvailable()) {
gEventsTask = new GetEventsTask();
gEventsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
Const.EVENTS_URL);
} else {
progressBar.setVisibility(View.INVISIBLE);
emptyList.setText(R.string.no_internet_connection);
}
Tracker tracker = GoogleAnalytics.getInstance(getActivity()).getTracker(mainActivity.getResources().getString(R.string.ga_trackingId));
tracker.send(MapBuilder
.createAppView()
.set(Fields.SCREEN_NAME, Const.TAB_TITLE_EVENTS)
.build()
);
}
private OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(final View v) {
if (selectedDate == null) {
return;
}
for (int i = 0; i < linearLayout.getChildCount(); i++) {
Button btn = (Button) linearLayout.getChildAt(i);
btn.setBackgroundResource(android.R.color.white);
}
day = "" + (20 + v.getId());
selectedDate = eventsLists.get(v.getId());
Button selectedButton = (Button) linearLayout.findViewById(v
.getId());
selectedButton.setBackgroundResource(R.drawable.event_circle_shape);
prevSelectedButton = selectedButton;
adaptData();
}
};
public void addEventButtons() {
if (prevSelectedButton == null) {
prevSelectedButton = (Button) linearLayout.getChildAt(0);
linearLayout.getChildAt(0).setBackgroundResource(
R.drawable.event_circle_shape);
}
int l = linearLayout.getChildCount();
for (int i = 0; i < l; i++) {
Button btn = (Button) linearLayout.getChildAt(i);
btn.setTypeface(font);
btn.setEnabled(true);
btn.setOnClickListener(onClickListener);
if (prevSelectedButton != null) {
if (prevSelectedButton.getText().equals(btn.getText())) {
btn.setBackgroundResource(R.drawable.event_circle_shape);
}
}
btn.setId(i);
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Event selectedEvent = selectedDate.get(position);
String[] categories = new String[selectedEvent.getCategories().size()];
categories = selectedEvent.getCategories().toArray(categories);
Bundle args = new Bundle();
args.putString(Const.EVENT_TITLE, selectedEvent.getTitle());
args.putString(Const.EVENT_DESC, selectedEvent.getEventDesc());
args.putString(Const.EVENT_DATE, selectedEvent.getDate());
args.putString(Const.EVENT_TIME, selectedEvent.getTime());
args.putString(Const.EVENT_LOCATION, selectedEvent.getLocation());
args.putString(Const.EVENT_LINK, selectedEvent.getlink());
args.putString(Const.EVENT_ID, selectedEvent.getId());
args.putStringArray(Const.EVENT_CATEGORIES, categories);
args.putString(Const.EVENT_DAY_OF_WEEK,
(String) prevSelectedButton.getText());
mainActivity.addFragments(Const.EVENTS, new EventViewFragment(), args,
true, true);
}
public void handleEventsResponse() {
eventsLists = new ArrayList<List<Event>>();
for (String rawData : eventsData) {
eventsLists.add(parse(rawData));
}
if (selectedDate == null) {
selectedDate = eventsLists.get(0);
}
adaptData();
}
public void adaptData() {
EventAdapter adapter = new EventAdapter(getListView().getContext(),
selectedDate);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
public List<Event> parse(String data) {
List<Event> tempEventList = null;
Event event = null;
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(data));
tempEventList = new ArrayList<Event>();
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase(Const.TAG_XML_ITEM)) {
insideItem = true;
event = new Event();
} else if (xpp.getName().equalsIgnoreCase(
Const.TAG_XML_TITLE)) {
if (insideItem)
event.setTitle(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase(
Const.TAG_XML_LINK)) {
if (insideItem)
event.setlink(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase(
Const.TAG_XML_DESCRIPTION)) {
if (insideItem) {
event.setEventDescString(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase(
Const.TAG_XML_CATEGORY)) {
if (insideItem)
event.addCategory(xpp.nextText());
}
} else if (eventType == XmlPullParser.END_TAG
&& xpp.getName().equalsIgnoreCase(Const.TAG_XML_ITEM)) {
event = parseXml(event);
tempEventList.add(event);
}
eventType = xpp.next(); // / move to next element
}
} catch (Exception e) {
e.printStackTrace();
}
return tempEventList;
}
private Event parseXml(Event event) {
String desc = android.text.Html.fromHtml(event.getEventDesc())
.toString();
String lines[] = desc.split("\\r?\\n");
event.setTime(lines[0]);
if (lines.length > 3) {
String combinedDesc = "";
for (int i = 1; i < (lines.length - 2); i++) {
combinedDesc += lines[i];
}
event.setEventDescString(combinedDesc);
event.setLocation(lines[lines.length - 1]);
} else {
event.setEventDescString(lines[2]);
event.setLocation("");
}
List<String> categories = event.getCategories();
event.setDate(categories.get(0));
event.removeCategory(0);
event.setId(event.getTime() + event.getTitle() + event.getDate());
return event;
}
public class GetEventsTask extends AsyncTask<String, Void, String[]> {
@Override
protected String[] doInBackground(String... urls) {
String eventsDataArr[] = { "", "", "", "", "", "", "", "" };
try {
int i = 0;
for (String url : urls) {
eventsDataArr[i] = getSiteData(url);
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
return eventsDataArr;
}
protected String getSiteData(String urlString) throws IOException {
String data = "";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(urlString);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
while ((data = r.readLine()) != null) {
total.append(data + "\n");
}
return total.toString();
}
@Override
protected void onPostExecute(String[] result) {
SharedPreferences.Editor editor = spfEventsData.edit();
editor.putString(Const.KEY_EVENTS_DATA, spfEventsData.toString());
editor.commit();
eventsData = result;
progressBar.setVisibility(View.INVISIBLE);
handleEventsResponse();
cacheData();
}
}
public boolean cacheData() {
SharedPreferences.Editor editor = spfEventsData.edit();
editor.putInt(Const.KEY_EVENTS_DATA + "_size", eventsData.length);
for (int i = 0; i < eventsData.length; i++)
editor.putString(Const.KEY_EVENTS_DATA + "_" + i, eventsData[i]);
return editor.commit();
}
public String[] loadArray() {
int size;
size = spfEventsData.getInt(Const.KEY_EVENTS_DATA + "_size", 0);
String array[] = new String[size];
for (int i = 0; i < size; i++)
array[i] = spfEventsData.getString(Const.KEY_EVENTS_DATA + "_" + i,
null);
return array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment