Archive for the ‘Android’ Category

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 24 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

android intent tutorial

March 14, 2011 2 comments

Today i am going to talk about something called intent. To get more in depth knowledge about android you should have basic understanding about intent.

Intent comes with your intention. It’s pretty interesting after you really understand what this is for.

Android uses two kinds of intent:

  1. Implicit Intent
  2. Explicit Intent

Let’s see a real world example, say you want some information about intent but you don’t know where to get it but you only know you want to see information about intent. So what do you do? You will be open up your browser -> go to google -> and enter something about intent and search

Now what google will do, it will search its entire database and try to match with those that best describe your entered keywords and return it to you.

What if you knew that in my blog there is a post about intent that badly describe about intent and still you wanna see that, then you will probably enter my blog address in your browser url instead of going to google. Though it’s not a bad idea to go to google for various type of information. At least I would do that. 🙂

In first case what did you do?

You did give some data to google and google fired something at you when it found something using that data.

This will be implicit since you didn’t know where in the world has a server which reside the appropriate data in terms your given data.

In the second case you did know explicitly where can you find your data, so you explicitly told your browser to take you there.

And that is also the case for android too.

Intent intent=new Intent(Intent.ACTION_PICK,

is used with implicit intent. As you can see here, in creating new intent we need an action and the data that action will be performed on. Now startActivityForResult will launch the activity that uses “content://contacts/” kind of data. As for the action though you don’t know if they don’t tell you what kind of action is permitted on that application’s activity but we know in the case we are using now because Intent.ACTION_PICK is supported by android’s own contact application so this intent will launch android’s native contact application where we can pick a contact that we choose and return with the result in your activity. As with previous example here you only knew what kind of data you needed what you wanna do with that data, now android will lookup for an appropriate application that uses this kind of data and also permit the kind of action you are requesting since some application’s data will not be available to others to use. If any appropriate application is found android will start that activity and show it to you to do your work.

As of explicit:

Intent intent=new Intent(PageOne.this,PageTwo.class);

You can easily guess that in here I’m in page one and I want to go another activity that is page two.

Here I explicitly told which activity I want to start.

Notice that I used startActivityForResult for the first one and startActivity for the second one, this may confused you a little bit, I will explain it to you later.

I think that explain not much but little bit about intent.

It will be more clear if you see some example application.

Using Implicit Intent:  ContactPicker

Using Explicit Intent: ReportGenerator

or you can check it from here:
svn checkout

this entire application uses explicit intent to go from one page to another.

Thank you for checking by and  if you have any question or suggestion please do comment. I appreciate that very much.


Categories: Android