Home Classroom Android Development

Hi guys, this time I’ll write about the new Android Wear, which was announced last week. So what is it all about?

Its a new approach by Google to bring a new concept by creating a new development area with targeting only wearable devices.

It’s not a completely new OS, its the same android but made specifically for wearable device software development.

‘Google Says that the Android Extends to Android Wear. Richer Experience for the Wearable devices’ -

So this time, there are 2 types of designs unlike the galaxy gear and smart watch 1 and 2. You can see a circle one and a traditional square screen. As I have heard the square one is going to be manufactured by LG, which has less spec and smaller price tag, whereas the circle one will be made by Motorola with high specs.

For developers, Android wear SDK developer preview has been released, so you guys can download and try it out. Which will be a great experience in the future when the device is out in the market.

So with the help of the official article I managed to find out that you can do the below shown basic functionality.


It does not mean that you have to learn anything new, you also can use the old APIs

‘You can also trigger your notifications contextually using existing Android APIs. For example, use geofences to provide glance able information to your users when they are at home, or use the activity detection APIs to send messages to your users’ wrists while they are bicycling.’

So what are you waiting for, register for developer preview, download the sdk and start developing.


Reference : Android Wear|Path of a Coder.com

Hi Guys, this time I am back with some Android Game Development. I got this idea after, the popular game Flappy Bird. Hope all may have tried that game…!
Ok, so I wanted to develop a game and I did some researches and found out that there are a lot of Game engines out there. Some of them are COCOS2D, AndEngine, libGDX and many others. In this article I’ll guild you using AndEngine which is a bit easier one. In future I’ll write on libGDX.

Assumption : I assume that you guys know how to install eclipse development environment, configure java path and install Android plugin to eclipse. This post does not cover all those basic steps.

Advise : As this is a kind of a crash course, its advisable to create files the same name as I use(But it is not mandatory).

Expected Outcome : You will be able to create some lines using the AndEngine

Step 1
Download the Source(library) for the AndEngine using this link and extract


Step 2
Create a new project and when creating select ‘Android Project from Existing Code’ and in it select the folder that we extracted in the Step1.
existing code

This is a library project. Actually this library is the ANDENGINE.

You can check it by right clicking on the project we created now and going to the Android tab. You can see the ‘Is Library’ check box ticked.

Step 3
Now create a new Android project and un tick the create activity. Because we are going to create AndEngine activity using the library project we created above.

Step 4
Now you have a project with empty src folder. Right click on that folder and create a new package when naming the package use the package name available in that project ManifestFile

In my case package name is ‘”com.batz.andengsample”‘

Step 4
Now in side the empty package Download or copy the code and create LineEample.java activity using this LineExample Source Code.

You will get some errors, but don’t worry we will fix it in the next step.

Step 5
So now in your project, right click and go to Android tab and there in the below section(library section), click on the add button and select the AndEngine project and press ok. And then press Apply.
add library

Now all the errors may have gone. Some times you will have errors on the package name, if you have used your own name. So for that, click on the package name that shows as error, click ctrl key +1 key , which will bring suggestion to create a package name according to yours, and click on it to create it. And hopefully all the bugs will be fixed.

Step 6
Before going for the app launch, we have to do one more important thing, we have to specify the activity we created now in the manifest file as a launcher

So go to the manifest file and add these lines between the application tags

<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />

LineExample is the name I gave for the activity we created, so in your one don’t forget to change that

Step 7
Now you are ready to run the app. So while you are in the the activity try running the app. it should bring a screen where you will see lots of random lines.

Step 8(For people getting error saying cannot find andengine.apk)
For some people the AndEngine folder is not getting added as library on the time of building the app. So at that point what you can do is copy the andengine.jar file from the AndEngine project libs folder and copy it into your projects’s libs folder. And right click on the newly added andengine.jar file and click on ‘Add to Build Path’ option. This is how the project structure looks after I added the jar to my project from the AndEngine project in the Step8


AndEngine Resources : http://www.andengine.org/

For people who got more time , for people who needs more detailed instruction on the same project guild please watch this tutorial video
Development Reference : http://www.youtube.com/watch?v=Q0kjiIH6u-M

Thank You

Reference:  – http://pathofacoder.com/2014/03/04/lets-try-android-game-development-with-andengine/

Developing many Android apps I found that a lot of methods are non-application-specific which means I can extract them into a Utils class which I can then share among various projects. One of my most useful methods is Utils.isEmulator(). This allows me to write into the app behavior which will be optimized for development in case the app is running inside an emulator supplied by an SDK and optimized for end-users in case it’s running on an actual device.

Here’s a use case example. Let’s say you’re building an alarm clock for Android and you want to test the snoozing feature. Let’s say the snooze period has a minimum length of 5 minutes. It will be a waste of time for you to wait 5 minutes every time you hit snooze when you’re actually testing this on the emulator, so why not set it to 1 in this case?

final int minutes = Utils.isEmulator() ? 1 : 5;

While developing the application yourself you’ll find many such use cases. At the moment there is no full proof, recommended way of checking whether you’re running in an emulator or not but the following implementation never failed me:

private static final boolean IS_EMULATOR = android.os.Build.MODEL.endsWith("sdk");

public static boolean isEmulator() {

Packaging both behaviors in the same ‘shipment’ (.apk file) is also convenient because it allows you to enable a debug/development mode when you’re helping customers or when you’re just testing functionality on real devices (e.g. simply by forcing IS_EMULATOR to be true in the implementation above in case some button is pressed). In my next process tip, I’ll share another use case for isEmulator() which isn’t application specific and which you can use in every single app you build from now on.

Efficient programming on mobile devices not only saves CPU, but battery as well

Everyone uses ArrayLists these days because they’re flexible. When you iterate over it, it allows you to use the enhanced for loop:

for (MyClass object : myArrayList) {

You use this because it’s simple to understand and easy to use. Did you know it’s consistently 3 times slower than the way you learned to do it in high-school? :)

for (int i=0; i<myArrayList.size(); i++){
  final MyClass object = myArrayList.get(i);

And you can squeeze even more out of this by looping it the other way around. If you check the condition you will access the ArrayList’s size() function every time you increment the counter. But if you loop the other way around you will only read in the beginning and then countdown towards 0, a constant:

for (int i=myArrayList.size()-1; i>-1; i--){
  final MyClass object = myArrayList.get(i);

Don’t forget to write i–. The first time you’ll try this you’ll write i++ out of habit and you won’t know why it crashed .This subject is pretty deep and it involves the JIT (Just In Time compiler) and automatic usage of Iterators behind the scenes as well. When you’re not sure what really matters in terms of speed the best way to figure it out is to write a small test yourself and run it directly on the emulator by measuring time the good old way with System.currentMillis()!

SQLite databases are the recommended way of storing quantitatively important data on the Android operating system. Because of the way user focus is organized on this platform, there are several kinds of contexts databases can be used in, e.g. activities (Activity class), services (Service class) or widgets. The first two inherit the Context abstract class, while context references are passed into the latter, but these, along with optimizations, will be discussed in the next sections.

  1. Introduction

Context is actually an interface to global information about the application environment, the implementation being provided by Android itself. The existence of Context references helps us determine their scope and even what we can do to optimize classes which are constructed using such references [1]. An Activity is, in a large sense, the logical unit of users’ interaction with the phone. Usually, only one Activity can have focus [2]. A Service is similar, but it doesn’t target the UI and is designed for longer-running operations; it’s a long-lived component of an Android application [3].

SQLite is an easy to use database system; there are certain helper classes to aid in database creation and version management, such a class being SQLiteOpenHelper [4]. You have to keep in mind that your app’s users might have different database versions when upgrading to the latest app version, so managing structural changes by implementing the onUpgrade(…) method is recommended.


2. Modelling & Creating the Database

Figuring out the best object-oriented model can depend on various factors. For example, you might want to focus on so called real-time usage needs, or you might want a trade-off with security features. Before explaining this choice, we first need to know how the database is created [5]:

  private class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
      super(context, DB_NAME, null, DATABASE_VERSION);
      mCtx = context;
      res = context.getResources();

    public void onCreate(SQLiteDatabase db) {
      Resources r = res;

      // creating the tag and entry tables and inserting a default tag
      db.execSQL(“CREATE TABLE “ + DB_TAG_TABLE + ” (“ + KEY_ROWID
          + ” integer primary key autoincrement, “ + KEY_NAME
          + ” text not null);”);
      db.execSQL(“INSERT INTO “ + DB_TAG_TABLE + ” (“ + KEY_NAME
          + “) VALUES (‘” + r.getString(R.string.tag1) + “‘)”);

As can be seen above, actual SQL code is passed to the execSQL method of the wrapper class. In fact, this snippet of code already contains an important optimization: the general isolation of upgrade operations which can be replicated for future users without being explicitly included in the SQL creation code. Details about the advantages of a custom upgrade method will be discussed in the following sections.

Classes such as DatabaseHelper are usually wrapped in other classes, becoming an inner class of the wrapper. This way, other helper methods can be implemented around the database helper. Before it’s actually used, it’s important to know that an SQLiteDatabase will be doing the hard work. An instance of it can be optained from the mentioned database helper, in an open open method (context use can be optimized) [5]:

  public ToDoDB open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;

Similarly, a closing method is needed – either for releasing resources or for freeing the database up for a lower level handling (more about the latter in the following sections) [5].
  public void close() {

But first an object model should be established. Some developers often execute their queries surrounded by the opening and closing methods. Thus, the default state, in that case, is a closed database. In theory, this increases security and modularity, also allowing for a permission system within a single app. This approach might be excusable with sparse accesses, but what is the CPU impact when these accesses occur periodically, or following every user action? Keep in mind that CPU activity translates not only into low response times but also into battery consumption on mobile phones. Therefore, if performance becomes an issue, and it rarely doesn’t, an open state should be considered default. The database can then be opened in the onCreate or onResume events of the activity, and closed in onDestroy. Similar events could be implemented / overridden in services and widgets, but this raises a lifecycle issue. Database instances will be different in these cases and will only live as long as the contexts will, but their cohabitation could cause problems. The singleton pattern can be employed here: if our database wrapper becomes a singleton, it will only have one true instance, forcing references (and not instances) to have a short life. This also eliminates the ultimately redundant overhead of creating parallel instances which do the same thing.
However, a Context needs to be passed to the constructor, and passing short-lived contexts to long-lived singletons wouldn’t be appropriate. This is why instead of using the local context, getApplicationContext() should be called on it; this will return the context of the single, global Application object of the current process. An instance of our own database wrapper would be obtained like this:
  sDbHelper = ToDoDB.getInstance(getApplicationContext());

And the public static getInstance function would look like this (the actual constructor should remain private, as it is a singleton):
  public static final ToDoDB getInstance(Context c) {
    return sInst != null ? sInst : (sInst = new ToDoDB(c).open());

This approach relies on Android to close the actual database, since explicitly closing it, for example, in a main activity, might prevent the app’s service to use it, or other such combinations. This way, the database will be closed only if it isn’t used anymore.

Fig. 1: Non-Singleton vs. Singleton approach


  3. Constraints

Some features might have certain constraints. For example, an app might offer the possibility to import a database from an external source. If this happens at a filesystem level, by overwriting files, the database will first have to be closed (released). After copying the files, it must be reopened, so it’s available to the app again [5] (the copy method can be implemented using standard Java):

  public static final void importBackupSD(final Context c) {
    try {
      Utils.copy(new File(“/sdcard/Tag-ToDo_data/database_backup”), new File(
    } catch (Exception e) {
      Utils.showDialog(R.string.notification, R.string.import_fail, c);
    sDbHelper = ToDoDB.getInstance(c);

Databases have, of course, different versions (e.g. when the app adds a feature, it might also need to change or add fields). This can be done in onUpgrade [5]:

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      // upgrade to db v74 (corresponding to app v1.2.0) or bigger;
      // 4 columns need to be added for entry dates (and other possible
      // future extra options).
      if (oldVersion < 74 && newVersion >= 74) {
        try {
          db.execSQL(“ALTER TABLE “ + DB_ENTRY_TABLE + ” ADD “
              + KEY_EXTRA_OPTIONS + ” INTEGER”);
        } catch (Exception e) {
          // if we are here, it means there has been a downgrade and
          // then an upgrade, we don’t need to delete the columns, but
          // we need to prevent an actual exception

        try {
          db.execSQL(“ALTER TABLE “ + DB_ENTRY_TABLE + ” ADD “ + KEY_DUE_YEAR
              + ” INTEGER”);
        } catch (Exception e) {

        try {
          db.execSQL(“ALTER TABLE “ + DB_ENTRY_TABLE + ” ADD “ + KEY_DUE_MONTH
              + ” INTEGER”);
        } catch (Exception e) {

        try {
          db.execSQL(“ALTER TABLE “ + DB_ENTRY_TABLE + ” ADD “ + KEY_DUE_DATE
              + ” INTEGER”);
        } catch (Exception e) {

      // upgrade to db v75 (corresponding to app v1.3.0) or bigger;
      // a column needs to be added for written notes
      if (oldVersion < 75 && newVersion >= 75) {
        try {
          db.execSQL(“ALTER TABLE “ + DB_ENTRY_TABLE + ” ADD “
              + KEY_WRITTEN_NOTE + ” TEXT”);
        } catch (Exception e) {

However, certain SQLite exceptions might occur. For example, if a database with an older version has been imported, and the app, of a newer version, queries for nonexistent field, there will be a force-close (the app will crash). The code above is useful in this situation as well because it allows us to easily repair the database by forcing missing subsequent upgrades until the current version is reached; onUpgrade being a method, not just an event, can be called programatically and, furthermore, its signature allows for successive and independent calls. These calls can be grouped in a method implemented in our DatabaseHelper class:

    public void upgrade(SQLiteDatabase db){
      onUpgrade(db, 73, 74);
      onUpgrade(db, 74, 75);
      onUpgrade(db, 75, 76);
      onUpgrade(db, 76, 78);
      onUpgrade(db, 78, 79);
      onUpgrade(db, 81, 82);
      onUpgrade(db, 85, 86);
      onUpgrade(db, 91, 92);

Repairing the database can be done in 2 ways, one simpler and one more complicated. The simple way involves calling the upgrade method and ensuring it is called only once upon the exception, so as not to enter an infinite loop in case the DB version isn’t the cause. This way, the database self-repairs based on its own design. A more full-proof way of handling such exceptions could be generating and executing SQL commands automatically based on the exception text, by extracting the names of problematic fields or tables and adding them to the data with a default value, but the extra effort in this second case might not be worth it.

  4. Flags

Using flags can be a straightforward design decision, but their advantages are worthwhile to mention. Flags usually have a passive nature, meaning that on change they don’t execute a particular action. They can be a very useful tool to customize user interaction by affecting query returns (e.g. to-do list users might want to sort their tasks, some alphabetically, others by priority, etc., which would be done by optionally appending an ‘ORDER BY’ clause to the SQL code). Setters can be implemented in our own wrapper while its inner methods can access it directly.

5. Events & Synchronization

Analyzing the mentioned ideas from the synchronization point of view reveals a few differences as well. When the default state is closed, you can consider the system synchronous (even if minimally) because specific methods need to be called before and after accessing the database (e.g. open and close). In other words, the application can’t unconditionally access at will, no matter the calling location, unless it opens the database first. With an open default state designed after the singleton pattern, this system is basically asynchronous, eliminating the necessity of calling the closing method and allowing any type of access from any location.

Although remotely related to databases from the documentation point of view, the connection with the UI and the way events propagate are very important, especially since some can be used as so called control signals. Events flow in a bottom up manner, and can be consumed (stopped) or allowed to continue along the propagation chain through the boolean return value, as seen in the following diagram:

Fig. 2: Event propagation

The way events can be used as control signals is translating user action into different use for the same UI elements. For example, a LinearLayout could be used to list all the tasks in a to-do list, but the same layout would be the best choice for enabling a task choice (e.g. moving a task under another task). Another example would be using a Spinner dialog for a similar double purpose: choosing tags from a list to show their content or choosing them to specify them as new hosts for previously selected tasks.

Fig. 3: Control signal example

Where preconditions and postconditions are concerned, there aren’t any except the ones imposed by design in the actual access methods implemented by the developer in the wrapper. Also, there aren’t any data type compatibility issues if parameters are properly included in the SQL or if Android’s special classes are used [5]:


  final ContentValues args = new ContentValues();
              args.put(KEY_NOTE_IS_AUDIO, 1);
              db.update(DB_ENTRY_TABLE, args, KEY_NAME + ” = ‘” + taskName
                  + “‘”, null);

This example updates a field which satisfies a certain condition with a new integer value.

6. Optimizations

One of the possible optimizations is using an abstract mother class for different kinds of tailored database wrappers. For example, in an alarm listener it might not make any sense to instantiate the entire wrapper with all its feaures; maybe a stripped down version would work better.

Another optimization is encoding multiple values into a single one. This can be done not only for security reasons, but for decreasing the amount of stored data (extra effort will be transfered to CPU). For example, a date – composed of year, month and day – can be encoded as an integer value:


  public int getDueDate(String task) {
    final Cursor entry = mDb.query(DB_ENTRY_TABLE, new String[] { KEY_ROWID,
        + ” = ‘” + task + “‘”, null, null, null, null);
    // for now, assuming we have a task named like this
    final int e = 372 * entry.getInt(entry.getColumnIndex(KEY_DUE_YEAR)) + 31
        * entry.getInt(entry.getColumnIndex(KEY_DUE_MONTH))
        + entry.getInt(entry.getColumnIndex(KEY_DUE_DATE));
    return e;

You can then decode the needed part using the DIV or MOD operators (/ and % in Java). 

7. Conclusion

SQLite databases on Android are a modern way of managing data on phones. Because of the multiple purposes mobile devices have, wrapper and helper classes have been and can be created as part of the platform to ensure high quality data management. Also, the Android operating system is constantly evolving providing compiler and performance optimizations that improve database use even further.


[1] Android: Context [WWW] http://developer.android.com/reference/android/content/Context.html

[2] Android: Activity [WWW] http://developer.android.com/reference/android/app/Activity.html

[3] Android: Service [WWW] http://developer.android.com/reference/android/app/Service.html
[4] Android: SQLiteOpenHelper [WWW] http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html

[5] Filimon T.: Tag-ToDo-List [APP] http://code.google.com/p/tag-todo-list