How To Display Facebook EVENTS on Android App? Step By Step Guide!


display-facebook-events-on-your-android-app

Some people, organizations or companies make their Android mobile app like their website. This is where any information about them is published or displayed. You can read more about the app for 365 at omparethebets.com.

Most of these entities have a Facebook page. They have created events on that Facebook page. Do you do this?

If your answer is YES, what if we can put their list of events on their Android app? What if there’s a way to do it once and display it both on their Facebook page and Android app?

Will you be happy to save more of your precious time? If your answer is YES, our code for today will make you happy today, just like we are!

Today we’ll teach you how to do that. Step by step, we’ll guide you to display your Facebook page events on your Android app!

Today post will include the following contents:

1.0 Source Code Overview
2.0 Final Code Output
3.0 Import packages
4.0 Extend your MainActivity to ListActivity
5.0 Declare needed variables
6.0 Specify date range of events
7.0 Create getTimeStamp() method
8.0 Construct the Facebook Graph API JSON URL
9.0 We will display the events on a ListView
10.0 Initialize the eventList variable
11.0 Create the GetEvents AsynTask class
12.0 Prepare onPreExecute() method
13.0 Prepare doInBackground() method
14.0 Create ServiceHandler class
15.0 Prepare onPostExecute() method
16.0 What People Say About This Code?
17.0 Download the Complete Source Code
18.0 What’s Next?

1.0 Source Code Overview

Here’s an overview of what our code does:

1.1 Gets events listed with data such as event name, time, description, etc. from your Facebook fan page using the Facebook Graph API.

1.2 Display these event data to an Android app with native / XML user interface.

1.3 Let the user smoothly scroll through the list of events. Each event is clickable to show more details about that Facebook event.

In summary, this tutorial and source code will enable your Android app to display a list of Facebook events from any publicly available Facebook page.

2.0 Final Code Output

2.1 LEVEL 1 Source Code Output

2016-02-29-22-59-48

2016-02-29-23-00-14

2.2 LEVEL 2 Source Code Output

2016-02-29-23-12-51

2016-02-29-23-20-46

2016-02-29-23-20-58

2016-02-29-23-21-07

3.0 Import packages

Well, you don’t really need to do this because Android Studio can help you import these packages automatically.

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

4.0 Extend your MainActivity to ListActivity

public class MainActivity extends ListActivity {

}

5.0 Declare needed variables

final String TAG="MainActivity.java";
private ProgressDialog progressDialog;

// url to get json data
private static String url = "";

// the following are event keys in the FB graph API JSON response
private static final String TAG_EVENTS = "data";

private static final String TAG_WHAT = "name";
private static final String TAG_WHEN = "start_time";
private static final String TAG_TIMEZONE = "timezone";

// place
private static final String TAG_WHERE = "place";
private static final String TAG_WHERE_NAME = "name";

private static final String TAG_WHERE_LOCATION = "location";
private static final String TAG_WHERE_LOCATION_CITY = "city";
private static final String TAG_WHERE_LOCATION_COUNTRY = "country";
private static final String TAG_WHERE_LOCATION_STATE = "state";
private static final String TAG_WHERE_LOCATION_STREET = "street";
private static final String TAG_WHERE_LOCATION_ZIP = "zip";

private static final String TAG_DESCRIPTION = "description";

// Facebook Graph API parameters
final String access_token = "128623690525794|LbfgDAXN_KioIspqkMegG1-ysHA";
final String fields = "id,name,description,place,timezone,start_time";
final String fb_page_id = "82945776796";
int year_range = 2; // get events for the next x years

// events JSONArray
JSONArray events = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> eventList;

6.0 Specify date range of events

Specify date range of events to display using since_date and until_date variables.

@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

	// get since date
	SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
	String since_date =  sdfDateTime.format(new Date(System.currentTimeMillis()));

	String since_unix_timestamp=getTimeStamp(since_date);

	// get until date
	Calendar c = Calendar.getInstance();
	try{
		c.setTime(sdfDateTime.parse(since_date));
	}catch(ParseException e){
		e.getStackTrace();
	}
	c.add(Calendar.YEAR, year_range);

	Date result_date = new Date(c.getTimeInMillis());
	String until_date = sdfDateTime.format(result_date);

	String until_unix_timestamp=getTimeStamp(until_date);
}

7.0 Create getTimeStamp() method

getTimeStamp() method won’t work without the following code. Put it outside the onCreate() method.

// get unix timestamp
public String getTimeStamp(String ymd){
	DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

	Date date=null;

	try {
		date = (Date) formatter.parse(ymd);
	}catch(ParseException e){
		e.getStackTrace();
	}

	long output = date.getTime() / 1000L;
	String str = Long.toString(output);
	long timestamp_result = Long.parseLong(str);

	return Long.toString(timestamp_result);
}

8.0 Construct the Facebook Graph API JSON URL.

Put the following code under the code on section 6.0

try{
	// json link
	this.url = "https://graph.facebook.com/v2.5/" + fb_page_id
			+ "/events/attending/?fields=" + URLEncoder.encode(fields, "UTF-8")
			+ "&access_token=" + URLEncoder.encode(access_token, "UTF-8")
			+ "&since=" + URLEncoder.encode(since_unix_timestamp, "UTF-8")
			+ "&until=" + URLEncoder.encode(until_unix_timestamp, "UTF-8");

	Log.e(TAG, this.url);

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

9.0 We will display the events on a ListView

When an item was clicked, it will show the event description. The following code will enable us to do that. Put the following code under the code on section 8.0

ListView lv = getListView();

// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		String description = ((TextView) view.findViewById(R.id.description)).getText().toString();

		new AlertDialog.Builder(MainActivity.this)
				.setTitle("Event Description")
				.setMessage(description)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						dialog.cancel();
					}
				}).show();
	}
});

10.0 Initialize the eventList variable

eventList variable is where we will store the events from Facebook Graph API. Next, call the AsyncTask to get JSON values. Put the following code under the code on section 9.0.

// where we will store the events
eventList = new ArrayList<HashMap<String, String>>();

// calling async task to get json values
new GetEvents().execute();

11.0 Create the GetEvents AsynTask class

Create the AsynTask class to get JSON values from Facebook Graph API. You can put it inside your MainActivity.java or create another file. For now, we’ll put it inside our MainActivity.java, outside the onCreat() method of course.

// Async task class to get json by making HTTP call
private class GetEvents extends AsyncTask<Void, Void, Void> {

}

12.0 Prepare onPreExecute() method

Put the following code inside our GetEvents class. onPreExecute() method will tell the user (via ProgressDialog) that something is loading.

@Override
protected void onPreExecute() {
	super.onPreExecute();
	// Showing progress dialog
	progressDialog = new ProgressDialog(MainActivity.this);
	progressDialog.setMessage("Loading events...");
	progressDialog.setCancelable(false);
	progressDialog.show();

}

13.0 Prepare doInBackground() method

The next method inside our GetEvents AsynTask class is doInBackground(). This is where we will connect to the Facebook Graph API URL to get the list of events. This is also where we will fill up the eventList variable with events data.

@Override
protected Void doInBackground(Void... arg0) {

	// instance of service handler class
	ServiceHandler sh = new ServiceHandler();

	// make request to url, jsonStr will store the response
	String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

	if (jsonStr != null) {
		try {
			JSONObject jsonObj = new JSONObject(jsonStr);
			
			// get json array node
			events = jsonObj.getJSONArray(TAG_EVENTS);

			// looping through all facebook events
			for (int i = 0; i < events.length(); i++) {

				JSONObject c = events.getJSONObject(i);

				String what = c.getString(TAG_WHAT);
				String when = c.getString(TAG_WHEN);
				String timezone = c.getString(TAG_TIMEZONE);

				// place node is JSON Object
				JSONObject where = c.getJSONObject(TAG_WHERE);
				String where_name = where.getString(TAG_WHERE_NAME);

				JSONObject where_location = where.getJSONObject(TAG_WHERE_LOCATION);
				String where_location_city = where_location.getString(TAG_WHERE_LOCATION_CITY);
				String where_location_country = where_location.getString(TAG_WHERE_LOCATION_COUNTRY);
				String where_location_state = where_location.getString(TAG_WHERE_LOCATION_STATE);
				String where_location_street = where_location.getString(TAG_WHERE_LOCATION_STREET);
				String where_location_zip = where_location.getString(TAG_WHERE_LOCATION_ZIP);

				String where_complete = where_name + ", ";
				where_complete += where_location_street.length() > 0 ? where_location_street + ", " : "";
				where_complete += where_location_city.length() > 0 ? where_location_city + ", " : "";
				where_complete += where_location_state.length() > 0 ? where_location_state + ", " : "";
				where_complete += where_location_country.length() > 0 ? where_location_country + ", " : "";
				where_complete += where_location_zip.length() > 0 ? where_location_zip : "";

				String description = c.getString(TAG_DESCRIPTION);

				// tmp hashmap for single event
				HashMap<String, String> event = new HashMap<String, String>();

				// adding each child node to HashMap key => value
				event.put(TAG_WHAT, "WHAT: " + what);
				event.put(TAG_WHEN, "WHEN: " + getWhen(when, timezone));
				event.put(TAG_WHERE, "WHERE: " + where_complete);
				event.put(TAG_DESCRIPTION, "DESCRIPTION: " + description);

				// adding event to event list
				eventList.add(event);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	else {
		Log.e("ServiceHandler", "Couldn't get any data from the url");
	}

	return null;
}

14.0 Create ServiceHandler class

ServiceHandler on section 13.0 won’t work without our ServiceHandler class. ServiceHandler will help us connect and get data from Facebook Graph API. Create a new file named ServiceHandler.java and put the following code.

package facebook.events.level1;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class ServiceHandler {

	static String response = null;
	public final static int GET = 1;
	public final static int POST = 2;

	public ServiceHandler() {

	}

	/*
	 * Making service call
	 * @url - url to make request
	 * @method - http request method
	 * */
	public String makeServiceCall(String url, int method) {
		return this.makeServiceCall(url, method, null);
	}

	/*
	 * Making service call
	 * @url - url to make request
	 * @method - http request method
	 * @params - http request params
	 * */
	public String makeServiceCall(String url, int method, List<NameValuePair> params) {
		try {
			// http client
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpEntity httpEntity = null;
			HttpResponse httpResponse = null;
			
			// Checking http request method type
			if (method == POST) {
				HttpPost httpPost = new HttpPost(url);

				// adding post params
				if (params != null) {
					httpPost.setEntity(new UrlEncodedFormEntity(params));
				}

				httpResponse = httpClient.execute(httpPost);

			} else if (method == GET) {
				// appending params to url
				if (params != null) {
					String paramString = URLEncodedUtils.format(params, "utf-8");
					url += "?" + paramString;
				}
				HttpGet httpGet = new HttpGet(url);

				httpResponse = httpClient.execute(httpGet);

			}
			httpEntity = httpResponse.getEntity();
			response = EntityUtils.toString(httpEntity);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return response;

	}
}

15.0 Prepare onPostExecute() method

The third method inside our AsyncTask is the onPostExecute() method. Here is where we’ll hide the progressDialog and put the eventList data to our ListView. Put the following code under the code on Step 11.

@Override
protected void onPostExecute(Void result) {
	super.onPostExecute(result);

	// dismiss progress dialog
	if (progressDialog.isShowing()) {
		progressDialog.dismiss();
	}

	// update parsed data into ListView
	ListAdapter adapter = new SimpleAdapter(
		MainActivity.this,
		eventList,
		R.layout.list_item,
		new String[] {
			TAG_WHAT,
			TAG_WHEN,
			TAG_WHERE,
			TAG_DESCRIPTION
		},
		new int[] {
			R.id.what,
			R.id.when,
			R.id.where,
			R.id.description
		}
	);

	setListAdapter(adapter);
}

16.0 What People Say About This Code?

From the web version of this source code, I’m so glad that other people are delighted by this code, the following are some of them!

★★★★★ “Hello and THANK you for this amazing work! :)” ~ Sergio

★★★★★ “Perfect! Thank you very much! If I have some new jobs, I will contact you! Greetings from Germany.” ~ Eric

★★★★★ “Thanks, I’ve been trying to get Facebook events on the website for 6+ months had no luck, decided last night to update the site which I haven’t done in a while and thought I’d give it another go and found you’re page through a google search.” ~ Ward

17.0 Download the Complete Source Code

You can get the source code by following the whole, well detailed tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the value or skill upgrade it can bring you, or income you can get from your Android app project or business.

For a limited time only, I will give you the source code for a low price. Download the source code by clicking the green buy button below.

17.1 Download the BASIC Source Code

FEATURES BASIC
Manage events for your Facebook Page and Android app once Yes
Save time figuring out and coding these features for your Android app Yes
Display list of all events Yes
Display list of upcoming events Yes
Display list of past events Yes
Display event title Yes
Display event date and time Yes
Display event location Yes
Display event description on AlertDialog Yes
Free source code updates for 6 months Yes
Fast and friendly email support for 6 months Yes
LEVEL 1: BUY AND DOWNLOAD NOW USING
* You can use your debit or credit card with PayPal.

17.2 Download the PRO Source Code

FEATURES PRO
All features of the BASIC source code Yes
Clicking an item will open new activity Yes
Link to actual Facebook event (opens in Facebook app) Yes
Tickets Link Yes
Link to Google Maps to view full map Coming soon!
More features Coming soon!
LEVEL 2: BUY AND DOWNLOAD NOW USING
* You can use your debit or credit card with PayPal.

Thanks for supporting our projects here at codeofaninja.com!

Do you need more reasons to download it?

MORE REASONS TO GET IT
Buy only once, use on unlimited number of android apps and Facebook pages! Yes
No different kind of licenses. Yes
No many different pricing schemes. Yes
No monthly or any recurring fees. Yes
No need to rely on another website to render Facebook events. Yes
No need for codes from other websites. Yes
You can learn more how to code, I love teaching and can give you free tips! Yes
Familiarize yourself with the Facebook Graph API. Yes
Features are constantly improving Yes
Completely customizable. Yes

18.0 What’s Next?

We are currently working on different Facebook Graph API source codes for the Android platform. For now, they are available for pre-order only. The source codes will be LEVEL 2.

If you pre-order now, you will get the LEVEL 2 Facebook Events script for FREE!

Once the source code of your desired product is finished, we will immediately send it to you.

✔ Display Facebook PHOTOS on Android App
✔ Display Facebook VIDEOS on Android App
✔ Display Facebook TIMELINE on Android App
✔ Display Instagram FEED On Your Android App
✔ Display Twitter FEED on Android App

Thanks for reading our step by step tutorial on how to display Facebook events on Android App!


Leave a Reply

Your email address will not be published. Required fields are marked *