detect your swipe on our own

April 29, 2013 2 comments

Howdy everyone,

This has been a long long time since i wrote any post regarding anything.I have been super busy with my life and job.
But it was worth it in the end i think. Started a new job[not new now] at Progmaatic Developer Network which is a great place to work so far. Also consulting at ICDDR,B as an Android Developer in my weekend to finalize one of the project i did for them more then a year ago.

Got interested in Game Development and iOS Development.
Currently doing 1 iOS project and 1 unity3d based game.

So what will be today’s post is going to be about?

Today’s post is going to be about something that i solve pretty recently for my unit3d based game[still on going].
So, let’s get cracking 🙂 .

The game i am currently working is a 2d game.
For the gameplay i needed to know which way user was swiping, based on that direction my player will move in that direction. Since i am no longer in android or iOS where i can just use the gesture detector classes and get it done so i needed a different way. So how am i going to solve that?

Thanks to
Fletcher Dunn and Ian Parberry for their amazing book: “3D Math Primer For Graphics And Game Development”. Out of my own interest i just wanted to read this book to have some knowledge about 3d game development in general so i can have some knowledge about what’s going on underneath. There i got introduced again with some of the techniques about vector mathematics that i long forgot.

So to solve the problem i was having i applied the vector mathematics 🙂 .

To know the direction of swiping i need to know at least two position and i know can get them via touch/mouse api from unity3d.

  Vector2 m_v2DownPos = Input.touches [0].position;
  // api call to give first position 
  // user touched/mouse down and make it a Vector2
  Vector2 m_v2UpPos = Input.touches [Input.touches.Length - 1].position;
  // api call to give the last position 
  // user touched/mouse down and make it a Vector2;
  Vector2 v2delta = m_v2UpPos - m_v2DownPos; // difference between them
      if (v2delta.normalized.x >= 0.8f) {
        // user swiping in right direction
      } else if (v2delta.normalized.x <= -0.8f) {
        // user swiping in left direction
      } else if (v2delta.normalized.y <= -0.8) {
        // user swiping in down direction
      } else if (v2delta.normalized.y >= 0.8) {
        // user swiping in up direction

I think you’ve got the idea of how it’s working. After getting v2delta if we normalize it, we will get the unit vector of v2delta and when you get that just check x and y component of the normalized vector to check swiping status of the user.I have defined the threshold of 0.8 . But it’s really up to you how you want to define the threshold. 1 means perfect swipe. But user hands might not be steady all the time so he/she might slip-away a little bit from perfect swipe.
Well this portion of code is applicable anywhere where we might need to calculate swipe event of our own.

So that’s it for today , until next time


FYI: This post can also be found in Progmaatic’s Blog .

Singleton pattern in android database and in general

June 24, 2012 3 comments

Howdy everyone,
It’s been a long time since i wrote any post.I have been super busy with my projects , i couldn’t manage my time to write any post for my blog.
Today i am going talk a little bit about using singleton pattern.And show you an example of it during the explanation.
Now what is it? and why do you care about it?
First let’s imagine the normal way of doing things if you are novice anough :).
Say my application consist of N number of screen.Now all screens uses an object for accessing some kind of data.If i were novice what i would do is create object of that class in every screen to access those data.
That would create N number of object.
Now since we only need to access some data but not to modify any data of that class object do we really need to create object for that class in every screen.
Of course we do if there is no pattern like singleton 🙂
Now let’s get down to what is it?As i said it’s pattern but more likely a design pattern.
Since we only need to access some data from a class, what this let’s us do is to create one object for the enitre application life cycle.And we can access those data over and over again using only single instance if that class object.
And that is what singleton mean 🙂
Why do u care? Well, i think it’s obvious, isn’t it? Save memory, Reduce complexity of the application….
Let’s see an example,
If you pay attention to class A structure you can see you can’t create any new object by
A object = new A();
Since the contructor is private the only way to get an instance of that class is calling static method getInstance of class A, so now whenever you call A.getInstance() it will return either a new object or an object that already been instantiated.

// Singleton class
    class A{
     public int a = 10;
     private static A a = null;
     private A(){
          a = this;
      public static A getInstance (){
          if ( a == null )
              a = new A ();
        return a;
    // Use of singleton class
   class B{
    int myInt;
      public B(){

Now let’s see a real exmple that might be helpful to some guys.I made this somedays ago during one of my project and documented it along the way so people who see the code can get a little bit of undertanding, what this class do?

Sqlite database for android in singlton:

package com.project;
@author : Saiful Islam
@mail :
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

     // db name for this application

     private static final String DATABASE_NAME = "appdb";

     // version number of this db

     private static final int DATABASE_VERSION = 1;

     // private variable which is going to store the singlton object of this class and return it to caller

     private static DatabaseHelper dbHelper = null;
     // private SQLiteDatabase varaible which is going to be responsible for all our db related operation // no need      touch it

     private static SQLiteDatabase db = null;
     // a private contructor which is going to be called from getInstance method of this constructor
     private DatabaseHelper(Context context) {
         super(context, DATABASE_NAME, null, DATABASE_VERSION);
         // storing the object of this class to dbHelper
         dbHelper = this;
     // Method is called during creation of the database
     /* ***************************

     public void onCreate(SQLiteDatabase database) {
     // Method is called during an upgrade of the database,
     // e.g. if you increase the database version

      public void onUpgrade(SQLiteDatabase database, int oldVersion,
     int newVersion) {
       DBTable.onUpgrade(database, oldVersion, newVersion);

     // method which is going to be responsible for all our select query
     /* use case:
     * String selectSql = "Select * from table_name";
     * //be careful using try catch:
     * Cursor myCursor = null;
     * try{
     * myCursor = DatabaseHelper.getInstance.executeQuery(selectSql);
     * // ..... get the data using cursor from the db
     * }catch(Exception e){
     * e.printStackTrace(); // be sure to check if any exception is thrown and find out what is the reason
     * }finally{ // be sure to close the cursor or else, might get some unexpected behavior
     * // see if cursor really got something when requesting for something and is not closed already, just for    precaution    :)
     * if(myCursor!=null && !myCursor.isClosed){
     * myCursor.close();
     * }
     * }

   public Cursor executeQuery(String sql){
    Cursor mCursor =db.rawQuery(sql, null);
     return mCursor;
     // method which is going to be responsible for all insert, update and delete query
     /* use case:
     * String dmlQuery = "Insert into table_name values(....";
     * DatabaseHelper.getInstance.executeDMLQuery(dmlQuery);// will return true or false based on the action succeeded    or   not if checked?

    public boolean executeDMLQuery(String sql){
    try {
       return true;
     } catch (Exception e) {
     // TODO: handle exception
      return false; 

     // will return a singleton object of this class will as well open the connection for convinient

    public static DatabaseHelper getInstance(Context context){
          dbHelper = new DatabaseHelper(context);
         return dbHelper;
     // will be called only once when singleton is created
    private static void openConnecion(){
          if ( db == null ){
                db = dbHelper.getWritableDatabase();
    // be sure to call this method by: DatabaseHelper.getInstance.closeConnecion() when application is closed by    somemeans most likely
    // onDestroy method of application

     public synchronized void closeConnecion() {
                dbHelper = null;
                db = null;

package com.project;
@author : Saiful Islam
@mail :
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DBTable {
   // Database creation SQL statement
   // Modify this class based on the need of the app's database

      private static final String CREATE_ANTLER_TABLE = "create table if not exists mytable "
          + "(_id INTEGER PRIMARY KEY autoincrement,"
          + "name VARCHAR(20),"
          +"value VARCHAR(30));";
      public static void onCreate(SQLiteDatabase database) {
      public static void onUpgrade(SQLiteDatabase database, int oldVersion,
   int newVersion) {
         Log.w(DBTable.class.getName(), "Upgrading database from version "
           + oldVersion + " to " + newVersion
           + ", which will destroy all old data");
           database.execSQL("DROP TABLE IF EXISTS todo");

I hope this help some people as it helped me.

Categories: Android

playing with sdcard in android

September 13, 2011 Leave a comment

Howdy everyone, today i am going to share a little code snippet that i developed recently while i was playing with my usual android development journey.

I wanted to build an android file manager,where one can browse all the files from sdcard.To bring up the pace in me at first i wanted to see all the files in sdcard.And this post is about that code snippet.

Another thing i want to ask that did you familiarize yourself with ddms? If not, that’s bad bcz i am sure of that if something goes wrong in your application you probably thinking your brains out.I tell you, ddms is big big helper when the whole world is beyond your hand. 🙂

In this post i am going to use ddms too, to help me out what’s going wrong.

So, let’s not talk too much…

        File file[] = Environment.getExternalStorageDirectory().listFiles();

Above line is the most mandatory one but not everythig even if it seems.

    public void FilesInDir(File[] file1){
        int i = 0;
        String filePath="";
                filePath = file1[i].getAbsolutePath();
                Log.d(i+"", filePath);

Running that code snippet will show us all the files and directory name in ddms right after /mnt/sdcard/
But that’s not what i want.I want to see all the files.And that’s when i got a brilliant idea of recursion, hah maybe that’s why they teach us recursion, DnC and all.To see the world 🙂

So, let’s use it … 🙂

    File file[] = Environment.getExternalStorageDirectory().listFiles();

    public void recursiveFileFind(File[] file1){
    int i = 0;
    String filePath="";
            filePath = file1[i].getAbsolutePath();
        		File file[] = file1[i].listFiles();
            Log.d(i+"", filePath);

After running this we will see a "Force Close" in our emulator.

Now, what to do?Swithing to ddms perspective view we will see lots of red light:

but never fear this is where our solution is reside.

Let’s examine what is the problem:

you can see it’s a NullPointerException which is causing the problem, that means we are assigning a null reference somewhere in our code.

Closely look at the recursion:

what happens when there is only a directory left at the end of a folder but no files in it.

So that means, at that time we are assigning what’s in this below line? Which has no length!!!

		File file[] = file1[i].listFiles();

So, to fix it all we need to do is check to see if the reference is null?


that should do it.

See how ddms helped to us to make a way when we can’t figure out things all by ourself.

That’s it for today, next i will try to write about Sensor bcz i recently added the Samsung Sensor Simulator in my eclipse, which is awesome.

Categories: Android

“TextSpeak” android app using text to speech api

August 20, 2011 25 comments

Today i’ve just developed another app for android using android’s own text to speech api.
Unlike the previous post i am going to share the apk file of this app and
i will provide the source code on request.
It’s  a pretty simple app with a neat interface.
here is a snap of this app

TextSpeak app for android

I am sure you can guess what this application does.
Of course this application only support those languages that android platform supports.

These languages are

You can see in the snapshot that there is two buttons for English, one of them
is for the guys who wants to go to America and other is for England. 🙂
And i also want to thank James of
blog bcz this application is inspired from his androidsam app idea.

Download the app:   TextSpeak
Download source code:  please contact me.

Categories: Android

mediaviewer android app

August 19, 2011 Leave a comment

Hello everyone.Today i am going to share my first android app that i built recently.
I call it MediaViewer.
The app is very simple.All it does is seek to see if you have any audio,video or photo in your phone, and represent them nicely in three gallery.One for images,one audios and other is for videos.
Here are some of the screen shot that i have taken.


You can click on any item and it will pop up another float screen with that item.
Also you can go to next item by clicking on top of the float screen.But not for video of course. 🙂
Oh, there is small button at the end of the screen if you want to contact me.
This application will be under development even though I’ve shown to you.
There are tons of idea pouring into my head and i will try to implement them, so in a way you can say that this app is the 1.0 version of MediaViewer.I will not publish it’s source code now since it has lot of things to update.When the update is done i will provide the source  code.Till then if you want to test the app for yourself please contact me.

If you have any query about anything please do comment.I’d be delighted to know.

Download app:        contact me

Categories: Android

starting with android gps

June 8, 2011 1 comment

Hello everyone, it’s been a while since my last post.It’s bcz i’ve been too lazy last few weeks figuring out what to do or what not.Though it’s not bcz of me it’s bcz my last semester exam is nearby and i have so much to do and so much to learn,Do you know the feeling when you are too excited to do lot more than you are thinking and you can not do anything at all, well i am in that situation right now.Let’s hope nothing goes wrong.
So, today i am going talk about android gps.

I am not going to dig into the theory behind android gps,rather i will try to show how you can begin development with android gps.

At first download this simple project so that you can understand what am i mockering.

Open the projects code, at first, let’s see what happening in onCreate method

LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);

There may be different types of location services available in your device, to access those service we need a manager LocationManager. In this portion of the code We are getting the handle of LOCATION_SERVICE to manager, that is LocationManager.

String provider = LocationManager.GPS_PROVIDER;
Location location =

Now that, we have the handler, we try to see current location by GPS service of that device,(you can also access other services using other providers (only if that’s available on your device)). Since we have the GPS_PROVIDER, now all we have to do is calling some method to see what gps is providing for us.Here we are trying to get the last known location.

locationManager.requestLocationUpdates(provider, 2000, 10,

This portion of the project is most important for us since it is responsible for listening the changes made by the device’s gps.
As you can see LocationManager has a method called requestLocationUpdates(java.lang.String provider, long minTime, float
minDistance, android.location.LocationListener listener) which takes as you can guess, 4 parameter.which provider to use,minimum time before listening for changes, minimum change in distance , and the listener.

Let’s see how is that listener is implemented:

private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {

public void onProviderDisabled(String provider){

public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }

here we have 4 methods but what we need for this project is onLocationChanged(Location location) and onProviderDisabled(String provider).
Every-time device changes it’s location, listener will fire the onLocationChanged(Location location) method with providing the location.
now remain only is updateWithNewLocation(location) which tells our UI to update with the location.

myLocationText.setText("Your Current Position is:\n" +

Before you run this project you should do a simple modification in your manifest file.

add <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”/> in your manifest. Use android.permission.ACCESS_COARSE_LOCATION if you are going to use LocationManager.NETWORK_PROVIDER.

And that’s it,wait, don’t run it right-away, we have a little housework to do.Now the Q is how the heck emulator is going to fetch the location, well that’s when mock gps comes in. It will mock you with gps location 🙂 , well not you, i mean emulator.

Fire up your emulator, after loading the emulator open your eclipse ide and go to ddms perspective view, you can see lot’s of thing happening in here. Find the emulator control.
now, i have provided a kml file with this project which stores some places location with their latitude and longitude.from emulator control’s kml “load KML” and locate the kml file.
Now run the project, after being initiated it will not show you anything bcz gps is not reading anything till now.Run the kml file from emulator control and voila, you are up and running.Isn’t it cool, you are moving from one place another without
being moved for an inch from your computer.I think that’s awesome.:)

Thanks everybody, next i will try to post something about android ndk(takes whole lot of pain only for configuring!!!) or
maybe else till then “HAVE A GOOD PROGRAMMING”

Categories: Android

android startActivity and startActivityForResult

March 19, 2011 27 comments

In my previous tutorial I have talked a little bit about intent. So we have our intention to do something either explicitly or implicitly now it’s time to start those intent. And we do this via startActivity() or startActivityForResult() but why do we have two kind of method for this.

As name suggest startAcitvity will only take you there where you wanna go without worrying about getting any result from child activity to parent activity.
It’s real classic when you have a sequence activity to go through, like filling some information in every activity and that’s it.
What if you want an activity that uses information from other activity or may be other application. In that case you need more than just startActivity(). And that’s when comes startAcitvityForResult().
So it start another activity from your activity and it expect to get some data from child activity and return that to parent activity.
Let’s see some example:

final Bundle bundle = new Bundle();
bundle.putStringArrayList("Q1", al);
Intent intent=new Intent(PageOne.this,PageTwo.class);

In this case I just wanna go from page one to page two and I don’t expect to get something from page two but I want page two to receive some data from page one and that I have sent using intent.putExtras().Full Code: ReportGenerator

Now we will try to understand startAcitvityForResult(). using previous ContactPicker example.
If you have not downloaded it yet you can download it from:
At first we should be creating an intent in our main activity that is ContentPickerTester and also create a static integer variable
public static final int PICK_CONTACT=1;
now that need to be done bcz you don’t actually know which sub activity is going to give you the result(if you are using implicit intent) so we need to somehow differentiate between sub activities so that we can take different type of action for different type of result.
Intent intent=new Intent(Intent.ACTION_PICK,

startActivityForResult() accept two parameters as it’s arguments, one is going to be the explicit or implicit intent and another is called request code which is our static variable.
now whenever subactivity finishes, it will return the request code you have sent, along with the data and a result code to your main activity.

Let’s look at the subactivity (ContactPicker)
In the subactivity side subactivity will finish itself and return the data to the parent whenever it gets the chance to execute the below code.
Uri outUri=Uri.parse(data.toString()+rowId);
Intent outData=new Intent();

Here Activity.RESULT_OK is the result code we were talking about. Now if something goes wrong with subactivity Activity.RESULT_CANCEL will return.

I don’t know if you have noticed or not that we are not calling ContactPicker anywhere in our main activity. Well we actually calling it implicitly. See at manifest file
That in our ContactPicker activity we have something like this:


<action android:name="android.intent.action.PICK"/>

<category android:name="android.intent.category.DEFAULT"/>

<data android:scheme="content" android:path="contacts"></data>


You should also remember that when we have created an intent in our main activity we defined our action as Intent.ACTION_PICK. And of course ContactPicker has an action named android.intent.action.PICK. And also the kind of data we are looking. Android will use something called Intent Resolution to find a best fit activity and that is in our case is ContactPicker activity.So voila, startActivityForResult() will open up ur subactivity.
After choosing a contact it will return to the main activity by setting the result setResult(Activity.RESULT_OK,outData) and finishing off the subactivity.

Now all you have to do is taking care of the returned data in the main activity and that is done by
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//blah blah…

And that’s it. A real simple application. Awesome, isn’t it? And plz do comment or question , that will encourage me to write more. Also if there is any mistake let me know so that I can correct myself. And “HAVE A GOOD PROGRAMMING”

Categories: Android