Posts

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!

Android Bluetooth Printing Example Code with Actual Printer Device

Android Bluetooth Printing Example Code with Actual Printer Device

Android Bluetooth Printing Example Code with Actual Printer Device

Recently, I was asked to make a program for printing some data to a small or handheld Bluetooth printer device.

This can be used for printing receipts, simple tickets, or customer notes.

I like how it works because usually, we are getting our program output on a computer screen.

But this time we are getting our output on a tangible paper!

This code will simply let you connect to the Bluetooth printer, type a text that you want to be printed and click the “send” button to print.

As for the printing with images, we made another code for that, please see section 4.3 (April 15, 2015 update) below!

1.0 Bluetooth Printing Source Codes

Step 1: Put the following code on your MainActivity.java. These imports are needed to perform our Android printing operations via Bluetooth.

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends Activity {

}

Step 2: Inside your MainActivity class will be the following variable declarations.

// will show the statuses like bluetooth open, close or data sent
TextView myLabel;

// will enable user to enter any text to be printed
EditText myTextbox;

// android built in classes for bluetooth operations
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;

// needed for communication to bluetooth device / network
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;

byte[] readBuffer;
int readBufferPosition;
volatile boolean stopWorker;

Step 3: After the variable codes, we will have the following onCreate() method.

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

    try {
        // more codes will be here
    }catch(Exception e) {
        e.printStackTrace();
    }
}

Step 4: Our XML layout file called activity_main.xml located in res/layout/ directory will have the following codes.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="10dp">

    <TextView
        android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Type here:" />

    <EditText
        android:id="@+id/entry"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/label" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/entry">

        <Button
            android:id="@+id/open"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:text="Open" />

        <Button
            android:id="@+id/send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send" />

        <Button
            android:id="@+id/close"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Close" />
    </LinearLayout>
</RelativeLayout>

Step 5: Inside the try-catch of your onCreate() method we will define the TextView label, EditText input box and buttons based on our XML layout file in Step 4.

// we are going to have three buttons for specific functions
Button openButton = (Button) findViewById(R.id.open);
Button sendButton = (Button) findViewById(R.id.send);
Button closeButton = (Button) findViewById(R.id.close);

// text label and input box
myLabel = (TextView) findViewById(R.id.label);
myTextbox = (EditText) findViewById(R.id.entry);

Step 6: We will set the onClickListener of our open button. This will open the connection between the android device and Bluetooth printer.

// open bluetooth connection
openButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        try {
            findBT();
            openBT();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
});

Step 7: findBT() method will try to find available Bluetooth printer. It will not work without the following code. Put it below the onCreate() method.

// this will find a bluetooth printer device
void findBT() {

    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if(mBluetoothAdapter == null) {
            myLabel.setText("No bluetooth adapter available");
        }

        if(!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        if(pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                
                // RPP300 is the name of the bluetooth printer device
                // we got this name from the list of paired devices
                if (device.getName().equals("RPP300")) {
                    mmDevice = device;
                    break;
                }
            }
        }

        myLabel.setText("Bluetooth device found.");

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

Step 8: openBT() method will open the connection to Bluetooth printer found during the findBT() method. It will not work without the following code. Put it below the findBT() method.

// tries to open a connection to the bluetooth printer device
void openBT() throws IOException {
    try {

        // Standard SerialPortService ID
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

        beginListenForData();

        myLabel.setText("Bluetooth Opened");

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

Step 9: We need beginListenForData() method so that openBT() method will work.

/*
 * after opening a connection to bluetooth printer device,
 * we have to listen and check if a data were sent to be printed.
 */
void beginListenForData() {
    try {
        final Handler handler = new Handler();
        
        // this is the ASCII code for a newline character
        final byte delimiter = 10;

        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];
        
        workerThread = new Thread(new Runnable() {
            public void run() {

                while (!Thread.currentThread().isInterrupted() && !stopWorker) {
                    
                    try {
                        
                        int bytesAvailable = mmInputStream.available();

                        if (bytesAvailable > 0) {

                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);

                            for (int i = 0; i < bytesAvailable; i++) {

                                byte b = packetBytes[i];
                                if (b == delimiter) {

                                    byte[] encodedBytes = new byte[readBufferPosition];
                                    System.arraycopy(
                                        readBuffer, 0,
                                        encodedBytes, 0,
                                        encodedBytes.length
                                    );

                                    // specify US-ASCII encoding
                                    final String data = new String(encodedBytes, "US-ASCII");
                                    readBufferPosition = 0;

                                    // tell the user data were sent to bluetooth printer device
                                    handler.post(new Runnable() {
                                        public void run() {
                                            myLabel.setText(data);
                                        }
                                    });

                                } else {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                        
                    } catch (IOException ex) {
                        stopWorker = true;
                    }
                    
                }
            }
        });

        workerThread.start();

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

Step 10: We will make an onClickListener for the “Send” button. Put the following code after the onClickListener of the “Open” button, inside onCreate() method.

// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        try {
            sendData();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
});

Step 11: sendData() method is needed so that the “Open” button will work. Put it below the beginListenForData() method code block.

// this will send text data to be printed by the bluetooth printer
void sendData() throws IOException {
    try {
        
        // the text typed by the user
        String msg = myTextbox.getText().toString();
        msg += "\n";
        
        mmOutputStream.write(msg.getBytes());
        
        // tell the user data were sent
        myLabel.setText("Data sent.");
        
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Step 12: We will code an onClickListener for the “close” button so we can close the connection to Bluetooth printer and save battery. Put the following code after the onClickListener of the “Send” button, inside onCreate() method.

// close bluetooth connection
closeButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        try {
            closeBT();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
});

Step 13: closeBT() method in Step 12 will not work without the following code. Put it below the sendData() method code block.

// close the connection to bluetooth printer.
void closeBT() throws IOException {
    try {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        myLabel.setText("Bluetooth Closed");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Step 14: Make sure the BLUETOOTH permission was added to your manifest file. It is located in manifests/AndroidManifest.xml, the code inside should look like the following.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluetoothprinter"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <supports-screens android:anyDensity="true" />

    <uses-permission android:name="android.permission.BLUETOOTH" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2.0 LEVEL 1 Source Code Output

Step 1: Click the “Open” button, the “Type here” text will change to “Bluetooth Opened”
Step 2: Type any text in the text box or EditText.
Step 3: Click the “Send” button, Bluetooth Printer device will print the text you typed in Step 2.
Step 4: Click the “Close” button to close Bluetooth connection and save battery.

Need to buy the same printer model we used above? I will give you the contact information of our supplier. Send an email to mike@codeofaninja.com with a subject “Bluetooth printer by codeofaninja.com”. I will reply with the contact information of our supplier.

3.0 LEVEL 2 Source Code Output

The LEVEL 2 source code can print small images. As you will see in the video, you can browse the image and then the Bluetooth printer will print it.

Need to buy the same printer model we used above? I will give you the contact information of our supplier. Send an email to mike@codeofaninja.com with a subject “Bluetooth printer by codeofaninja.com”. I will reply with the contact information of our supplier.

Please note that you have to pair your Android device (in your Bluetooth settings) and Bluetooth printer before running our source code.

4.0 Download Source Code

4.1 Downloading The Source Code

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

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

Download the source code by clicking the “Buy Now” button below. What will you get? The source codes and free code updates!

4.2 LEVEL 1 Source Code

LEVEL 1 is the complete source code of our tutorial above.

DOWNLOAD NOW

4.3 LEVEL 2 Source Code

Here’s the source code version where you can print images (see output video demo on section 3.0 above). The source code can let you browse an image and then print it in the Bluetooth printer.

Images must be small and less than 10KB in size only, anything more than that, the printing will fail.

DOWNLOAD NOW

4.4 Download ALL LEVELS Source Code

This means you will download LEVEL 1 and LEVEL 2 source codes above at a discounted price.

DOWNLOAD NOW

IMPORTANT NOTE: This code was only tested with the printer we specified above. It may not work with your kind of printer. We provide the code as is. Download it at your own risk.

Also, thanks to a code from project green giant for helping me figure out this Android Bluetooth printing code example.

android sqlite database crud tutorial with example app

Android SQLite Database CRUD Tutorial with Example Application

android-sqlite-database-crud-tutorial-min

This is a step by step android CRUD tutorial where we’ll create an Android application that demonstrates Android’s SQLite database capabilities.

Operations such as create, read, update and delete (CRUD) in Android is an essential skill every aspiring Android developer must have.

In this post, we will cover the following contents:

Read more