Appcelerator Titanium: Learning by examples #4


Titanium modules: Facebook

  1. Module collections: https://marketplace.appcelerator.com/home. For Facebook we do not need to download anything from market place.
  2. Download a module and save it under /modules dir, inside Titanium SDK folder. Make sure to place module in proper OS (iOS, Android etc)
  3. Add the module in tiapp.xml file. Click on Add button and add Facebook
  4. Add the module in alloy.js file. For example,
    Alloy.Globals.Facebook = require('facebook')
  5. Lets add Login button. Add the code in index.html
    <LoginButton id="fbLoginButton" ns="Alloy.Globals.Facebook"/
  6. Add the code in index.js
  7. var facebook = Alloy.Globals.Facebook;
    facebook.appid = 122761107792145;
    facebook.permissions = ['publish_stream'];
    facebook.addEventListener('login', function(e) {
    	if (e.success) {
    		alert('Logged in!');
    	}
    });
    
  8. For iOS, the following code need to be added manually in tiapp.xml file.
    <ios>
            <plist>
                <dict>
                    <key>UISupportedInterfaceOrientations~iphone</key>
                    <array>
                        <string>UIInterfaceOrientationPortrait</string>
                    </array>
                    <key>UISupportedInterfaceOrientations~ipad</key>
                    <array>
                        <string>UIInterfaceOrientationPortrait</string>
                        <string>UIInterfaceOrientationPortraitUpsideDown</string>
                        <string>UIInterfaceOrientationLandscapeLeft</string>
                        <string>UIInterfaceOrientationLandscapeRight</string>
                    </array>
                    <key>UIRequiresPersistentWiFi</key>
                    <false/>
                    <key>UIPrerenderedIcon</key>
                    <false/>
                    <key>UIStatusBarHidden</key>
                    <false/>
                    <key>UIStatusBarStyle</key>
                    <string>UIStatusBarStyleDefault</string>
                    <key>FacebookAppID</key>
                <string>1227611077092145</string>
                <key>FacebookDisplayName</key>
                <string>MyAppName</string>
                <array>
                    <dict>
                        <key>CFBundleURLName</key>
                        <!-- Application ID same as the id value in the tiapp.xml file -->
                        <string>1227611077092145</string>
                        <key>CFBundleURLSchemes</key>
                        <array>
                            <!-- Prefix the Facebook App ID with 'fb' -->
                            <string>fb1227611077092145</string>
                        </array>
                    </dict>
                </array>
                </dict>
            </plist>
        </ios>
    

File System

function saveFile() {
	var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationCacheDirectory, "file.txt");
	/** other options are
	 * Ti.Filesystem.applicationDataDirectory
	 * Ti.Filesystem.applicationDirectory
	 * Ti.Filesystem.applicationSupportDirectory
	 */
	
	if (file.exists) {
		file.deleteFile();
	}
	file.write("hello world from file");
	file = null;
	
}

function loadFile() {
	var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationCacheDirectory, "file.txt");
	alert("File content: " + file.read().text);
	file = null;
}

Advertisements

Appcelerator Titanium: Learning by examples #3 (Alloy)


Intro to Alloy

  1. alloy.js enables you to initialize stuff before any controller gets executed
  2. Execution starts from controllers/index.js by convention
<Alloy>
	<TabGroup>
		<Tab title="First View" icon="KS_nav_ui.png">
			<Window title="First View">
				<View layout="vertical">
					<View class="rowLayout">
						<Label>First Number</Label>
						<TextField id="tf1"></TextField>
					</View>
					<View class="rowLayout">
						<Label>Second Number</Label>
						<TextField id="tf2"></TextField>
					</View>
					<Button platform="ios" title="Add Sum" onClick="onClickAdd"></Button>
					<Button platform="android" title="ADD SUM" onClick="onClickAdd"></Button>
					<Label id="result"></Label>
				</View>
			</Window>
		</Tab>
		<Tab title="Second View" icon="KS_nav_views.png">
			<Window title="Tab 2">
				<Label>I am Window 2</Label>
			</Window>
		</Tab>
	</TabGroup>
</Alloy>
"Window": {
	backgroundColor: "#fff"
}

"Label": {
	width: Ti.UI.SIZE,
	height: Ti.UI.SIZE,
	color: "#000",
	font: {
		fontSize: 20,
		fontFamily: 'Helvetica Neue'
	},
	textAlign: 'center',
	left: 10
} 

"TextField": {
	width: 120,
	left: 10,									// left margin 
	keyboardType: Ti.UI.KEYBOARD_NUMBER_PAD,	// Number keypad 
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_BEZEL,	// Better UI for iOS
}

"TextField[platform=android]" : {
	width: 120,
	left: 10,									// left margin 
	keyboardType: Ti.UI.KEYBOARD_NUMBER_PAD,	// Number keypad 
}

".rowLayout" : {
	layout: "horizontal",
	height: 48,
	top: 10
}
var firstNumber = 0;
var secondNumber = 0;
var total = 0;

$.index.open();

function onClickAdd() {
	if ($.tf1.hasText() && $.tf2.hasText()) {
		firstNumber = parseInt($.tf1.value);
		secondNumber = parseInt($.tf2.value);
		total = firstNumber + secondNumber;
		$.result.text = "Result: " + total;
	} else {
		$.result.text = "Please enter value";
	}
}

Appcelerator Titanium: Learning by examples #2


Multiple screen app

// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

// create tab group
var tabGroup = Titanium.UI.createTabGroup();


//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({  
    title:'Tab 1',
    backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({  
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var FirstView = require('FirstView');

win1.add(new FirstView());

//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({  
    title:'Tab 2',
    backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({  
    icon:'KS_nav_ui.png',
    title:'Tab 2',
    window:win2
});

var label2 = Titanium.UI.createLabel({
	color:'#999',
	text:'I am Window 2',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win2.add(label2);



//
//  add tabs
//
tabGroup.addTab(tab1);  
tabGroup.addTab(tab2);  


// open tab group
tabGroup.open();


function FirstView() {
	
	// Top level container 
	var self = Ti.UI.createView({
		layout: 'vertical',		// vertical layout 
		top: 10					// margin from top is 10 
	});
	
	// Line 1 
	var row1 = Ti.UI.createView({
		layout: 'horizontal',
		height: 80
	});
	
	// adding to the container 
	self.add(row1);
	
	// Lets add some UI controls to the row1 
	
	var label1 = Titanium.UI.createLabel({
		color:'#999',
		text:'Label 1',
		font: {
			fontSize:20, 
			fontFamily:'Helvetica Neue'
		},
		textAlign:'center',
		width:'auto',
		left: 10
	});
	
	// 
	row1.add(label1);
	
	var textField1 = Ti.UI.createTextField({
		left: 10,									// left margin 
		keyboardType: Ti.UI.KEYBOARD_NUMBER_PAD,	// Number keypad 
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_BEZEL,	// Better UI for iOS, no effect on Android 
		width: 160
	});
	
	row1.add(textField1);
	
	var button1 = Ti.UI.createButton({
		left: 10,
		title: 'Button1'
	});
	
	// adding click listener of the button 
	button1.addEventListener('click', function() {
		// alert will be displayed 
		alert(textField1.value);
	});
	
	row1.add(button1);
	
	var row2 = Ti.UI.createView({
		layout: 'horizontal',
		height: 80
	});
	
	self.add(row2);
	
	var button2 = Ti.UI.createButton({
		left: 10,
		title: 'Second View'
	});
	
	button2.addEventListener('click', function() {
		var SecondView = require('SecondView');
		var secondWindow = new SecondView();
		secondWindow.open();
	});
	
	row2.add(button2);
	
	return self;
}

module.exports = FirstView;

function SecondView() {
	
	var self = Ti.UI.createWindow({
		backgroundColor: '#ffffff',
		modal: true, 
		layout: 'horizontal'
	});
	
	var label = Ti.UI.createLabel({
		top: 20,
		left: 10,
		color: '#000000',
		text: 'Hello'
	});
	
	self.add(label);
	
	var closeButton = Ti.UI.createButton({
		top: 10,
		left: 10,
		title: 'Close'
	});
	
	closeButton.addEventListener('click', function() {
		self.close();
	});
	
	self.add(closeButton);
	
	return self;
}

module.exports = SecondView;

Preferences

// set property 
Ti.App.Properties.setInt('hello', 5);

// get property 
var hello = Ti.App.Properties.getInt('hello');
if (hello == null) {
	hello = 0;
}

Events

Window close

button2.addEventListener('click', function() {
	var SecondView = require('SecondView');
	var secondWindow = new SecondView();
	secondWindow.addEventListener('close', function() {
		// this event will be called on closing the new window 
	});
	secondWindow.open();
});

Custom event

// app.js
tab1.addEventListener('focus', function() {
	Ti.App.fireEvent('customEvent');
});

// FirstView.js
Ti.App.addEventListener('customEvent', function() {
		
});

Appcelerator Titanium: Learning by examples #1


Intro to Titanium

Titanium applications are written in Javascript but are complied to native apps that use native interfaces.

For iOS, Javascript is encoded and put into a variable in a C file inside the app and Javascript is interpreted by the Javascript engine built into the app and generate UI elements dynamically.

For Android, Javascript is compiles to Java byte code using Rhino JSC compiler. A part of Javascript code is still interpreted at runtime.

Creating View

  1. Create a Mobile App Project with Classic template
  2. Replace the code in app.js with the following code
  3. // this sets the background color of the master UIView (when there are no windows/tab groups on it)
    Titanium.UI.setBackgroundColor('#000');
    
    // create tab group
    var tabGroup = Titanium.UI.createTabGroup();
    
    
    //
    // create base UI tab and root window
    //
    var win1 = Titanium.UI.createWindow({  
        title:'Tab 1',
        backgroundColor:'#fff'
    });
    var tab1 = Titanium.UI.createTab({  
        icon:'KS_nav_views.png',
        title:'Tab 1',
        window:win1
    });
    
    var FirstView = require('FirstView');
    
    win1.add(new FirstView());
    
    //
    // create controls tab and root window
    //
    var win2 = Titanium.UI.createWindow({  
        title:'Tab 2',
        backgroundColor:'#fff'
    });
    var tab2 = Titanium.UI.createTab({  
        icon:'KS_nav_ui.png',
        title:'Tab 2',
        window:win2
    });
    
    var label2 = Titanium.UI.createLabel({
    	color:'#999',
    	text:'I am Window 2',
    	font:{fontSize:20,fontFamily:'Helvetica Neue'},
    	textAlign:'center',
    	width:'auto'
    });
    
    win2.add(label2);
    
    
    
    //
    //  add tabs
    //
    tabGroup.addTab(tab1);  
    tabGroup.addTab(tab2);  
    
    
    // open tab group
    tabGroup.open();
    
    
    
  4. Create a file named FirstView.js and place the following code
  5. function FirstView() {
    	
    	// Top level container 
    	var self = Ti.UI.createView({
    		layout: 'vertical',		// vertical layout 
    		top: 10					// margin from top is 10 
    	});
    	
    	// Line 1 
    	var row1 = Ti.UI.createView({
    		layout: 'horizontal',
    		height: 80
    	});
    	
    	// adding to the container 
    	self.add(row1);
    	
    	// Lets add some UI controls to the row1 
    	
    	var label1 = Titanium.UI.createLabel({
    		color:'#999',
    		text:'Label 1',
    		font: {
    			fontSize:20, 
    			fontFamily:'Helvetica Neue'
    		},
    		textAlign:'center',
    		width:'auto',
    		left: 10
    	});
    	
    	// 
    	row1.add(label1);
    	
    	var textField1 = Ti.UI.createTextField({
    		left: 10,									// left margin 
    		keyboardType: Ti.UI.KEYBOARD_NUMBER_PAD,	// Number keypad 
    		borderStyle: Ti.UI.INPUT_BORDERSTYLE_BEZEL,	// Better UI for iOS, no effect on Android 
    		width: 160
    	});
    	
    	row1.add(textField1);
    	
    	var button1 = Ti.UI.createButton({
    		left: 10,
    		title: 'Button1'
    	});
    	
    	// adding click listener of the button 
    	button1.addEventListener('click', function() {
    		// alert will be displayed 
    		alert(textField1.value);
    	});
    	
    	row1.add(button1);
    	
    	var row2 = Ti.UI.createView({
    		layout: 'horizontal',
    		height: 80
    	});
    	
    	self.add(row2);
    	
    	return self;
    }
    
    module.exports = FirstView;
    

Install Kitchen Sink

  1. Open Help -> Studio -> Show Studio Dashboard
  2. On the Dashboard page click on “More” besides “Get Started Quickly With Sample Apps”
  3. Go to the “Samples” window and right click on “Kitchen Sink” -> import sample as project
  4. Run the app in all platforms (iOS, Android etc)

Titanium: 3.1.0 Apple iTunes Store and Android App Store Distribution Bug Workaround


I am using Titanium build: 3.1.0.201304151600

Distribute – Apple iTunes Store

Bug:
Bug is reported here: https://jira.appcelerator.org/browse/TISTUD-4311
they said, its already fixed in the release candidate version

Apple iTunes Store distribution begets Ad Hoc distribution file
Xcode won’t get open automatically after the build process
Though popup showing: Apple app store distribution completed successfully

Console output: 
[INFO] :   Build type: production
[INFO] :   Building for target: dist-adhoc

Workaround:
1. Remove the directory WORKSPACE/.metadata/.plugins/org.eclipse.debug.core/.launches to clear the existing launch configurations

2. Goto Run Configurations and Delete all particular application related subsections of Titanium Apple iTunes Distribution
and
Delete all particular application related subsections of Titanium Apple Ad Hoc/Enterprise Distribution

3. clean and Restart Titanium Studio

4. Goto Run Configurations and Select Titanium Apple iTunes Distribution
click New Launch Configuration
Provide necessary information on Right pane (Distribution Certificate, Keychain, provisioning profile, sdk version)
click Run

Expected Result: After a while Xcode should open automatically
Next process should be familiar to you

Distribute – Android App Store

Bug:
Android play store showing a package signing error
or
downloaded android application showing: Packaging is not valid, or package sign error

The problem
Titanium can successfully create the KeyStore file and Key Alias
but due to bug, it can’t sign the apk properly ..
unfortunately, you can’t see the error log in the console

Workaround
I guess you have a valid keystore file, keystore Password and Keystore Alias
If you don’t then you may make it with Titanium Distribution Dialog .. it works fine

clean and run the app in emulator 

run the command: 

cd APP_DIRECTORY/build/android/bin 

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_LOCATION app-unsigned.apk KEYSTORE_ALIAS

jarsigner -verify app-unsigned.apk 

zipalign -v 4 app-unsigned.apk PRODUCTION.apk