Friday, November 4, 2011

Blackberry JDE: Validate Email Address With Regex

There is no build in solution in the Blackberry JDE to validate an Email address. A common approach would be to use regular expressions with a Pattern Match approach.

Unfortunately the Pattern and Match classes are also missing in the JDE.

There is a third party Regex project for Java ME called Regexp-me.
http://code.google.com/p/regexp-me/
Check out the source files and integrate them into your Blackberry Java project.

Below example describes how to utilise the RE class.

public static boolean validateEmail(String email) {
     if(email.length() == 0) {
         return false;
     }

     String pttn = "^\\D.+@.+\\.[a-z]+";
     RE regex = new RE(pttn);
    
     if(regex.match(email)) {
         return true;
     }

     return false;
 }

That's it. Let me know if you have any problems with the instructions.

Tuesday, October 25, 2011

Free Joomla 1.6+ Amazon Component

Recently I wanted to integrate Amazon products as ads on my Joomla 1.6 Website. After hours of testing and research I decided to go with the free FSR Amazon Component for Joomla 1.6+.


With help of the component you can utilize the Amazon Web Service (AWS) to integrate Amazon product ads with your Joomla CMS 1.6 or 1.7.
The component comes with an easy to use backend part that allows you to integrate single products or product groups.

Below a feature list of the fsramazon Component:


  • AWS configuratiton

  • Partnernet (Amazon Advertising) Konfiguration

  • Farb-Konfiguration

  • Produktdetail Konfiguration

  • Erstellung von Seo optimierten Seiten

Below the description of the official Website:

fsramazon - free joomla amazon component (plugin/module)

Fsr Amazon is a component which can be used with the content management system (cms) joomla. With the help of this component products of amazon platforms can be integrated into joomla pages via amazon web service (» aws) and amazons » product advertising API. Not only displaying products in index and item (detail) pages is implemented, but also amazons affiliate program can be used in Fsr Amazon component to earn money.

Thursday, October 20, 2011

Blackberry JDE: Eclipse I/O Error: Cannot run program "jar": CreateProcess error=2

The Problem

At one point when I've created a new Screen in my Blackberry JDE Eclipse project I received an error:

Eclipse I/O Error: Cannot run program "jar": CreateProcess error=2

I searched the Internet for solutions and several people stated that this happend for them after the exceeded a certain number of files in their project. After trying different things I found the below solution working for me.

The Solution

The easiest fix for this error is to copy the jar.exe from the Java JDK binary folder to JRE binary folder.

The files is normally under:
C:\Program Files (x86)\Java\jdk1.6.0_27\bin\jar.exe

The version number can be different. But since Blackberry JDE only runs under 32 bit Java/Eclipse is has to be the Java version in the (x86) Program Folder.

Paste the file into:
C:\Program Files (x86)\Java\jre6\bin\jar.exe

That's it.

Tuesday, August 9, 2011

Xcode4: CSV Parser for iPhone/iPad iOS

Introduction

I had to dig a while to find a Objective C CSV Parser I like and that has decent performance on a mobile device. One problem is that most of those parsers are originally written for Mac OS and they are not all easily transferable.

The cCSVParse from Michael Stapelberg is one of those lightweight CSV parsers. Since the website is entirely in German I will write a little summary and provide example for the English speakers on the Web.

Installation

1. Download the library

Either clone the project from Git.
git://code.stapelberg.de/cCSVParse

Or download the archive from the CSV Parser Project Homepage. Scroll down to "Herunterladen" and click the link.

2. Copy the files in your project

Copy the parseCSV.h and parseCSV.m into your project. Make sure you have checked the copy function in Xcode.

3. Change the library for iOS use

Open the parseCSV.h and replace:

#import <Cocoa/Cocoa.h>

with:

#import <UIKit/UIKit.h>

Example of how to use the CSV Parser


#import "parseCSV.h"

...

- (void)parseMyCSVFile{

     CSVParser *parser = [CSVParser new];
     //get the path to the file in your xcode project's resource path 
     NSString *csvFilePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"csv"];
     [parser openFile:csvFilePath];

     NSMutableArray *csvContent = [parser parseFile];
     
     for (int i = 0; i < [csvContent count]; i++) {
	NSLog(@"content of line %d: %@", i, [csvContent objectAtIndex:i]);
     }
     [parser closeFile];
}

Wednesday, July 13, 2011

Xcode 4: Fatal: Not a git repository

Introduction


Recently I created a new project and at some point I uploaded it to SVN. I am not quite sure how to reproduce this situation but somehow the versioning support of Xcode 4 decided to interpret the project as a git repository.

Each time I tried to copy a file per drag and drop into my project I got following error:
fatal: Not a git repository (or any of the parent directories): .git

The result was that the file got copied into the project folder, but the reference didn't get set in the project. I had to go into the folder and drag and drop the file again and uncheck the copy option this time, so that the reference gets set.

The Solution


1. Open Xcode and go to Window > Organizer
2. Find under repositories your project. It might be two entries if you use something like SVN.
3. Make sure it says "Type Git"
4. Mark the repository entry and hit backspace or delete (on mac)
5. Done

Tuesday, June 28, 2011

How to use JavaScript in Joomla 1.6 Custom HTML Module

Introduction

Recently I tried to use a custom HTML module in Joomla 1.6.
There are a few problems with using this to get pure HTML displayed as you have copied it from somewhere to display a widget or something.
Even more complicated is to get JavaScript to work in the module. By default the <script> tag gets stripped out.

Be able to use pure HTML

By default any user in your Joomla backend (administration area) use the TinyMCE. When you create the Custom HTML Module the text field on the bottom left will also use this Editor. The problem is that this is a WYSIWYG editor(What You See Is What You Get). That means you basically enter regular text like in Word and the editor will translate it into the according HTML code. If you paste HTML into the editor it will not interpret the code as HTML.

There are two options to bypass that problem.

1. Go into HTML mode

The TinyMCE editor has a button HTML that lets you edit HTML. If you use this option you can past pure HTML there. Be aware that when you hit "Update" the Editor window only shows the interpreted code. So you don't see all the HTML tags anymore.

2. Turn of the Editor

I personally prefer the second option. If you worked a bit with HTML it will make sense for you too. Editors like TinyMCE still produce kind of messy code and things not always look like I want them.

To turn of the editor for your user perform the following steps:

  • 1. Go to Users > User Manager.
  • 2. Click on your user's name
  • 3. On the right select at Editor "Editor - None"
  • 4. Save
Now when you open a Custom HTML Module you just have a plain text field.

Be able to use JavaScript

If you past HTML code in the plain text field of the Custom HTML Module it should work now without problems. When you paste JavaScript though, the <script> tags will get stripped, which will make your JavaScript appear as text on the frontend.

To change the filtering of JavaScript in your text you can turn of filtering for your admin user like this:

  • 1. Go to Content > Article Manager
  • 2. Click Options
  • 3. In the Popup go to Text Fitlers
  • 4. Depending on what kind of user you are (e.g. SuperUser) change Filter Type to No Filtering
  • 5. Save & Close

Text or Textarea Attribute in Joomla 1.6 Module prevent filtering

Another related problem is that in modules you have sometimes attributes you can set. If it is a textarea you want to use HTML or JavaScript here as well, but it all gets filtered, even if you have the above settings applied.

A solution here is to modify the module xml file and add teh attribute filter="raw" to the field definition.

Now you should have no problem to paste JavaScript and save it in the Custom HTML Module.
Let me know if you have any problems.

Thursday, June 23, 2011

Point Domain to Subfolder in Bluehost for a Joomla 1.6 Installation

Introduction


Bluehost points your primary domain always to the public_html folder.
If you want to install your CMS like Joomla or Wordpress in a subfolder, rather than have all the files in the root, there is no easy build in way at Bluehost.

After reading through the Internet a trying tons of suggestions I found the solution that works for me and a Joomla 1.6 installation. It is a combination of several snippets I found online.

The Solution


Find the .htaccess file in the root folder (public_html) of you Bluehost webspace.
Open the file and add following code. Make sure you read the comments and make the according adjustments.

# Activate the rewrite engine
RewriteEngine on

# Replace yourdomain.com with your domain name.
RewriteCond %{HTTP_HOST} ^(www.)?yourmaindomain.com$

# Replace 'subfolder' with your subfolder name.
RewriteCond %{REQUEST_URI} !^/subfolder/

# Don't touch this line.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Replace 'subfolder' with your subfolder name.
RewriteRule ^(.*)$ /subfolder/$1

# Replace yourdomain.com with your domain name.
# Replace 'subfolder' with your subfolder name.
# set index.php to whatever necessary for your CMS, for Joomla you don't need to change it
RewriteCond %{HTTP_HOST} ^(www.)?yourmaindomain.com$
RewriteRule ^(/)?$ subfolder/index.php [L]

Permanent Redirect yourdomain.com to www.yourdomain.com


If you want additionally forward yourdomain.com to www.yourdomain.com add following code to the .htaccess right below "RewriteEngine On".

# use "www", replace yourdomain with your domain name
RewriteCond %{HTTP_HOST} !^www\.yourdomain\.com$
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]

Permanent Redirect www.yourdomain.com to yourdomain.com


If you instead want to do the redirect the other way around, add following code to the .htaccess right below "RewriteEngine On".

# use "www", replace yourdomain with your domain name
RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com$
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]

Troubleshooting

Please test after every step if everything is working so that you know at which point the new settings broke everything.

It also helps to clear the cache on your browser to make sure the current rewrite rules are used.

If you still have problems with your Joomla, I read it helps to additionally set the live_site parameter in the configuration.php to yourdomain.com.

Wednesday, June 22, 2011

How to Verify a Joomla 1.6.x Website with Google Webmaster Tools, Bing Webmaster Tools, Yahoo Site Explorer and Alexa

Introduction

This article describes how to verify your website with Google Webmaster Tools, Bing Webmaster Tools, Yahoo Site Explorer and Alexa, while using the Meta Tags verification method.


Downloading the latest Version

You can download it at the Link below.

Download v1.0 for Joomla 1.6.x:
plg_j_webmaster_verify_Joomla1.6_v.1.0.zip

Example


Here is an example of a Joomla 1.6 Website that is using the meta tags:

Moving-Boxes-Portal.com

Let your browser display the source code to see the <meta... entries. (Ctrl+U Windows, Command+Alt+U Mac)

Installation for Joomla 1.6


1. Download the Plugin from the Link above.

2. Go to your Joomla Admin area.

3. Go to Extensions > Extensions Manager.

4. Under Install, go to Upload Package File and click "Choose File".

5. After selecting plg_j_webmaster_verify_Joomla1.6_v.1.0.zip from your harddrive, click "Upload File & Install".

6. Go into the Plugin under Extensions > Plug-in Manager.

7. Find the Plugin name System - J-Webmaster Verify and open it.

8. Enable the Plugin. Enter the verification codes of the accounts you want to verify.

9. Save and you are done.

Get the required Verification Code, Example for Google Webmaster Tools


To be able to use Google Webmaster Tools you need an Google Account, if you have a Google Mail address your are good to go.

1. Go to Google Webmaster Tools Homepage

2. Click "Add a site..." and enter the URL

3. Select "Alternate Methods"

4. Select "Add a meta tag to your site's home page"

5. Copy the part that is in between the quotes after content.


6. Paste the string into the Plugin in your Joomla 1.6 backend under Google Key.

7. Done

The other verifications should be similar.
Let me know if you have any problems or questions.

Thursday, June 2, 2011

How to add the Google +1 Button to Joomla 1.6

Introduction

Recently I published a new Joomla 1.5 module for the Google +1 Button. Here now the same module for the all new Joomla 1.6. Integrate the button on your Joomla website without working in the code or change anything in the template.

Changelog/Latest Version

Joomla 1.6, Version 1.1, released June 10 2011

  • show total +1 counter ON/OFF beside the +1 Button
  • set a target URL for the +1 Button or keep the default (the page the button is embedded)

Joomla 1.6, Version 1.0, released June 02 2011

  • change size of the Google +1 Button, small, medium, standard, tall
  • add custom CSS with the +1 Button

Downloading the latest Version

You can download it at the Link below.

Download v1.1 for Joomla 1.6.x

Or check out the official Joomla Extension Website for more infos.

Example


Here is an example on how the Google Plus One Joomla Module looks in action:
Flopwatch.org

Installation for Joomla 1.6

In Joomla 1.6.x you can just install the new version as described below, there will be no conflict with an old version. In case you had one installed before.

1. Download the Module from the Link above.

2. Go to your Joomla Admin area.

3. Go to Extensions > Extensions Manager.

4. Under Install, go to Upload Package File and click "Choose File".

5. After selecting the mod_j_google_plus_one_for_j1.6.zip from your harddrive, click "Upload File & Install".

6. Go into the Module under Extensions > Module Manager.

7. Enable the Module and disable the Title. Make sure you have selected Pages it show up on.

8. Select the position and size of the button.

9. Save and you are done.


More about the Google +1 Button in a Google Video






Wednesday, June 1, 2011

How to add the Google Plus One Button to your Joomla 1.5 website

New update available, read below.

Introduction

I wrote a little Module for Joomla 1.5 that supports the new Google Plus One Button for your Joomla Website without working in the code or change anything in the template.

Download for Joomla 1.6

Here you can find the Download and Documentation for the Google +1 Button Module for Joomla 1.6.

Changelog/Latest Version

Joomla 1.5, Version 1.1, released June 10 2011

  • show total +1 counter ON/OFF beside the +1 Button
  • set a target URL for the +1 Button or keep the default (the page the button is embedded)

Joomla 1.5, Version 1.0, released June 02 2011

  • change size of the Google +1 Button, small, medium, standard, tall
  • add custom CSS with the +1 Button

Downloading the Extension

You can download it at the Link below.

Download v1.1 Joomla 1.5.x

Or check out the official Joomla Extension Website for more infos.

Example


Here is an example on how the Google Plus One Joomla Module looks in action:
Flopwatch.org

Installation

If you have never installed the Google Plus One module before go straight to "Install the new Version" otherwise make sure you uninstall the old version first.

Uninstall the old Version

1. Go to your Joomla Admin area.

2. Go to Extensions > Install/Uninstall.

3. Go to Modules.

4. Find and select the entry "mod_j_google_plus_one".

6. Click Uninstall.

7. Done.

Install the new Version

1. Download the Module from the Link above.

2. Go to your Joomla Admin area.

3. Go to Extensions > Install/Uninstall.

4. Go to Upload Package File and click "Choose File".

5. After selecting the mod_j_google_plus_one_1.0.zip from your harddrive, click "Upload File & Install".

6. Go into the Module under Extensions > Modules .

7. Enable the Module and disable the Title.

8. Select the position and size of the button.

9. Save and you are done.


More about the Google +1 Button in a Google Video






Wednesday, May 25, 2011

Checkout the all new Hattrick iPhone App - HT-SmartViewer

Earlier this year the Lite version was released and now there is Full version of the HT-SmartViewer. The App is written for iPhone it does work on iPad as well though.


The App is still free of charge and comes with tons of new stuff. Below are links to the articles that write about the features.

1. HT-SmartViewer The Home Screen/Social Media
2. HT-SmartViewer League Infos Feature
3. HT-SmartViewer Match Data Feature
4. HT-SmartViewer Match Stats Feature

The App Homepage is here: HT-SmartViewer Home. The App can be downloaded directly from the Apple AppStore here: HT-SmartViewer in the AppStore.




Based on user feedback and our own ideas the App will be extendend with new modules like conference, team and youth team infos, national team etc.

Tuesday, May 10, 2011

Objective C/Xcode 4: Check at runtime whether iOS device supports multitasking

Introduction


When I was recently in search for a code snippet that tells me whether the iOS device that the code is running does support Multitasking I quickly found some answers. All the answers seemed to be missing something though.

So below the solution I came up with, that satisfies all my requirements to check for multitasking of my iPhone/iPad/iPod device at runtime.

Difference between multitasking support of the SDK version and of the device version


Since version 4.0 iOS supports multitasking. Read more about it in this interesting article: Understanding iOS 4 Backgrounding and Delegate Messaging.

Even though you have iOS 4.x on your iPhone 3G it doesn't support multitasking. Multitasking is supported from iPhone 3GS and iPod touch G3 (both released in 2009) but not previous generations like iPhone 2G or 3G due to hardware limitations. Read more here: Apple announces multitasking for iPhone OS 4

The Code

//get the current device object
UIDevice* device = [UIDevice currentDevice];

//check if the currently running iOS knows the isMultitaskingSupport message (method)
if ([device respondsToSelector:@selector(isMultitaskingSupported)]){
        
        //check if the current device does actually support multitasking
        if ([device isMultitaskingSupported]) {
            //do some multitasking stuff

        } else {
            //deal with the lack of multitasking 

        }
        
    } else {
        //deal with the lack of multitasking 
    }

Wednesday, May 4, 2011

Bugzilla and Gmail: Send mail notifications/alerts via Gmail

Bugzilla is an Issue Tracking System that can send email notifications to its members. Most important Bugzilla sends an Email to the bug reporter or assignee of a bug. Bugzilla does support SMTP to send email notifications. That can be set when you are logged in as an administrator under Administration > Parameters > Email.

If you want to configure Bugzilla to use Gmail you have to consider that Gmail doesn't use standard SMTP, Gmail is using SMTP with TLS. I tried this tutorial BugZilla alerts using GMAIL, but I couldn't get it running and I found it somewhat confusing.

So I digged a little deeper and came up with my own more easy solution using Email::Send::Gmail rather than Email::Send::SMTP::TLS as described in the other tutorial. The steps are done with Bugzilla running on Apache2.2 Server with a Debian Linux OS. The instructions should be similar for other Linux distributions like Ubuntu, Fedora or RedHat Linux. Be awate if you run Bugzilla on a Windows Server especially the folder structure is different.

Install the Email-Send-Gmail package for Pearl


If you have Bugzilla installed and running then you have Pearl installed properly. Start the pearl command line.
# perl -MCPAN -e shell
Run the install package command for Email-Send-Gmail.
cpan[1]> install Email::Send::Gmail
Confirm all questions with 'yes'.
If everything is done leave the command line.
cpan[2]> quit

Optional Fix: Warning (usually harmless): 'YAML' not installed...


I fixed that by entering the below command in the regular command line:
# sudo apt-get install libnet-ldap-perl

Confirm Email-Send-Gmail was installed properly


Login as administrator into your Bugzilla and go to Administration > Parameters > Email.
You should be able to select an entry called "Gmail". Select it and save the changes for now.

Change Mailer.pm


Now we need to change the Bugzilla Mailer.pm to pass on the right parameters when sending emails via the new pearl package.

Go to your Bugzilla root folder on your server. For me that is /var/www/bugzilla.
# cd /var/www/bugzilla
In the subfolder of your Bugzilla root is another folder called Bugzilla. In this folder the Mailer.pm is located. Open it with the editor of your choice, e.g. vim or nano.

# nano Bugzilla/Mailer.pm

After the last line that starts with use enter:
use Email::Send::Gmail;
use Email::Simple::Creator;

The line that says:
if ($method eq "SMTP"){
change to:
if ($method eq "SMTP" || $method eq "Gmail") {
Save your settings and you are done here.

Configure Bugzilla's Email settings


Now again as an administrator go back to Administration > Parameters > Email in your Bugzilla.

mailfrom:
username@gmail.com or username@your_domain.com (if you use your own domain via Google Applications)

smtpserver:
smtp.gmail.com

smtp_username:
username@gmail.com or username@your_domain.com (if you use your own domain via Google Applications)

smtp_password:
your Gmail password

smtp_debug:
You might want to turn on debug to see if sending mails is working. if not you should get a debug message that should help you better narrowing the error down. When everything is working you can turn debug off.

Save your changes and you are good to go. Let me know if you run into problems.

Friday, April 29, 2011

Xcode4/CoraData: Using LIKE to search SQLite Table - "String starts with"

Problem


I recently had a task where a UITableView should suggest autocomplete for a word I started to type into a UISearchBar/Search Display Controller.

From the top of my head I came up with the SQL query that I wanted to use:

SELECT string FROM table WHERE string LIKE 'S%';

This query should return all the strings that start with capital S.

Solution


For a NSPredicate the query has to look like this:

NSString *query = [NSString stringWithFormat:@"String LIKE '%@%%'", startOfString];

Most important here is that the percent sign needs to be escaped with another percent sign (%%).

Friday, April 15, 2011

Xcode4: Set Company/Organization Name for specific Projects

Another thing that changed in Xcode 4 is how to tell Xcode to use a certain Organization name instead of the default "__MyCompanyName__" or the company name that is tight to your Mac user account.

Most prominent this value shows up in the comment copyright header when you create a new file in Xcode4.

1. Click on your project root in the Project Navigator on the left.


2. Enable your Utilities view on the right while the project root is marked.


3. Select the File Inspector. To make sure you are in the right location, the Identity should display your Project Name.


4. Under Project Document is a text field called Organization. Enter here the Organization name you want to show up for all your new files that get generated in this project.


That's it. Let me know if you have any problems or comments.

Sunday, April 10, 2011

Objective C: Adding an Enter/Search Button to Number Pad on iPhone Apps

In my Xcode projects where I needed a button on the Number Pad to initiate the intended action I used this tutorial: UIKeyboardTypeNumberPad and missing return key.

I also implemented the updates described in the Internet that make the hack compatible with either iOS version, below 3.2 and above, including iOS 4, iOS 4.1, iOS 4.2 and iOS 4.3.

Another improvement compared to the tutorial is that I put the image in the Background of the Button and use a Label in the foreground to be able to use any Label I want and make it localizable.




Below are the steps from the above website with my additions to accomplish the above features:

Create and Add the button images to your project


The button will be placed on the number pad in your iPhone or iPad App. To make it look good the button should look like the other number pad buttons when it gets clicked and when not. That means that the button has to states.

I modified a button from number pad to look like the other buttons. You can use them in your project if you want.



Call them buttonUp.png and buttonDown.png or whatever you want and copy them in your xcode project.

Prepare your ViewController Header (.h)


Make sure you have set your keyboard as the delegate for the UILabel that uses the Keyboard.

in ExampleViewController.h:
@interface ExampleViewController : UIViewController {
 UITextField *textField;
}
...
@property (nonatomic, retain) IBOutlet UITextField *textField;
...
- (void)addButtonToKeyboard;
- (void)keyboardWillShow:(NSNotification *)note;
- (void)keyboardDidShow:(NSNotification *)note;
- (void)buttonClicked:(id)sender;
@end

Prepare your ViewController (.m)


- (void)viewDidLoad {
    [super viewDidLoad];
...
// add observer for the respective notifications (depending on the os version)
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];     
    } else {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    }
...
}

- (void) viewWillDisappear:(BOOL)animated{
 [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)addButtonToKeyboard {  
    // create custom button
    UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
    yourButton.frame = CGRectMake(0, 163, 105, 53);
    yourButton.adjustsImageWhenHighlighted = NO;
    //set font button size and type
    yourButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    
    //set the label text of the button when its not pushed 
    [yourButton setTitle:@"SEARCH" forState:UIControlStateNormal];
    //set the color of the label text of the button when its not pushed
    [yourButton setTitleColor:[UIColor colorWithRed:0.302f green:0.33f blue:0.384f alpha:1.0f] forState:UIControlStateNormal];
    //set the background image of the button when its not pushed
    [yourButton setBackgroundImage:[UIImage imageNamed:@"buttonUp.png"] forState:UIControlStateNormal];

    //set the label text of the button when its pushed
    [yourButton setTitle:@"SEARCH" forState:UIControlStateHighlighted];
    //set the color of the label text of the button when its pushed
    [yourButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    //set the background image of the button when its pushed
    [yourButton setBackgroundImage:[UIImage imageNamed:@"buttonDown.png"] forState:UIControlStateHighlighted];
    
    [yourButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
 
    // locate keyboard view
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    UIView* keyboard;
    for(int i=0; i<[tempWindow.subviews count]; i++) {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        // keyboard found, add the button
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
            if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
                [keyboard addSubview:yourButton];
        } else {
            if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
                [keyboard addSubview:yourButton];
        }
    }
}

- (void)keyboardWillShow:(NSNotification *)note {
    // if clause is just an additional precaution, you could also dismiss it
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 3.2) {
        [self addButtonToKeyboard];
    }
}

- (void)keyboardDidShow:(NSNotification *)note {
    // if clause is just an additional precaution, you could also dismiss it
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
        [self addButtonToKeyboard];
    }
}

- (void)buttonClicked:(id)sender{
        //lets the number pad disappear after your clicked your custom button
 [self.textField resignFirstResponder];
 ...
        //do here what you want after the button was clicked
}


Troubleshooting

So far I came across only one problem and that was that my picture where not added properly to my project. Therefore clicking worked, but the buttons didn't show up. You can test this by adding a UIImage view manually to your NIB and see if the image shows in the list of images that you could set.

Let me know if you have more issues or suggestions.

Wednesday, March 23, 2011

Objective C/Xcode 4: Encoding Problem with Localizable.strings files

When compiling your Xcode project and your are using Localization in the Form of Localizable.strings and can happen that your get one of the following Build Errors.

Possible Build Errors

1.
Conversion of string failed. The string is empty. Command /Developer/Library/Xcode/Plug-ins/CoreBuildTasks.xcplugin/Contents/Resources/copystrings failed with exit code 1

2.
CopyStringsFile
...
Localizable.strings:0: error: validation failed: The data couldn’t be read because it has been corrupted.

Causes


These kind of errors can happen if you copy and paste content within Xcode or from external files in your localization files. The consequence is that the encoding of the file changes to for example Western (Mac OS Roman). The Localizable.strings file should be in UTF-16 though.

Solution


1.
Like in the picture below, navigate in Xcode to the Localizable.strings location and open it so that you can see all the languages you are supporting.


2.
Left-click on the language file the causes the build error.

3.
Make sure your Utilities View is showing in Xcode. Activate on the button at mark 1 in Picture below.


4.
In the Utilities View select the File Inspector. (Small Logo that looks like Page)

5.
Under Text Settings change the encoding to UTF-16(Marked as 2 in the picture above). The Drop-Down might be grayed out but you can click on it anyways. Click on "Convert" on the Popup.

That's it your project should now compile again.

Tuesday, March 22, 2011

Objective C/Xcode 4: How to label and internationalize a Round Rect Button (UIButton) programatically

If you only support one language it is easy to go into Interface Builder and set the Label of your Round Rect Button. For localization it is not as easy though.

How to use localization for UILabels


Text Label elements or UILabels can easily be set to a localized String with this command.

@synthesize nameLabel;

...

self.nameLabel.text = NSLocalizedString(@"name.label.translation", @"Comment for the name label.");

How to NOT use localization for UIButtons

Since buttons have different states the label would disappear if you click it and you only set the title like that.
@synthesize myButton;
...
//Wrong
self.myButton.titleLabel = = NSLocalizedString(@"button.label.translation", @"Comment for the button label.");

How to USE localization for UIButtons

The proper way is to assign the localized string to all states of the UIButton.

@synthesize myButton;
...
//Correct
NSString *buttonLabelString = NSLocalizedString(@"button.label.translation", @"Comment for the button label.");
 [self.myButton setTitle:buttonLabelString forState:UIControlStateNormal];
 [self.myButton setTitle:buttonLabelString forState:UIControlStateHighlighted];
 [self.myButton setTitle:buttonLabelString forState:UIControlStateDisabled];
 [self.myButton setTitle:buttonLabelString forState:UIControlStateSelected];

Wednesday, March 9, 2011

iPhone App: HT-SmartViewer Lite now in the AppStore

Its done. My first iPhone App made its way in the AppStore.

Get it for free now!

The App is a Match Viewer and Statistics App for the free Online Soccer Manager Hattrick. We hope to get people to use it and participate in the process to make it a really great, fun and useful Hattrick App.





Languages supporter are right now English, German, French and Spanish. If you want to see it in a different language feel free to contact us.

For feedback, news and more go to the HT-SmartViewer Homepage oder the HT-SmartViewer Forum.

Thursday, February 17, 2011

Objective C: Terminate App when pushing the Home button on iPhone/iPad

To make sure your iPhone or iPad App does not keep running in the background after you used the Home button, this is the way to go. Terminating the app helps saving resources on your device.

1. Open your project in Xcode.


2. Find the Info-iPhone.plist or Info-iPad.plist file.


3. Left-click once on it to see the Key Value pairs.


4. Right-click on one of the entries and select Add Row.


5. As key enter UIApplicationExitsOnSuspend.


6. Right-click on the new row and select Value Type Boolean.


7. Check the value field.


Let me know if you have any trouble.

Wednesday, February 16, 2011

Objective C: alternating background color in UITableViewCell for iPhone Apps

In one of my iPhone Apps that has a UITableView I wanted to make the background color of the UITableViewCells alternating. Having two different colors in the background of the cells help to improve the readability.


As you can see in the screenshot the odd cells are grey and the even cells are white.
The changes need to be done in the DataSource method cellForRowAtIndexPath.

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:@"cell"];
 if( nil == cell ) { 
  cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"cell"] autorelease]; 
 }
 Fruits *fruit = [fruits objectAtIndex:indexPath.row]; 
 cell.textLabel.text = fruit.fruitName; 
 
        //start of important code for background color changes
        cell.textLabel.backgroundColor = [UIColor clearColor];
 
 UIView *bgColor = [cell viewWithTag:100];
 if (!bgColor) {
  CGRect frame = CGRectMake(0, 0, 320, 44);
  bgColor = [[UIView alloc] initWithFrame:frame];
  bgColor.tag = 100; //tag id to access the view later
  [cell addSubview:bgColor];
  [cell sendSubviewToBack:bgColor];
  [bgColor release];
 }
 
 if (indexPath.row % 2 == 0){
  bgColor.backgroundColor = [UIColor colorWithRed:233.0/255.0
                green:233.0/255.0
                blue:233.0/255.0
                alpha:1.0];
 } else {
  bgColor.backgroundColor = [UIColor clearColor];
 }
 //end of important code

 return cell;
} 

Above is the whole method with all the additional code you need to get a white/grey background color alternation.

Lets go through the main changes in detail:

Make sure the cell text has a transparent background

cell.textLabel.backgroundColor = [UIColor clearColor]; 
This line makes sure your cell text has an transparent background, otherwise you end up with a result like in the screenshot below.

Create a view that holds the new background color

UIView *bgColor = [cell viewWithTag:100];
if (!bgColor) {
 CGRect frame = CGRectMake(0, 0, 320, 44);
 bgColor = [[UIView alloc] initWithFrame:frame];
 bgColor.tag = 100; //tag id to access the view later
 [cell addSubview:bgColor];
 [cell sendSubviewToBack:bgColor];
 [bgColor release];
}
First we check if the cell has already a view with tag id 100. If not, create a new view with the size of the cell(standard 320x44). Then the view gets add to the cell and send to the background.
If the view exists we don't need to create it again.

Set the color for odd and even cells

if (indexPath.row % 2 == 0){
 bgColor.backgroundColor = [UIColor colorWithRed:233.0/255.0
        green:233.0/255.0
        blue:233.0/255.0
        alpha:1.0];
} else {
 bgColor.backgroundColor = [UIColor clearColor];
}
If the cell index is even (0, 2, 4, etc.) the background color of the background color view is set to grey. Else it is set to clear (white).
If you want it to be the other way around use:
if (indexPath.row % 2 == 0){
...

Hope that helps. Please let me know if you have any problems or questions.

Monday, February 7, 2011

Objective C: Use Network Activity Indicator in iPhone Apps with GTMHTTPFetcher

The Google Toolbox HTTP Fetcher (GTMHTTPFetcher) allows you to send synchronous and asynchronous HTTP request in iPhone/iPad Apps using Objective C/Xcode.

Pretty common in those Apps is to display the network activity indicator during the request process.

The below instructions should also work for other HTTP libraries, you just need to replace the observer names accordingly.


This is how you can do it. The example tutorial below shows how to add this functionality to the RootViewController, but it could be added to any ViewController.

In the RootViewController.h


// RootViewController.h

#import <UIKit/UIKit.h>

@class GTMHTTPFetcher;

@interface RootViewController : UIViewController <UINavigationControllerDelegate> {

 int networkActivityCounter;
        ...
}

- (void)startFetchingData;
- (void)fetchData:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)retrievedData error:(NSError *)error;

@end

Important here is the networkActivityCounter that will later hold the number of requests that are currently running.

In the RootViewController.m


// RootViewController.m

- (void)viewDidLoad{
 //add observer for fetcher start and stop events
 NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
 [nc addObserver:self selector:@selector(incrementNetworkActivity:) name:kGTMHTTPFetcherStartedNotification object:nil];
 [nc addObserver:self selector:@selector(decrementNetworkActivity:) name:kGTMHTTPFetcherStoppedNotification object:nil];
 
 ...
 
}

First add the observers for the fetch start and stop events in the viewDidLoad method.

#pragma mark Network activity

- (void)incrementNetworkActivity:(NSNotification *)notify {
  ++networkActivityCounter;
  if (1 == networkActivityCounter) {
    UIApplication *app = [UIApplication sharedApplication];
    [app setNetworkActivityIndicatorVisible:YES];
  }
}

- (void)decrementNetworkActivity:(NSNotification *)notify {
  --networkActivityCounter;
  if (0 == networkActivityCounter) {
    UIApplication *app = [UIApplication sharedApplication];
    [app setNetworkActivityIndicatorVisible:NO];
  }
}

The increaseNetworkActivity is called when a fetch requested started, when the counter is at 1 the indicator gets displayed. After when the counter gets increased it doesn't need to be activated anymore, its still running.

Each time a fetch request has stopped the activity gets decreased, at 0 activity the indicator gets invisible.

- (void)dealloc {
 //remove the observer
 NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
 [nc removeObserver:self];
 ...
 
 [super dealloc];
}

Don't forget to remove the observer when not needed anymore.

Friday, January 14, 2011

Objective C: Remove certain characters from NSString

Sometimes when you work in Xcode in the Cocoa Framework you want to filter a NSString so that only certain characters are left. That can be numbers or letters or special characters. Following code snippet can do that for you.

//the String with the original text
NSString *unfilteredString = @"The sum of 1 + 2 = 3.";
//initialize a string that will hold the result
NSMutableString *resultString = [NSMutableString stringWithCapacity:unfilteredString.length];
    
NSScanner *scanner = [NSScanner scannerWithString:unfilteredString];
//define the allowed characters, here only numbers from one to three, equal and plus
NSCharacterSet *allowedChars = [NSCharacterSet characterSetWithCharactersInString:@"123+="];
    
while ([scanner isAtEnd] == NO) {
 NSString *buffer;
 if ([scanner scanCharactersFromSet:allowedChars intoString:&buffer]) {
  [resultString appendString:buffer];     
 } else {
  [scanner setScanLocation:([scanner scanLocation] + 1)];
 }
}
//Print out the result String, will be 1+2=3   
NSLog (@"Result: %@", resultString);

Wednesday, January 5, 2011

Turn Eclipse project into Java project

Sometimes you have a project in Eclipse that needs to be changed into a Java Project. Lets call that furthermore "Example".

The description is made with a Dynamic Web Project as the example Java Project. With some easy and obvious changes you could also use this tutorial for a Static Web Project etc.

1. Create a dynamic web project as helper


2 Files will be needed later in the project you want to change into a Java project. We create a dynamic web project to get those two files. That is the .project and the .classpath file.

You can delete this temporary dynamic web project when we are done with everything.

To create the dynamic web project open eclipse and go to the project explorer. Right-click and select New > New Project. In the "Select a wizard" under Web choose "Dynamic Web Project".

Then hit Next and type in the next view the Project name, e.g. "Temp", and hit Finish.

2. Change the .project file of the actual project "Example"


To change the .project file you have to first navigate to the file in a file browser. In Windows you can use the Explorer to go to the project folder, in Mac OS the Finder.

The example project has already a .project file, but the file is invisible. That's why you have to make sure that you can see invisible files in your browser. Here is a good description how to show invisible files in Finder on Mac OS.

In Windows Explorer you click Extras > Folder Options > View and then select something along the lines "display invisible Folders and Files".

When the file shows up for you, you have to open it in a text editor. Then also open the .project file in the "Temp" project folder and copy the content in the "Example" .project file. But make sure that you don't override the name tag. It should still read "Example".

The file look somewhat like that:



 Example
 
 
 
 
  
   org.eclipse.wst.jsdt.core.javascriptValidator
   
   
  
  
   org.eclipse.jdt.core.javabuilder
   
   
  
  
   org.eclipse.wst.common.project.facet.core.builder
   
   
  
  
   org.eclipse.wst.validation.validationbuilder
   
   
  
 
 
  org.eclipse.jem.workbench.JavaEMFNature
  org.eclipse.wst.common.modulecore.ModuleCoreNature
  org.eclipse.wst.common.project.facet.core.nature
  org.eclipse.jdt.core.javanature
  org.eclipse.wst.jsdt.core.jsNature
 


3. Change the .classpath file of the actual project "Example"


The "Example" project has no .classpath file yet. We can copy the .classpath file from the "Temp" project into the project folder.

The .classpath is invisible as well, but with the changes above it should be visible in the file browser as well.

4. Add Project Facets


That the changes from above take effect you first have to completely shut down eclipse. After the restart of eclipse the project should already be a Java project. That the project compile correctly you need to add some required facets.

Therefore right-click in eclipse Project Explorer on the project folder. Then open Properties and go to Project Facets. Here check Dynamic Web Module and Java.

5. Add required libraries (JAR files) to the project


This steps describes how to add the 3rd party libraries that are required in the project. Normally those jar files are stored in WebContent/WEB-INF/lib.

To add them to the classpath, open the project properties like described in step 4. Then select Java Build Path. Under Libraries select "Add JARs..." and navigate to WebContent/WEB-INF/lib and mark all .jar files you need. After hitting OK the libraries are added and you are good to go.

Troubleshooting


If there are still errors in your project it could be because your project needs libraries from the Apache Tomcat. If you go right-click on the project. And then select Run As > Run on Server and go through the whole process the needed Library will be added.