Skyledger UI Clone Tryout :)

Last night while browsing Dribbble, I’ve seen a beautifully crafted iPhone UI project done by Josh Helmsley, which was part of his SkyLedger project. It was just fantastic.

SkyLedger

So I tried to clone the same UI using Titanium and finally done something similar :)

SkyLedger UI Clone in Titanium :P

Just a test project. No interaction, just plain simple UI done using Titanium. You can download this Appcelerator titanium project by clicking on the following link. Let me know if you like it.

Download

Icons by DryIcons (Handy-2)

Posted in UI | 1 Comment

Adding red badges to tabs in a tabgroup

Red badges are particularly useful to let user know how many notifications are there in a particular section. Most iPhone developers use this feature to notify users about unread messages or notifications. These red badges looks like the following image

Red badges on a Tab

You can add such notification badges using “badge” property while creating a new tab, like this


var tabWithBadge = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Mails',
    badge:16
});

or you can also set it to any tab by using the “setBadge()” method as shown below. You need to create the tab first.


var tabWithBadge = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Mails',
});
tabWithBadge.setBadge(16);

Hope it helps

Posted in Tips, UI | Leave a comment

Tasawr-JSRecord – Titanium JavaScript based ORM library

Hi,
It wasn’t my intention to bring out ORM library for titanium, but some how i got it out. still lotta features to implement.
My current implementation is very basic with “hasOne”, finder, save, update, destroy and model before/after observer. My goal is not to implement all of them together rather i’ve been implementing them one by one. so i could persist my patient to debug thems thoroughly.

Let’s see how you can use the current version -

Include this library in your app.js


Ti.include('lib/tasawr-jsrecord/database_service.js');

Define your model –


var AccountService = {

  TABLE_NAME: 'accounts',

  Account: function(name) {
    this.id = 0;
    this.active = false;
    this.name = name;
    this.description = "";
    this.safetyBalance = 0;
    this.currentBalance = 0;
    this.totalExpenses = 0;
    this.totalIncomes = 0;
    this.currency = 'BDT';
    this.userId = 0;

    // Use this method right after declaring fields otherwise it won't work
    DatabaseService.introduceDaoSupport(this, AccountService.TABLE_NAME, {
      primaryKey: 'id DESC',
      // None database fields could be defined through noDbFields: ['field1', 'field2']
    });

  // You can map relationship, hasOne: model name, this will be converted to "givenModelNameId"
  // Also define model class type.
  // this.hasOne('user', {modelClass: UserService.User});

  // You can define this.beforeFilter('eventType', callback);
  // You can also define this.afterFilter('eventType', callback);

  findAccounts: function(options) {
    return DatabaseService.Finder.findRows(AccountService.TABLE_NAME, AccountService.Account, options);
  }
}

You can see i’ve added AccountService to provide more utility methods for account model specific task. Also defined Account with the account service scope. (you can use it any way you want, there is no convention constraint).

Now you can use the following line of codes –


// Create new account
var a = new AccountService.Account();
a.name = 'Personal';
a.save();

// Update record
a.updateAttributes({ name: 'New name' });

// Find items
var arrayOfAccounts = AccountService.findAccounts({conditions: {name: 'New Name'}});

// Destroy item
a.destroy();

Let me guide you through the code so you could understand how these things are working –

  • TABLE_NAME is just holding the preferable database table name
  • Defining Account model with attributes and their sample value
  • It’s important to provide sample data otherwise all fields will be treated as text
  • 
    DatabaseService.introduceDaoSupport(this, AccountService.TABLE_NAME, {
          primaryKey: 'id DESC'
        });
    

    This code is introducing all “save, update, destroy, hasOne and other” related functionality

  • Finder methods (ie. findAccounts) are kept under AccountService scope so those could be accessed statically

These are the features i’ve already implemented –

  • Record save
  • Record updateAttributes
  • Record finder
  • Query builder with fluent interface
  • Observer with before and after hook for create, destroy and update
  • Relationship with hasOne

I’ve plan to implement the following features as well –

  • belongs to
  • Has many
  • scope
  • More default caching behavior

Let’s see how far it goes :)

Posted in Tips, tools | Tagged , , , | 1 Comment

So titanium simple ORM wrapper in progress

Check out few code snippets from my query builder fluent interface implementation –

This is about how simply you can store an object.


var a = new AccountService.Account('name', ...other attributes...);
a.save();

This is for retrieve a list of items.


new DatabaseService.QueryBuilder().
        select(fields).from(AccountService.ACCOUNT_TABLE_NAME)
        .where(conditions).withOptions(withOptions).afterExecution().returnResult();

This is for inserting a new row.


return new DatabaseService.QueryBuilder().
      insert().into(tableName).
        withFieldsAndValues(instance.getFieldsWithValue()).
          afterExecution().expectChanges(1).
            ifFound(
               function() {
                 var rowId = DatabaseService.getLastInsertRowId();
                 DatabaseService.logNewRecord(true, rowId);
                 return rowId;
               }).
            otherwise(
               function() {
                 DatabaseService.logNewRecord(false, query);
                 return false;
               }).
      returnResult();
Posted in tools | Tagged , , , , | Leave a comment

So “arguments”, “apply” and “call” doesn’t work with Titanium.Database.execute

At last, i think i got it, it looks like Titanium.Database’s execute method doesn’t look like a “Function” even though typeof says “function”. perhaps this is how their javascript interpreter is designed :)

Anyway this was my scenario -

I’m in the middle of building a rails activerecord kinda ORM tool on top of titanium.database library. so i could take OO advantages to make it more simpler and similar. so here is what i’ve built so far and where i had to stucked.


var a1 = new AccountService.Account('Daily', ... few other... values...);
a1.save();

this is how my Account model looks like -


Account: function(name) {
// Fields with sample or default data.
this.name = name;
this.safetyBalance = 20000;
this.currentBalance = 40000;
this.totalExpenses = 25000;
this.totalIncomes = 65000;
this.currency = 'BDT';
DatabaseService.introduceDaoSupport(this, 'accounts', {
primaryKey: 'name'
});
}

Actually introduceDaoSupport is doing all magical stuff here. it adds up “save”, “updateAttributes” and other required methods. also it takes care of creating the table if not already exists.

Since i’ve figured out that “titanium execute” method doesn’t allow us to dynamic invocation. so i had to do something like the following code -


var code = "";
var vars = [];
for (var i = 0; i < args.length; i++) {
var varName = "var_" + i;
vars.push(varName);
code += "var " + varName + " = args[" + i + "];";
}

code += "DatabaseService.dbInstance.execute(query, " + vars.join(', ') + ");";
Ti.API.debug(code);
eval(code);

Now at least it is working. please let me know if you think this is not the right way.
i’m sharing this with other so if anyone face similar problem they could know about it.

best wishes,

Posted in Tips | Tagged , , , | Leave a comment

Determine the type of a javascript object

Since i’m in the middle of developing something to facilitate my database using experience over the titanium, i had stumbled upon the strict type related issue.
My requirement was to determine the type from the given sample or real value. so here is what i’ve done.


if (this.typeOf(sampleOrDefaultValue) == 'boolean') { ... }
else if (this.typeOf(sampleOrDefaultValue) == 'array') { ... }

thanks to the original author of the “typeOf” implementation -


    /**
     *
     * This implementation is taken from -
     * http://blogs.vertigo.com/personal/rbiggs/Blog/Lists/Posts/Post.aspx?List=02949b85-a29d-4682-abdb-a065bff28a03&amp;amp;ID=32&amp;amp;Web=e8261135-ffe2-4406-81bc-2d89564d6b99
     *
     * Method to test the type of data. It returns a string.
     * If the data is a JavaScript primitive, it will return
     * the string in lowercase. If the data is an object type,
     * it returns a string with an uppercase initial letter.
     * Array literals and object arrays are identified with
     * and initial uppercase letter string, as are object literals
     * and object objects. This is because JavaScript does not
     * distinguish between the literal and object versions of
     * these two datatypes.
     */
    this.typeOf = function(value) {
      // First check to see if the value is undefined.
      if (value == undefined) {
        return "undefined";
      }
      // Check for objects created with the "new" keyword.
      if (value instanceof Object) {
        // Check for a boolean object.
        if (value instanceof Boolean) {
          return "boolean";
          // Check for a number object.
        } else if (value instanceof Number) {
          // Test whether it's a float or int.
          return "number";

          // Check whether it's a string object.
        } else if (value instanceof String) {
          return "string";
          // Check whether it's an array object/array literal.
        } else if (value instanceof Array) {
          return "array";
          // Check whether it's a date object.
        } else if (value instanceof Date) {
          return "date";
          // Check whether it's a function object.
        } else if (value instanceof Function) {
          return "function";
          // Check whether it's and object object/object literal.
        } else if (value instanceof Object) {
          return "object";
        }

        // If these tests failed, check to see if we're
        // dealing with a literal.
      } else if (typeof value) {
        // Here we're testing for null. Get this,
        // JavaScript returns it as an object!
        // So first we check for object, then for value.
        if (typeof value == "object") {
          if (typeof value == "object" &amp;amp;&amp;amp; !value) {
            return "null";
          }
          // If the value wasn't null, check if it is a literal.
        } else {
          // Check for a boolean literal.
          if (typeof value == "boolean") {
            return "boolean";
            // Check for a number literal.
          } else if (typeof value == "number") {
            return "number";
            // Check if it's a string literal.
          } else if (typeof value == "string") {
            return "string";
          }

        }

        // If it slipped through all these tests,
        // we're dealing with something undetectable.
        // Therefore return nothing.
      } else {
        return 'null';
      }
    };
Posted in Tips | Tagged , , | Leave a comment

One Script a Day

I am planning to add one useful snippet on Titanium everyday. I will try to post scripts those are written by me, but sometime other people’s code will also be posted in this thread, with proper references :)

I think that will be cool. Wait for todays script.

Posted in OneScriptADay | 5 Comments

Add new row into table view section

I have a table view where all user generated tags are listed under a specific section. later i came up with a feature where user can write their tag and when they hit the return button it goes into the tags section.
as i’ve thought that the following code should have worked. but it didn’t -


updatedSection.add(Ti.UI.createTableViewRow({...}));

so, later i figured out i better reset data to the table, like the following code -


table.setData([existingSections[0], updatedSection, existingSections[2]);

Ah! now it all appears properly. check out the screen shot for better understanding. best wishes.

Writing new tag

Writing new tag

Added on the specific section

Added on the specific section

Posted in Uncategorized | Leave a comment

Show status through notification box (ie. Loading data…)

So now i’m more into fancy stuff! :) you know what? being on web we know about how nicely gmail pops up their “Loading mail” or “Sending..” status over the browser view port. so now i’m just trying to be on mobile, i was looking for the similar kinda stuff, then built it (since it is damn simple i believe if you are lame enough you gonna read my post out) -

To make my words more understandable check out the screen shot -

See the black backed notification box

See the black backed notification box

This is the code i’ve written to appear this black semi transparent box with message -


showMessage: function(base, message, interval) {
var label = Ti.UI.createLabel({
text: message,
backgroundColor: '#000',
color: '#fff',
height: 40,
borderRadius: 10,
opacity: 0.7,
shadowColor: '#ccc',
textAlign: 'center',
top: 100,
width: '90%',
left: 10
});

base.getWindow().add(label);
interval = interval ? interval : 5000;

setTimeout(function() {
base.getWindow().remove(label);
}, interval);
}

Posted in Uncategorized | Tagged , | Leave a comment

How to open sub window through tab view open

So i’m on appstep now :) i’ve started working on a project which is meant to be used for keeping family financial accounts. right now i’m developing the iphone version.

On the iphone version, we have arranged the UI in the following hierarchy -

[Login, Registrtion] –> [Dashboard + TabView] –> [Sub views]
[Sub views] –> [Dashboard + TabView]

We have been using this hierarchy to keep the UI consistent and let the user get feedback that they can go back to the parent window anytime they want.

in order to implement this kinda view, we had two options, either go with Navigation Group view or go with Tab View. since we have to use Tab view (to sub arrange other views) we rode over tab view.

We kept parent window state with every new window we fired up, so the new window knows what is his parent window. thus new window could trigger the following kinda code -
newWindow.parentWindow.tagGroup.open(newWindow);

Actually i’m sharing this because i had to spent around 2/3  hours to figure out how this son of bitch works. (that kinda dump was me ;) )

let’s dig it more – (here i’m adding some screen shots to make it more understandable).

Dashboard (Main window)

Dashboard (Main window)

Accounts list view

Accounts list view

Add account

Add account

So you can understand now, how does the navigation flow works. To implement this kinda view i had to use “TabView” on the first window (Dashboard window) and used
dashboardWindow.tabView.open(accountsWindow);
similarly dashboardWindow.tabView.open(newAccountWindow);

My upcoming posts will demonstrate how  i’ve been managing those states and flow among the different windows and views :)

best wishes,

Posted in Uncategorized | Tagged , , , | Leave a comment