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


Some people, organizations or companies make their Android mobile app like their website. This is where any information about them is published or displayed.

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



2.2 LEVEL 2 Source Code Output





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.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.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="";
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.

public void onCreate(Bundle savedInstanceState) {

	// 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();
	}catch(ParseException e){
	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){

	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

	// json link
	this.url = "" + 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) {

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() {

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

		String description = ((TextView) view.findViewById(;

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


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 or create another file. For now, we’ll put it inside our, 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.

protected void onPreExecute() {
	// Showing progress dialog
	progressDialog = new ProgressDialog(MainActivity.this);
	progressDialog.setMessage("Loading events...");


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.

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
		} catch (JSONException e) {

	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 and put the following code.


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) {
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		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.

protected void onPostExecute(Void result) {

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

	// update parsed data into ListView
	ListAdapter adapter = new SimpleAdapter(
		new String[] {
		new int[] {,,,


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

Manage events for your Facebook Page and Android app onceYes
Save time figuring out and coding these features for your Android appYes
Display list of all eventsYes
Display list of upcoming eventsYes
Display list of past eventsYes
Display event titleYes
Display event date and timeYes
Display event locationYes
Display event description on AlertDialogYes
Free source code updates for 6 monthsYes
Fast and friendly email support for 6 monthsYes
* You can use your debit or credit card with PayPal.

17.2 Download the PRO Source Code

All features of the BASIC source codeYes
Clicking an item will open new activityYes
Link to actual Facebook event (opens in Facebook app)Yes
Tickets LinkYes
Link to Google Maps to view full mapComing soon!
More featuresComing soon!
* You can use your debit or credit card with PayPal.

Thanks for supporting our projects here at!

Do you need more reasons to download 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 improvingYes
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!

Simple Android Signature Capture Tutorial and Source Code

Hello my friends! Today’s code is about capturing a user’s signature and saving it as a PNG image in the device SD card.

This android signature capture tutorial is useful if your app requires some signature for purposes like purchases, receipts or any transactions that needs a signature as a proof .

Our simple program below will have two buttons, a ‘save’ and ‘clear’ buttons and a canvas where the user can draw his signature. The program output is simple, so the code should be simple too! So…

The content of this post includes:

Read more

Android Calculator Tutorial and Source Code Example

android calculator tutorial

What if there’s an easy way to use a calculator for your android app? That would be great! Right? Well, I’ll try to help you guys with that.

Our post for today is about an android calculator tutorial and after the tutorial is the source code download, available in zip format.

Just a brief background on how this calculator works, we will have a TextView in which the user can click on. After clicking it, our calculator will be shown using a pop up or dialog.

The contents of this post include:

Read more

How To Get the User’s Current Location in Android? – GPS Example Help

Today I’m sharing you a working code on how to get the user’s current location in Android. There are many popular apps using this feature such as Google Maps and Facebook. Remember when you checked in a place?

Knowing exactly where your users are located is really cool, but you always have to let them know you are doing it. Asking permission to get user’s location is an ethical way.

One advantage of getting user’s current location is customizing their experience, just like what Twitter does. If you let twitter know your location, it will show top trends or news near you, how cool is that?

how to get user's current location in android?

Read more

Android Navigation Drawer Example Step by Step

android navigation drawer horizontal open

Android Navigation drawer is now a standard when creating an Android app.

It gives a better user experience since the user can easily access more app functionality – on a small screen smartphone.

Personally, it is really fun to use since I just have to swipe a finger to use or access a view.

This post is a step by step guide on how to create a navigation drawer for your Android app.

Read more

Android Action Bar Tutorial with 2.2+ Compatibility

I have an Android Action Bar Tutorial for you guys! Android ActionBar looks good on our smartphone apps and at the same time, it is really useful. Aside from displaying your app’s title or section, the ActionBar can also be used as a back function (upper left) or a viewable button or dropdown options (upper right).

android action bar tutorial

This is a step by step guide on how you can create an ActionBar for your awesome Android app. I’ll walk you through the process of creating a very simple but awesome android ActionBar. Let’s get started!

Read more

Android SQLite Transaction Example with INSERT Prepared Statement

Today I’m going to share an Android SQLite transaction example that I consider as one of the most useful test I made with Android SQLite. I’m really excited to share this since it helped me a lot and maybe it can help some more people as well.

This post will cover the following contents:

1.0 The Back Story
2.0 Insert Speed Problem
3.0 Android SQLite Transaction Example Source Code
4.0 Application Code Output
5.0 Other Tips On Improving Insert Speed

1.0 The Back Story

Recently, my app was required to download 30,000 records during sync. I think that’s a lot of data for a phone app, but that’s the way our app is.

The data were from a URL with data in JSON format. Our Android app has to read, parse and store the data on the device SQLite database.

30,000 records in one URL load is not advisable, we did several tests. I tried to parse it but failed, memory leaks occur, sometimes it was an out of memory error. So I tried some more test until I found the correct number of records per URL. 7,000 records and our app was able to read and parse it all. But to be safer, I made it to 5,000 records per page.

We had to paginate the download, so in our case, we had 6 pages. 6 pages x 5,000 records = 30,000. So yeah, it was very effective. All records were downloaded and inserted to the device SQLite database.

2.0 Insert Speed Problem

But before we were able to efficiently insert the records to the database, we run into the problem of “insert speed”. The usual insert command in Android is slow, so we had to use a transaction and prepared statement.

In our case, we use INSERT OR REPLACE INTO on the insert query since we want to update a row if it already exists, based on the trigger (INDEX) created.

If you’re using INSERT OR REPLACE INTO command, you have to create a trigger. This SQL trigger is executed after the table has been created (see below)

Another important factor in speeding up your insert is using prepared statements.

3.0 Android SQLite Transaction Example Source Code

Our source code will have three main files, the, and activity_main.xml. I made the code as simple as possible for this example to be clear and easy to follow.

DOWNLOAD SOURCE CODE – our program’s first run, it also contains the AsyncTask that will be executed when the user clicks a button.

package com.example.androidsqlitetransaction;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    final String TAG = "";
    EditText editTextRecordNum;
    TextView tvStatus;
    protected void onCreate(Bundle savedInstanceState) {


        View.OnClickListener handler = new View.OnClickListener() {
            public void onClick(View v) {

                switch (v.getId()) {

                    new AsyncInsertData("normal").execute();
                    new AsyncInsertData("fast").execute();

        // EditText for entering desired number of records to be inserted
        editTextRecordNum = (EditText) findViewById(;
        // Button for normal and fast insert
        // status TextView
        tvStatus = (TextView) findViewById(;


    // we used AsyncTask so it won't block the UI thread during inserts.
    class AsyncInsertData extends AsyncTask<String, String, String> {

        DatabaseHandler databaseHandler;
        String type;
        long timeElapsed;
        protected AsyncInsertData(String type){
            this.type  = type;
            this.databaseHandler = new DatabaseHandler(MainActivity.this);
        // @type - can be 'normal' or 'fast'
        protected void onPreExecute() {
            tvStatus.setText("Inserting " + editTextRecordNum.getText() + " records...");

        protected String doInBackground(String... aurl) {

            try {

                // get number of records to be inserted
                int insertCount = Integer.parseInt(editTextRecordNum.getText().toString());
                // empty the table

                // keep track of execution time
                long lStartTime = System.nanoTime();
                if (type.equals("normal")) {
                } else {

                // execution finised
                long lEndTime = System.nanoTime();

                // display execution time
                timeElapsed = lEndTime - lStartTime;
            } catch (Exception e) {
            return null;

        protected void onPostExecute(String unused) {
            tvStatus.setText("Done inserting " + databaseHandler.countRecords() + " records. Time elapsed: " + timeElapsed / 1000000 + " ms."); 
} – handles the database operations such as table creation, emptying the database, counting database records and the inserting our data using a loop.

package com.example.androidsqlitetransaction;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class DatabaseHandler extends SQLiteOpenHelper {

    // for our logs
    public static final String TAG = "";

    // database version
    private static final int DATABASE_VERSION = 7;

    // database name
    protected static final String DATABASE_NAME = "NinjaDatabase2";

    // table details
    public String tableName = "locations";
    public String fieldObjectId = "id";
    public String fieldObjectName = "name";
    public String fieldObjectDescription = "description";
    // constructor
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    // creating table
    public void onCreate(SQLiteDatabase db) {

        String sql = "";

        sql += "CREATE TABLE " + tableName;
        sql += " ( ";
        sql += fieldObjectId + " INTEGER PRIMARY KEY AUTOINCREMENT, ";
        sql += fieldObjectName + " TEXT, ";
        sql += fieldObjectDescription + " TEXT ";
        sql += " ) ";


        // create the index for our INSERT OR REPLACE INTO statement.
        // this acts as the WHERE name="name input" AND description="description input"
        // if that WHERE clause is true, I mean, it finds the same name and description in the database,
        // it will be REPLACEd. 
        // ELSE, what's in the database will remain and the input will be INSERTed (new record)
        String INDEX = "CREATE UNIQUE INDEX locations_index ON " 
                        + tableName + " (name, description)";

    // When upgrading the database, it will drop the current table and recreate.
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        String sql = "DROP TABLE IF EXISTS " + tableName;


    // insert data using transaction and prepared statement
    public void insertFast(int insertCount) {

        // you can use INSERT only
        String sql = "INSERT OR REPLACE INTO " + tableName + " ( name, description ) VALUES ( ?, ? )";
        SQLiteDatabase db = this.getWritableDatabase();
         * According to the docs
         * Writers should use beginTransactionNonExclusive() or beginTransactionWithListenerNonExclusive(SQLiteTransactionListener) 
         * to start a transaction. Non-exclusive mode allows database file to be in readable by other threads executing queries.
        // db.beginTransaction();
        SQLiteStatement stmt = db.compileStatement(sql);
        for(int x=1; x<=insertCount; x++){
            stmt.bindString(1, "Name # " + x);
            stmt.bindString(2, "Description # " + x);

    // inserts the record without using transaction and prepare statement
    public void insertNormal(int insertCount){
            SQLiteDatabase db = this.getWritableDatabase();
            for(int x=1; x<=insertCount; x++){
                ContentValues values = new ContentValues();
                values.put(fieldObjectName, "Name # " + x);
                values.put(fieldObjectDescription, "Description # " + x);
                db.insert(tableName, null, values);
        }catch(Exception e){
    // deletes all records
    public void deleteRecords(){
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("delete from "+ tableName);
    // count records
    public int countRecords(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("SELECT count(*) from " + tableName, null);
        int recCount = cursor.getInt(0);
        return recCount;

activity_main.xml – the layout so we can enter the desired number of records to be inserted, choose whether we want it to be a ‘normal’ or ‘fast’ insert, and the status of the operation.

<RelativeLayout xmlns:android=""
    tools:context=".MainActivity" >

        android:ems="10" >

        <requestFocus />

        android:text="Normal Insert" />

        android:text="Fast Insert" />

        android:text="Status" />


4.0 Android SQLite Transaction Example Code Output

See our code’s output screenshots below…

When you entered 1000 as number of records to be inserted and pressed either the “Normal Insert” or “Fast Insert” button.

android sqlite transaction example

After inserting 1000 the “Normal Insert” way.

the normal insert way

After inserting 1000 the “Fast Insert” way.

the fast insert way - sqlite prepared statement

See the huge difference in insert speed? Inserting 1,000 records were from 54,615 milliseconds (almost 1 minute) down to 322 milliseconds!

5.0 Other Tips On Improving Insert Speed

Some other important points:

1. Do not put a “log” inside a loop, it affects the program execution and slows down the performance. For instance, Log.v(TAG, “Record was created.”); was inside a loop where you also insert the data.

2. Do not instantiate an object or class inside a loop, that’s the worst. The “new” keywords will slow down the performance. For instance, ValueConverter valueConverter = new ValueConverter(); will make you lonely for the rest of your life if it was inside a loop where you also insert the data.

If you have other thoughts or want to correct me, or something, please drop it in the comments section below. I’m willing to update this post for new information, ideas and tips that you can give. Thanks for reading this Android SQLite transaction example!

Android Intents Tutorial to Share Your Social Media Links

The following Android intents tutorial will help increase your app’s Facebook likes or twitter followers. Almost every app has their own social media accounts or links that you can like, follow, +1, or even send an email to. There’s always an app that can connect you to that product or service.

Android Intents Tutorial to Share Your Social Media Links

Now, from that app, a user must be able to view your accounts effortlessly and in a standard, native and beautiful way. Don’t just throw a browser with a link to a social media account, impress your users by opening it in the native app! The most commonly used social media apps are Facebook, Twitter and Google Plus.

Those are covered in this post, but with the additional Browser and GMail intents! For this code’s demo, see our Android Intents video demo below.

Video Demo Permalink


By the way, the app on the demo above is this blog’s official browser app. You might want to download it on Google Play. I didn’t have enough time to develop that app due to my busy schedule. But it is working fine, try it out!


1.0 Facebook Intent in Android
2.0 Google Plus Intent in Android
3.0 Twitter Intent in Android
4.0 Browser Intent in Android
5.0 GMail Intent in Android
6.0 How to Check If An App Is Installed in Android?

1.0 Facebook Intent in Android

Here’s how my app show that Facebook page.
Step 1: Go to the FB page and get the Facebook page name using the URL, in my case, it is “CodeOfANinja”
You can also get the Facebook page ID using the graph API URL, for example
…and see the “id”: “107786425949934″ on that JSON string.

Step 2: Use the method below on your Listener, just replace the Facebook page name or ID. You can also use some parameters on this method if you’re opening multiple Facebook pages.

public void openFacebookPage() {
Intent i = null;

try {
context.getPackageManager().getPackageInfo(“com.facebook.katana”, 0);

// replace 107786425949934 with your page ID
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“fb://profile/107786425949934″));

} catch (Exception e) {

// replace CodeOfANinja with your page name
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“”));

checkIfAppExists(i, “Facebook”);


2.0 Google Plus Intent in Android

Calling the official Google Plus app to show the Google+ page of your customers would be great. That’s one feature I already worked with and now I’m ready to show you the working code I used.
Here’s how I did it:
Step 1: Go to the Google+ Page and copy the page ID. In my case, it is: 101266899643014043497

Step 2: Add the following code in your file or utility class.

public void openGooglePlusPage(String googlePlusId){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setClassName(“”, “”);
i.putExtra(“customAppUri”, googlePlusId);

checkIfAppExists(i, “Google Plus”);

How to use? Just call the function with the ID you got in step 1.


3.0 Twitter Intent in Android

Here’s how my app show that Twitter page.
Step 1: Get the Twitter page username, in my case, it is “ninjazhai”

Step 2: Add the following method on your project or utility class.

public void openTwitterPage(String username){
Intent i = null;

try {

// use the twitter app
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“twitter://user?screen_name=” + username));

}catch (Exception e) {

// try to use other intent
i = new Intent(Intent.ACTION_VIEW, Uri.parse(“!/” + username));

checkIfAppExists(i, “Twitter”);

How to use the method above? Remember the twitter username you got on step 1 and put code below on your click listener:


4.0 Browser Intent in Android

This time we are going to take a look at the browser intent filter in android. I used this one when I want my users have the ability to view the subscribe form of this blog. This code basically answers the question “How do I show a web page from my app to a web browser?”
Here’s the working code I used. Just follow this two step guide.
Step 1: Of course, prepare the URL you wanted to be shown. In my case, it was:

Step 2: Add this method to your JAVA file or utility class.

public void openUrl_InBrowser(String url){
Intent i = new Intent(Intent.ACTION_VIEW);

checkIfAppExists(i, “Web Browser”);


How to use? easy, you can do it this way.


5.0 Gmail Intent in Android

You can use this code when you want your users to have the ability to send email from your app, for example is the app feature where the users can send feedback, comments or suggestions directly to any given email address.

This code will open the Gmail App with the help of android intent filter.

Now you can add this code to your project or utility class.

public void openGmailApp(String[] emailAddresses, String subject, String text){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setClassName(“”, “”);
i.putExtra(Intent.EXTRA_EMAIL, emailAddresses);
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT, text);
checkIfAppExists(i, “Gmail”);


And you can use the method above this way:

// you can try to add more email in this array: new String[] { "", "" }
// if you're going to send the message to multiple people
new String[] { “” },
“Feedback for The Code of a Ninja Programming Blog”,
“Sent using The Code of a Ninja Android App:nn“

6.0 How to Check If An App Is Installed in Android?

Before a specific app will run, we have to verify if that app exists or installed in the device. This will enable us to tell the user that a certain app must be installed before using a feature. This prevents showing an error or force close message, so it is good for the user experience. The method below will show us the way.

Checking if an app is installed in the Android device is required if you are going to start another applications’s intent. There are other ways to do this but the code below is what’s working for me.

I used and tested this code when I wanted to start an intent to some apps like:

  • Facebook
  • Twitter
  • Google Plus
  • Browser
  • Gmail
// method to check whether an app exists or not
public void checkIfAppExists(Intent appIntent, String appName){

if (appIntent.resolveActivity(context.getPackageManager()) != null) {

// start the activity if the app exists in the system

} else {

// tell the user the app does not exist
Toast.makeText(context, appName + ” app does not exist!”, Toast.LENGTH_LONG).show();

Sample Usage: Below is the code I used when I want to open my google plus page with the Google+ official android app.

Intent i = new Intent(Intent.ACTION_VIEW);
i.setClassName("", "");
i.putExtra("customAppUri", "101266899643014043497");
checkIfAppExists(i, “Google Plus”);

You can read more about Android intents here.