Thursday, 11 July 2013

JSON object Sorted by Date

Hi,

Many of them asking how to sort my json objects based on date. And writing many lines of code, sometimes get tired to sort the json object. Here I found simple function to sort your json object based on date.

Not only date you can sort json object based on any attribute by writing custom sort function in your code.

Let me explain how to create custom sort function in java script.

You can download the sample app source code from git repository Sort Json by Date

Example JSON object:
 
var latestOffers=[
          {id: '1', date: '20 Dec 2012, 8:00 am', text:'item1'},
          {id: '2',  date: '29 Jun 2012, 5:47 pm', text:'item2'},
          {id: '3', date: '15 May 2013, 6:40 pm', text:'item3'}         
        ]; 

Now I write sortbydate() function


function sortbydate(a, b) {
    // change the < condition to > for reverse the sort.
    // here you can add your own sorting condition 
    // eg,   return a.id < b.id;   //its sort your object based on id.
    return new Date(a.date).getTime() < new Date(b.date).getTime();
}

Now you can call the Array.sort() with your sortbydate function.


 
latestOffers.sort(sortbydate);
Ti.API.info('sorted json array ==='+ JSON.stringify(latestOffers));


Thanks

Alloy Framework - Use Preloaded Sqlite Database

Most of time you may need to use the preloaded db in your application.

We are going to see How to use preloaded SQLite Database in Alloy framework in titanium.

Download the source code from git repository  AlloySqlitedb

1. Open the Titanium Studio  (I am using 3.1.1)
2. create New Alloy Mobile Project  (refer the Link for creating New Alloy Project)
3. Put your sqlite database file into app/assets folder. (I am using myapp.sqlite)
4.create collections object in alloy.js file.

 
Alloy.Collections.fighters = Alloy.createCollection('fighters');

5.create model file "fighters.js" in app/model directory.

 
exports.definition = {
  config:{
   
   adapter:{
    "type":"sql",
    "collection_name":"fighters",
    "db_file": "/myapp.sqlite",
    "db_name": "fighters",
    "idAttribute": "id",
    "remoteBackup":false
   }
  }
}

6.Modify index.xml file in app/views/ directory - create Table View.

 

    
        
        
            
        
    


7. Create controller index.js file in app/controller directory

 
var fighters = Alloy.Collections.fighters;
var counter = 1;

function showId(e) {
 if (e.row.model) {
  //alert(e.row.model);
  var detailObj=fighters.get(e.row.model);
  var win=Alloy.createController('detail',{"$model":detailObj});
     win.getView().open();
 }
}

function addTestFighter(e) {
 // create the test fighter model
 var model = Alloy.createModel('fighters', {
  name: 'Name ' + counter,
  nickname: 'Nickname ' + counter
 });
 counter++;

 // add model to the collection and save it to sqlite
 fighters.add(model);
 model.save();

 // let's refresh so we can see the ids coming from the 
 // autoincrement field in the sqlite database in the 
 // row click alerts
 fighters.fetch();
}

fighters.fetch();

$.index.open();

8. Create layout for row.xml in app/views directory

 

 
  


9. Create controller row.js in app/controller directory

 
// Attach the bound model ($model) to the row so 
// we can access it in a click event.
if ($model) {
 $.row.model = $model.toJSON();
}


10. Create layout for for detail.xml in app/views directory

 

 
  
   
    >
  >
 >




11. Create controller detail.js in app/controller directory.

 
var args=arguments[0]||{};
if(args.$model){
 Ti.API.info('model ='+JSON.stringify(args.$model));
 var dataJson=args.$model.toJSON();
}else{
 alert('data not passed');
}

12. Finally add the styles to your layouts in app/styles

a. index.tss

 
"Window": {
 backgroundColor: '#fff',
 navBarHidden: true,
 exitOnClose: true
}

"#title": {
 top: 0,
 height: '50dp',
 width: Ti.UI.FILL,
 color: '#fff',
 backgroundColor: '#a00',
 font: {
  fontSize: '36dp',
  fontWeight: 'bold'
 },
 textAlign: 'center'
}

"#table": {
 top: '50dp',
 bottom: 0
}

b.row.tss

 
"#row": {
 height: '60dp',
 backgroundColor: '#fff'
}

"Label": {
 height: Ti.UI.SIZE,
 width: Ti.UI.SIZE
}

"#name": {
 top: '7dp',
 left: '7dp',
 font: {
  fontSize: '24dp',
  fontWeight: 'bold'
 }
}

"#nickname": {
 bottom: '7dp',
 left: '14dp',
 font: {
  fontSize: '16dp',
  fonWeight: 'normal'
 }
}

c. detail.tss

 
"Window": {
 backgroundColor: '#fff',
 navBarHidden: true
}
"#name": {
 top: '10dp',
 font: {
  fontSize: '24dp',
  fontWeight: 'bold'
 }
}

"#nickname": {
 top: '10dp',
 font: {
  fontSize: '16dp',
  fonWeight: 'normal'
 }
}

13. Here we go and run the project.


Thanks.

Alloy Animation - builtin library

Titanium alloy framework provide collection of useful animation utilities. To use the animation builtin library, all you need to do is require it with the alloy root directory in your require call. For example:

var animation = require('alloy/animation');
animation.crossFade(view1, view2, 500, finishCallback);



chainAnimate( Titanium.UI.View view, Titanium.UI.Animation[] animations, [function() finishCallback] )
Executes a series of animations on the target view.
crossFade( Titanium.UI.View from, Titanium.UI.View to, Number duration, [function() finishCallback] )
Transitions from one view to another using a cross-fade animation.
fadeAndRemove( Titanium.UI.View from, Number duration, Titanium.UI.View container, [function() finishCallback] )
Fades out a view then removes it from its parent view. 
fadeIn( Titanium.UI.View to, Number duration, [function() finishCallback] )
Fades in the specified view. 
fadeOut( Titanium.UI.View to, Number duration, [function() finishCallback] )
Fades out the specified view. 
flash( Titanium.UI.View view, [Number delay], [function() finishCallback] )
Flashes the target view twice, fading to partially transparent then back to fully-opaque. 
popIn( Titanium.UI.View view, [function() finishCallback] )
Makes the specified view appear using a "pop-in" animation, which combines a fade-in with a slight expanding and contracting animation, to call attention to the new view. 
shake( Titanium.UI.View view, [Number delay], [function() finishCallback] )
Creates a shake animation, moving the target view back and forth rapidly several times.

Example:

1. open Titanium Studio
3. Modify views/index.xml
 

     
        
              
             
4. Modify styles/index.tss
 
".container": {
 backgroundColor:"white"
},
"#square": {
 width: 200,
 height: 200,
 color: "#f00"
} 

"#shakeMe":{
 title:'Shake Me',
 bottom:'100dp'
}


5. Modify controllers/index.js
 
function shakeMe(e) {
    var animation = require('alloy/animation');
    animation.shake($.view2, 500);
}

$.index.open();

6. Run the project and click the button.

Thanks.

Monday, 24 June 2013

Garbage Collector - Titanium Module for Android


Recently I developed an native module called Garbage Collector Module and published in Appcelerator Marketplace.


This module is used to Monitor your android device heap memory and force the garbage collector for free the unused objects.

Using this module we can get following informations,
  • MaxVMHeapSize
  • NativeHeapSize
  • VMHeapSize
  • TotalHeapSize
  • VMAllocatedHeapSize
  • NativeHeapAllocatedSize
  • VMHeapTotalAllocatedSize
  •  VMHeapFreeMemory
  • VMHeapTotalFreeMemory
And Also we have two more public methods called,
  • isOutOfMemoryException()   - we can check the Memory exception before app get crash.
  • callGC() - This method force the garbage collector and release the memory occupied by unused objects.
 Accessing the Garbage Collector Module

To access this module from JavaScript, you would do the following:

var garbagecollector = require("prakash.garbagecollector");

Force Garbage Collector

garbagecollector.callGC(); 

Check MemoryException

garbagecollector.isOutOfMemoryException();  returns true/false

Check Heap Memory Status
garbagecollector.getMaxVMHeapSize();
garbagecollector.getNativeHeapSize();
garbagecollector.getVMHeapSize();
garbagecollector.getTotalHeapSize();
garbagecollector.getVMAllocatedHeapSize();
garbagecollector.getNativeHeapAllocatedSize();
garbagecollector.getVMHeapTotalAllocatedSize();
garbagecollector.getVMHeapFreeMemory();
garbagecollector.getVMHeapTotalFreeMemory(); 

Sample App Screenshot
Module URL :

https://marketplace.appcelerator.com/apps/5834?2036618235

Friday, 5 October 2012

Loading Remote JPG images in Android - Appcelerator Titanium

Hi....

When I trying to Load the set of JPG images from json data (remote Images) the following error occurred.

 
Bitmap bounds could not be determined. If bitmap is loaded, it won't be scaled.
but its working fine in iOS. I started the research in INTERNET to fix this problem. Two solutions suggested by most of the people. They are,

1. Disabled FastDev in Android
2. Increase the VM Heap memory size.


but These are not solve my Problem. Finally I found one alternate solution for loading Remote JPG images in Android.

I am creating ImageLoader.js file for loading images....

ImageLoader.js

  
exports.LoadRemoteImage = function (obj,url) {
   var xhr = Titanium.Network.createHTTPClient();

xhr.onload = function()
{
 Ti.API.info('image data='+this.responseData);
 obj.image=this.responseData;
 
};
// open the client
xhr.open('GET',url);

// send the data
xhr.send();
}


For using this you need to pass imageView object and RemoteImageUrl.


app.js

 
var ImageLoader = require('ImageLoader');
var self = Ti.UI.createWindow({
     backgroundColor:'#ffffff',
  navBarHidden: true,
  fullscreen:true,
  layout:'horizontal'
  
 });
 
for(var i=0;i<5;i++) 
 {
var fullImage = Titanium.UI.createImageView({
    left: 10,
    top : 10,
    width : 100,
    height: 100,
    image:''
   });
   self.add (fullImage);
 
 ImageLoader.LoadRemoteImage(fullImage,'http://ic.i.tsatic-cdn.net/1213/105_99/29fce_1213904.jpg');
 
}

Finally my problem is solved..... Now Remote JPG Images Loaded fine in android...

I was created Thumbnail album and FullView album by using this ImageLoader.js

But You cannot pass any other object and can not set as backgroundImage. because when you are trying to load Image through HTTPClient, the image return as blob object. In iOS backgroundImage propert supports blob but not in Android.

Thankyou...........

Album Creation using scroll view and scrollableView in Titanium

Hi......

In this post we are going to create Image Album for both thumbnail and fullview.

Design Goal:

            The list of images are displayed in thumb size which are loaded into scroll view. when user clicks the particular Thumbnail Image the Image is loaded into Fullview mode.


Start to Code:

           1. First create a window object and add a scroll view that should by in  "horizontal' Layout and width is "100%".

            2. Now construct the for loop and Load Images in scrollView.

                          
                            var self = Ti.UI.createWindow({
                             backgroundColor:'#ffffff',
                             navBarHidden: true,
                              fullscreen:true,

                              width:'100%'
                                  
                            });

                           var ThumbAlbum=Ti.UI.createScrollView({
                                  layout:'horizontal',
                                  width:'100%'
                           });
                           self.add(ThumbAlbum);
                           var totalcount=5;
                           for(var i=0;i<
totalcount;i++)  
                              {
                                 var thumb = Titanium.UI.createImageView({
                                 left: 10,
                                  top : 10,
                                 width : 100,
                                 height: 100,

                                  imageID:i,
                                  image:'
'http://ic.i.tsatic-cdn.net/1213/105_99/29fce_1213904.jpg''
                              });
                       
ThumbAlbum.add (thumb);
                           }
                          self.open();

                  3. Next write fullImageView code in imageview's click event.

                                ThumbAlbum.addEventListener('click',function(e){
                                              var FullView=require("fullviewWindow");
                                               var win=FullView(e.source.imageID,e.source.image,totalcount);
                                                win.open();
                                 });
                     4. Now create fullviewWindow.js file
                            function fullviewWindow (imageID,imageurl,totalcount)
                             {
                               var self = Ti.UI.createWindow({
                             backgroundColor:'#ffffff',
                             navBarHidden: true,
                              fullscreen:true,

                              width:'100%'
                                  
                            });

                         var headerLbl=Ti.UI.createLabel({
                               width:'100%',
                                height:30,
                                backgroundColor:'#000',
                                text:  imageID+' of ' +totalcount
                          });
                        var fullimage = Titanium.UI.createImageView({
                                 left: 0,
                                  top : 30,
                                 width : '100%',
                                 height: '90%',

                                 image:imageurl
                              });

                              self.add(fullimage); 
                              self.open();
                              
                             }
                           module.exports=fullviewWindow;

                   5. Run the Program in Emulator/Simulator
                
Thankyou......
                                 

          

Simple tweets search app using Titanium

Hi...

In this post we are going to see simple tweets search app using Titanium appcelerator.


Design goal:

  Search the tweets based on name and list the results in Table view with tweets photo, name/title, description and posted date. when clicking the particular row the detailed information will be displayed in new window.

Start the Implementation:
       1.   create new titanium mobile project and start to edit the app.js (OR)          create new .js file in your existing mobile project.

       2.    create TextField and one Button with title 'Search' on the top of the window.

       3.   Now write the code in Search button's click event.

              3a. Twitter provides the api url for search the tweets.
     
                      var url = "http://search.twitter.com/search.json?q=" + stext.value;
               
                       here, stext.value is the TextField value.
             
               4b. Now create httpClientRequest object to send the request.

                        var xhr = Ti.Network.createHTTPClient({
                            onload: function () {

                                                              json = JSON.parse(this.responseText);
                                                              loadData(json);
                                                            },
                            onerror: function (e) { alert('ERROR');},
                             timeout: 5000
                          }); 

                        xhr.open("GET", url);
                        xhr.send();

                  4c. Write the definition for function loadData(json)
                            function loadData(json)
                              {
                                   if (json.results.length < 10) count = json.results.length;
                                    else count = 10;
                                   for (i = 0; i < count; i++) {
                                     tweets = json.results[i];
                                     row = Ti.UI.createTableViewRow({
                                     height: 'auto',
                                     hasChild: true,
                                     url: 'resultwindow.js',
                                     iurl: tweets.profile_image_url,
                                      iname: tweets.from_user,
                                     itext: tweets.text,
                                     idate: tweets.created_at,
                                     id: tweets.from_user_id_str
                                     });


                                   var image = Titanium.UI.createImageView({
                                     image: tweets.profile_image_url,
                                     top: 5,
                                     left: 5,
                                     height: 60,
                                     width: 60
                                    });
                                   nameLabel = Ti.UI.createLabel({
                                  text: tweets.from_user,
                                   font: {
                                   fontSize: '12dp',
                                   fontWeight: 'bold'

                                   },
                                  height: 'auto',
                                  left: 70,
                                  top: 0,
                                  color: '#f00',
                                  touchEnabled: false
                                  });

                               textLabel = Ti.UI.createLabel({
                               text: tweets.text,
                              font: {
                                 fontSize: '8dp'
                                },
                    height: 'auto',
                    left: 80,
                    top: '15dp',
                    color: '#00f',
                    touchEnabled: false
                });

                nickLabel = Ti.UI.createLabel({
                    text: '"' + tweets.created_at + '"',
                    font: {

                         fontSize: '8dp',
                        textAlign: 'right'
                    },
                    height: 'auto',
                    right: 0,
                    bottom: '2dp',
                    color: '#999',
                    touchEnabled: false
                });

                row.add(image);
                row.add(nameLabel);
                row.add(textLabel);
                row.add(nickLabel);

                tableData.push(row);
            }

            table.setData(tableData);

             } 

     4d. Write code for Table Click event

              table.addEventListener('click', function (e) {

        if (e.rowData.url) {

            var win1 = Titanium.UI.createWindow({
                //title:e.rowData.nameLabel.value,

                url: e.rowData.url,
                //navbarHidden: false,
                modal: true, // 'back' goes to previous window but no OptionMenu
                iurl: e.rowData.iurl,
                iname: e.rowData.iname,
                itext: e.rowData.itext,
                idate: e.rowData.idate,
                id: e.rowData.id
            });

            win1.open();
        }

            });



 5. Display the data in resultwindow.js as you like to display.
    sample code for getting data from win object in resultwindow.js
    var win = Ti.UI.currentWindow;  //you should write this line at first in resultwindow.js
     var iname=win.iname;

6. Go to Runas and select android Emulator
 

Thank you......