a

Tuesday, 11 August 2015

Filesystem

8.   a.    Store text and binary data in files
b.    Read text and binary data from files
c.

Exercise -1
Store Text in Files

Solution


var textDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'FileManipulations');
if (! textDir.exists()) {
textDir.createDirectory();
var textFile  = Ti.Filesystem.getFile(textDir.resolve(), 'trainingdetails.txt');
//Create a Buffer
//var buffer = Ti.createBuffer({ length: 1024 });
//var buffer = Ti.createBuffer({ value: "Training progressing" });
textFile.write("forgot last contents", false);
textFile=null;

textDir =null;
}


Exercise - 2
Read Text in Files

Solution


function(){
Ti.API.info('reading text');
//reading the file
var textDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'FileManipulations');
if (textDir.exists()) {
var textFile  = Ti.Filesystem.getFile(textDir.resolve(), 'trainingdetails.txt');
var blob = textFile.read();
var readText = blob.text;
Ti.API.info('Text from file is '+ readText);
}

};


Exercise -3
Store Binary data

Solution


function(){
var imgVw= Ti.UI.createImageView({
  image:'/appicon.png'
});
Ti.API.info('start storing binary data');
var textDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'FileManipulations');
if ( textDir.exists()) {
var imgFile  = Ti.Filesystem.getFile(textDir.resolve(), 'appicon7.jpeg');
imgFile.write(imgVw.toBlob(), false);
 Ti.API.info('directory exists');
}
Ti.API.info('stop storing binary data');

};



Exercise -4
Identify the accessible storage locations on the filesystem
Identify the appropriate locations to store data on the filesystem
Determine when the filesystem is the most suitable storage location for your app’s data 


Multimedia



a.    Display still images as foreground and background graphics
b.    Implement local and streaming audio playback
c.    Implement local and streaming video playback
d.    Capture still images and video from the camera
e.    Retrieve images from the device’s photo gallery app


Validate


/*To validate above path check following

Prasads-MacBook-Pro:~ prasadkatankot$ adb shell

root@vbox86tp:/ # cd data/data

root@vbox86tp:/data/data # cd com.delhi/app_appdata


root@vbox86tp:/data/data/com.delhi/app_appdata # ls



Exercise - 1

Implement Local Streaming audio playback

Solution
function PlayLocalAudio(){
  Ti.API.info(Ti.Filesystem.getResourcesDirectory());
   //var mp3URL = Ti.Filesystem.getResourcesDirectory()+ 'music.mp3';
 var textDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'FileManipulations');
if (textDir.exists()) {
var mp3URL  = Ti.Filesystem.getFile(textDir.resolve(), 'magic.mp3');
}
//var mp3URL = Ti.Filesystem.getResourcesDirectory()+ 'music.mp3';
var audioPlayer = Ti.Media.createAudioPlayer({
    url : mp3URL
});

audioPlayer.start();

  }

Exercise - 2

Implement Remote Streaming audio playback

Solution


   function PlayRemoteAudio(){
  var audioStreamer = Ti.Media.createAudioPlayer({
url: 'http://www.tonycuffe.com/mp3/pipers%20hut.mp3'
});
 audioStreamer.start();
  }


Exercise - 3




 Implement local video playback

Solution


  function PlayLocalVideo(){
   var textDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'FileManipulations');
if (textDir.exists()) {
var videoURL  = Ti.Filesystem.getFile(textDir.resolve(), 'Nature.mp4');
var videoStreamer = Titanium.Media.createVideoPlayer({
url:videoURL,
autoPlay:true,
mediaControlStyle:Titanium.Media.VIDEO_CONTROL_EMBEDDED
});

$.indexWindow.add(videoStreamer);


}
Exercise - 4
Implement remote streaming video playback

Solution
  function PlayRemoteVideo(){
var videoStreamer = Titanium.Media.createVideoPlayer({
url:'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4',
autoPlay:true,
mediaControlStyle:Titanium.Media.VIDEO_CONTROL_EMBEDDED
});
$.indexWindow.add(videoStreamer);

}


Exercise - 5

Capture video from the camera

Solution

exports.retrieveVideo=function(videoPlayer, win){

var intent = Titanium.Android.createIntent({
        action : Ti.Android.ACTION_PICK,
        type : "video/*"
    });

    intent.addCategory(Ti.Android.CATEGORY_DEFAULT);
   
        win.activity.startActivityForResult(intent, function(e) {
        if (e.resultCode == Ti.Android.RESULT_OK) {
            if (e.intent.data != null) {
                // If everything went OK, save a reference to the video URI
                videoPlayer.visible=true;
                videoPlayer.url=e.intent.data;
        }
            else {
                Ti.API.error('Could not retrieve media URL!');
            }
        }
        else if (e.resultCode == Ti.Android.RESULT_CANCELED) {
            Ti.API.trace('User cancelled video capture session.');
        }
        else {
            Ti.API.error('Could not record video!');
        }
    });


};


Networking



a.    Implement the HTTP Client object
b.    Retrieve data in various formats from network services
c.    Upload and download files across the network
d.    Post JSON-formatted data to a web service; receive and process JSON data from a network endpoint
e.    Receive and process XML data from a network endpoint
f.     Handle network and data errors


  Exercise - 1

   Implement the HTTP Client object and analyse XML HTTP Request Life Cycle

Solution


function xhrlifecycle(){
var xhr = Ti.Network.createHTTPClient({
    onload: function(e) {
// function called in readyState DONE (4)
Ti.API.info('onload called, readyState = '+this.readyState);
    },
    onerror: function(e) {
// function called in readyState DONE (4)
Ti.API.info('onerror called, readyState = '+this.readyState);
    },
    ondatastream: function(e) {
// function called as data is downloaded
Ti.API.info('ondatastream called, readyState = '+this.readyState);
    },
    onsendstream: function(e) {
// function called as data is uploaded
Ti.API.info('onsendstream called, readyState = '+this.readyState);
    },
onreadystatechange: function(e) {
switch(this.readyState) {
case 0:
// after HTTPClient declared, prior to open()
// though Ti won't actually report on this readyState
Ti.API.info('case 0, readyState = '+this.readyState);
break;
case 1:
// open() has been called, now is the time to set headers
Ti.API.info('case 1, readyState = '+this.readyState);
break;
case 2:
// headers received, xhr.status should be available now
Ti.API.info('case 2, readyState = '+this.readyState);
break;
case 3:
// data is being received, onsendstream/ondatastream being called now
Ti.API.info('case 3, readyState = '+this.readyState);
break;
case 4:
// done, onload or onerror should be called now
Ti.API.info('case 4, readyState = '+this.readyState);
break;
}
},
    timeout:5000  /* in milliseconds */
});
xhr.open("GET", 'http://api.sba.gov/rec_sites/keywords/domain/irs.json');
xhr.send()// request is actually sent with this statement

}

  Exercise - 2

Retrieve data in various formats from network services

Solution


function httpnetwork(){
var url = "http://api.sba.gov/rec_sites/keywords/domain/irs.xml";
var xhr = Ti.Network.createHTTPClient({
    onload: function(e) {
// this function is called when data is returned from the server and available for use

        // this.responseData holds any returned binary data
        Ti.API.info(this.responseXML)  // this.responseXML holds any returned XML (including SOAP)
               
    },
    onerror: function(e) {
// this function is called when an error occurs, including a timeout
         Ti.API.info('Error from network');
        Ti.API.info(e.error);
        //alert('error');
    },
    timeout:5000  /* in milliseconds */
});
xhr.open("GET", url);
xhr.send()// request is actually sent with this statement


}



  Exercise - 3

 download files across the network

Solution


function downloadfile(){
var file ;
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'myaudio.mp3');
file.write(this.responseData); // write to the file
Ti.App.fireEvent('audio_downloaded', {filepath:file.nativePath});
},
timeout: 10000
});
xhr.open('GET','http://www.freesound.org/data/previews/2/2686_5150-lq.mp3');
xhr.send();
Ti.App.addEventListener('audio_downloaded', function(e) {

//image.image = e.filepath;
Ti.API.info(file.nativePath);
var audio = Titanium.Media.createSound({
url:file.nativePath,
preload: true
});
audio.play();
});

};



  Exercise - 4

Post JSON data from a network endpoint

Solution


function postJSONData(){

   var xhr = Ti.Network.createHTTPClient({
    onload: function onLoad() {
        alert("Loaded: " + this.status + ": " + this.responseText);
    },
    onerror: function onError() {
        alert("Errored: " + this.status + ": " + this.responseText);
    }
});

xhr.open("POST","https://c0ceb560ef3c83761ce4c21a93b2ce718311fa76.cloudapp-enterprise.appcelerator.com/api/newtest");
var authstr = 'Basic ' + Ti.Utils.base64encode('WqrIxir6bD9oHoV07seH4T8vrrnc0rQA:');
xhr.setRequestHeader("Authorization", authstr);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(JSON.stringify({
    "first_name": "Mohan",
    "last_name": "Singh",
}));
  


  Exercise - 5

Receive and process JSON data from a network endpoint

Solution

var funcToExecute=function () { //function called when GET URL is loaded from HTTP
console.log("inside first cal back");
if(this.status == '200'){
    if(this.readyState == 4)
JSONObj=JSON.parse(this.responseText);
var data = [];

for (var i = 0; i < JSONObj.length ; i++) { //Loop through
//for (var i = 0; i < 10 ; i++) {
 var listItem = JSONObj[i];
data.push({
title :listItem["name"]
});
}
//Create table and set values
var table = Titanium.UI.createTableView({})
table.setData(data);
$.tableContainer.add(table);
console.log("Table Set");
}
};
//HTTP request call
var xhr=Titanium.Network.createHTTPClient();    
xhr.onerror = function(e){ 
 Ti.API.error('Bad Sever =>'+e.error);
};
xhr.open("GET","http://api.sba.gov/geodata/all_links_for_county_of/orange county/ca.json");//ADD your URL

xhr.onload=funcToExecute;
  Exercise - 6

Detect Network Change

Solution


Titanium.Network.addEventListener('change', function(e) {
    Ti.API.info('network changed: ' + e.networkTypeName);
    Ti.API.info('Reason: ' + e.reason);
    if (e.online) {
        Ti.API.info('device is online');
    } else {
        Ti.API.info('device is offline');
    }
});

Monday, 10 August 2015

User interface



Course Outline

Exercise -1

Include platform specific resources at build time

Solution

1) Create a TestPlatform.js with following code and save it in Assets/Android

    Ti.API.info("called from Android specific library');

2) Create a TestPlatform.js with following code and save it in Assets/MobileWeb

    Ti.API.info("called from Android specific library');

3) Preview applicatioon in Android / Mobile  Web and confirm if platform specific files are getting loaded


Exercise -1.1
Test the position behavior of UI elements 

Solution

  1. Create a new Titanium Mobile project.
  2. Create a gridlines.js file containing the code. (shared with you)
  3. In app.js, remove all of the existing code. Declare a window, require the grid line module, and draw gridlines every 20 points, following the example code as shown
  4. var grid = require('gridlines');
  5. grid.drawgrid(20,win);
  6. Implement the positioning code (as given in Detailed Code below) shown in the example labeled "Positioning" above. This will draw red, blue, yellow, and green boxes at various positions on the screen.
  7. Build and run the project. Count the gridlines to confirm that elements were placed as described in this chapter.
  8. Adjust the positioning properties of the various boxes to test positioning rules.
  9. Try setting the window's layout property to vertical or horizontal to see the effect on the lines and boxes. Adjust the code so that the boxes are visible.
Detailed Code

var win=Ti.UI.createWindow({});

var redview = Ti.UI.createView({
    top:20,
left:20,
    width:10,
    height:10,
    backgroundColor:"red"
});
win.add(redview);
var yellowview = Ti.UI.createView({
    bottom:100,
right:100,
    width:10,
    height:10,
    backgroundColor:"yellow"
});
win.add(yellowview);
var blueview = Ti.UI.createView({
center: {x: 160, y: 240},
width:50,
height:50,
backgroundColor:"blue"
});
win.add(blueview);
var greenview = Ti.UI.createView({
    top:-20,
    width:10,
    height:10,
    backgroundColor:"green"
});
win.add(greenview);
win.open();

Exercise - 3
Achieve above results using ALLOY

Exercise - 3.1

Try to vertically and horizonatlly align elements


Solution

<Window layout="vertical>

<View baclgroundcolor="green" height="20" width="20"></View>
<View baclgroundcolor="red" height="20" width="20"></View>
<View baclgroundcolor="blue" height="20" width="20"></View>

</Window>

 INTERNATIONALIZATION

Internationalize your app using replaceable strings


Avoid hardcoding ! Go for localized string


Exercise - 4

Use localized string for Dialog Messages

Solution
1> Create folder i18n under same level of “app” folder

2> create “strings.xml” under language directory

3> var str1 = L('welcome_message');

var str2 = Ti.Locale.getString('welcome_message');
Ti.API.info ('WELCOME MESSAGE FROM LOCALIZED STRING'+str1+'-'+str2);

Exercise - 5

Handle missing Key in localization

Solution
var str1 = L('WelcomeMessage', 'Nothing available');

Exercise - 6

Assign title to titanium UI objects using localization

Solution

var label = Ti.UI.createLabel({

titleid: 'welcome_message'

});

Exercise - 7

Replace values in a local string

Solution

var formatted = String.format(L('format_test'),'Infy');


var formatted = String.format(L('ordered'), 'Infy', 'Murthy');

 
Exercise - 8

Internationalize App Name

Solution


Exercise - 9

 Create a button and make it to Listen to an event . Click the button and make sure event listener is working

Solution

Write following code in controller
function doSomething(e) {
Ti.API.info('The '+e.type+' event happened');
}

 $.mybutton.addEventListener('click', doSomething);


Exercise - 10

 Create a button and make it to Listen to an event

Solution

 $.mybutton.fireEvent('click');


Exercise - 11

 Pass data with event and retrieve same in listener

Solution

 $.mybutton.fireEvent('click', {kitchen: 'sink'})

 $.mybutton.addEventListener('click', function(e){
        Ti.APP.info('The value of kitchen is '+e.kitchen);
});