RSS

Category Archives: How-to

9 How To: RSS and News Feeds

RSS is a term that encompasses a number of web feed formats used in the publication of frequently updated works such as information on news-related sites, blogs, forum posts. Articles can contain both text and links to media such as images, movies etc.

What does RSS actually stand for? – there are several expansions of the term RSS such as Really Simple Syndication, Rich Site Summary etc. Here some descriptions of RSS:-

RSS Explained:-
http://www.whatisrss.com/

Wikipedia RSS
http://en.wikipedia.org/wiki/RSS

.
The most commonly used formats are RSS followed by Atom. HAC can process both these formats plus some custom formats as well. It can also process sources from either a URL or a text file. Usually the term RSS is generic and refers to RSS plus Atom and custom formats.
.
With HAC, users do not have to specify the format because HAC tries to be flexible and process as much of each article as possible. For each article it is asked to keep, it saves every field it can parse, and also saves their field names. This allows the programmer/user to decide which fields to use. Fields are created by HAC in the order in which they were found.

Apps handling news feeds need some protection because RSS feeds can potentially be huge and any attempt to download/process the entire feed could cause a memory exception in the app. Therefore HAC allows feeds to be interrogated for their size and has options to process a specified range of articles. For instance, if there were 1000 articles in the source, then the user might like to just look at articles in the range 100 to 150 without downloading/parsing the entire source.
.
.
Example Feeds
Here are some example feeds used in testing the HAC RSS example project.

Atom feed
http://blog.case.edu/news/feed.atom

HAC Forums RSS:-
http://www.tigabyte.com/forum/index.php?action=.xml;type=rss

BBC News Feed:-
http://feeds.bbci.co.uk/news/world/middle_east/rss.xml

Global Sport feed:-
http://globoesporte.globo.com/dynamo/futebol/times/vasco/rss2.xml
.
.
Reading Feeds
There are 3 steps in using RSS

  1. Get feed from URL or a file.
  2. Parse the feed for articles.
  3. Examine or display articles.

The format of articles is explained below.

.

Feeds and Articles

Feeds are comprised from a number of articles and each article can have several named fields although there can be more than one field with the same name. The situation can be more complex though as some sources use custom formats where fields have sub fields etc. Custom formats are more complex to parse and HAC RSS parsing currently doesn’t support them as its parser just looks for top level elements/fields.

The list below shows comparative field names for RSS and Atom although there is nothing to stop sources having their own unique field names:

.
.

EXAMPLE: Creating an RSS Reader

Here we will show you the scripts behind a basic RSS reader that can work with the formats: RSS, Atom and some custom ones. As mentioned above there are 3 stages to reading an RSS feed although HAC combines both the fetch and parse stages into one function. Note, for clarity, it does not show any error checking.

a) Open and Parse Feed

To parse an RSS source use the RssParseSourceFN function. This function returns a count of the number of articles found although if an error occurred it returns -1. It automatically stores any retrieved articles and their field names so later they can be processed or displayed. Note, for app safety, a maximum article limit must be specified so for instance if the feed contained a million articles then your app could limit itself to just 100 articles. There is also a start value that enables a number of articles to be skipped.

The code below shows how to parse an RSS feed:-

@ --- Reads BBC news source ---
Local mode,source,start,max

@ read from URL so set mode = 2 (=1 for file)
PUT 2 INTO mode

@ Set URL
PUT 'http://feeds.bbci.co.uk/news/world/middle_east/rss.xml' INTO source

@ Set limits
PUT 1 INTO start
PUT 100 INTO max

@ Retrieve and parse source
PUT RssParseSourceFN(mode,source,start,max) INTO field 1

@ Display article count found
PUT RssArticleCountFN INTO field 2

.
It you just want to count how many articles are in the source then use the RssParseCountFN function. This parses the source but does not store any articles. Again, for safety it requires the maximum number of articles to parse. The example below shows how to do this.

@ --- Reads BBC news source ---
Local mode,source,max

@ read from URL so set mode = 2 (=1 for file)
PUT 2 INTO mode

@ Set URL
PUT 'http://feeds.bbci.co.uk/news/world/middle_east/rss.xml' INTO source

@ Set limits
PUT 10000 INTO max

@ Parse and count source
PUT RssParseCountFN(mode,source,max) INTO field 1

.

b) Accessing Retrieved Articles

Once the articles are retrieved to memory then they can be processed and displayed. The RssArticleCountFN returns the number of articles previously retrieved and can be used to loop over the articles.

Each article has a number of named fields such as AUTHOR, CATEGORY, DESCRIPTION etc. There is no restriction though on uniqueness of the field names so for example an article might have several fields named DESCRIPTION. Furthermore, articles within the same feed can have different numbers of fields and different field names. The number of field names and a list of their names can be retrieved using the functions RssFieldCountFN and RssFieldNamesFN respectively. Note, all field names are forced to uppercase. There is also a function called RssFieldListFN that returns in list form the name of every field found in the source.
.
The script below shows how to retrieve the contents of a known named field called DESCRIPTION from article number 5.

@ --- Display DESCRIPTION field of article 5 ---

PUT RssFieldByNameFN(5,'DESCRIPTION') INTO field 1

.
.

The script below shows how to loop over all of the fields in article 5.

@ --- Displays article 5 ---
Local aid,count,f

@ set article number
PUT 5 INTO aid

@ how many fields
PUT RssFieldCountFN(aid) INTO count

@ Loop over all fields and place into text field 1
Clear field 1
FOR f=1 TO count
   PUT RssFieldByNumberFN(aid,f) AFTER field 1
ENDFOR

.
.
c) Tidying Up

Once you have finished using the retrieved articles it is a good idea to clean up and free the memory they occupied, especially if hundreds or more articles were retrieved. The RssClear command frees memory used for storing all article headers, fields and articles themselves.

@ --- Clear memory used by RSS ---

RssClear

.
.

.
Summary
This article shows how to create a very simple RSS reader using HAC and briefly looks at a few of its RSS commands/functions. For more details see the project link below.

With HAC an RSS app can:

  1. Read RSS, Atom and some custom formats.
  2. Read from either a URL feed or a text file.
  3. Limit the number of articles parsed
  4. Skip articles and retrieve just a range.

For more information about creating RSS apps with HAC, look at HAC’s built-in help or its HAC Help pdf.

There is an RSS project and its built app on our examples web page http://www.hypernextandroid.com/hnfiles/rescreator.html The project example is only test bed that demonstrates HAC’s RSS functionality.

.

Members of HAC forums can download the latest trial version of HAC, see details here:- http://www.hypernextandroid.com/hnfiles/downloads.html

 

8 How To: Android Databases

Android Databases

This article give a brief overview of Android (SQLite) databases and how they are used with HAC. It then shows how to create a simple book database app. Both a book database project and its app can be downloaded from the HAC projects web page.

So what is a database? A database is an organized collection of data arranged in one or more tables. Each table represents one collection such as a book or video catalog and has its own layout as defined by its record structure. Each record within a table is stored in its own a row, and all rows within the table have the same format as defined by the number of fields(columns) and their data types.

A table within a database has:-
– rows and columns
– a row = one record
– a column = fields within the records

For instance a record may have the following format:-
Column:-      1       2                   3                   4
Name:-        ID     Title             Author         Comment
Values:-       1      Android      J Smithy      Android coding

Note, each table has a primary column and the primary column values must be unique to ensure individual records can found. Generally the database itself takes care of the primary column as records are added to it.

.

Location of Database Files

The Android OS ensures that each app can store database files within the app’s private protected folder thus preventing other apps from accessing them and users from browsing for them. These protected database files are often referred to as internal database files.

There are times though when it is necessary to work with so called external database files, These are database files in other locations such as on the SD card or when bundled with an app in its data folder. External database files are particularly useful when it comes to backing up, upgrading, emailing or exporting the database onto a desktop computer.

HAC apps can work with both internal and external database files. It also has Export and Import functions for copying databases both from the internal area and into the internal area.

HAC apps can work with multiple databases simultaneously and in order to do this most HAC database related commands/functions identify the database by specifying its full file path.

.

Using a Database

The 4 basic operation on databases are Create or Open, Insert, Query and Upgrade

  1. Create – this creates a database as specified by the location, table name and record structure
  2. Insert – this puts records into the database
  3. Query – this requests information or records meeting certain criteria from the database
  4. Upgrade – used when the structure of the database must be changed – eg adding an extra column.

.

Defining a Database

Before creating and using a database some thought must be given to the structure and format of the data to be stored. For instance, are the fields numeric or text, and which field is the primary one.

Android SQLite has the following three data types although it does not check for valid data formats -:-

  • text (string) – eg ‘Hello World’,
  • long integer – eg 23095
  • real – eg 14.268

Note, HAC uses strings(text) for all its variables and will automatically convert the data types to string.

.

Example of a Book Database

This example is a simple book database where the database file name is ‘infox.db’ and the table name is ‘books’. It has the following record format:-

ID (primary) – integer
Title – string
Authors – string
Comment – string

With HAC most of the database related commands and functions require that the database be identified by specifying its full file path.

Note, many of HAC’s database functions return a 1 if successful, otherwise they return 0. However, in the example below, no error checking is carried out in order to try and make the code easier to understand.

a) Open or Create

A database must be open before it can be used. If it already exists then opening it will do, otherwise it must be created, after which it will be in the open state.

Opening an existing database is easy, just use the DbOpenFN function. This function needs the full file path to the database and the file path can point to either an internal or external database file. The database can be set to either read-only mode or read/write mode by setting the mode flag to 0 or 1 respectively.

Creating a database is more complex because the structure of the database must be passed to the DbCreateFN function. In the following example it is assumed that the database does not exist and therefore must be created.

Note the part where it forms the file path pointing to the database. Line 10 uses a database file within the App’s ‘Local Folder’ while Line 11 has a commented out part which refers to an Internal database file.

@ --- sets the database path ---
@ -- local path is chosen but internal commented out ---
Global dpPath
Local dbname

@ filename
Put 'infox.db' into dbname

@ --- form source path ---
Put LocalPathFN into dbPath
@Put DatabasePathFN into dbPath
Append '/' onto dbPath
Append dbname onto dbPath

This next part specifies the table structure and then creates the database:-

@ --- sets up and creates database from dbPath ---
@ --- table name is 'books'
Global dbPath
Local version,table,structure,okay

@ db version
Put 1 into version

@ table name
Put 'books' into table

@ form db structure - columns and their data types
Put '(' into structure
Append '_id integer primary key autoincrement,' onto structure
Append  ' title text not null,' onto structure
Append  ' author text not null,' onto structure
Append  ' comment text not null);' onto structure

@ --- Create Database ---
Put DbCreateFN(dbPath,version,table,structure) into okay

.

b) Insert 3 records

The SQL commands for inserting a record and its data into a database can appear quite daunting to the uninitiated therefore the HAC commands try to make it easier for the beginner to insert data into a database.

The insert data process uses three steps to insert a record:-
1 – Init – creates the record
2 – Build – adds data to the record
3 – Insert – inserts the record into the database

@ --- insert 3 records into the database ---
Global dbPath
Local dbname,path,command,okay

@ --- Record 1 ---
DbInsertInit(dbPath,'books')

DbInsertByName(dbPath,'title','Android G1')
DbInsertByName(dbPath,'author','Zaks')
DbInsertByName(dbPath,'comment','info about phone')

Put DbInsertDoFN(dbPath) into okay

@ --- Record 2 ---
DbInsertInit(dbPath,'books')

DbInsertByName(dbPath,'title','Dogs')
DbInsertByName(dbPath,'author','Meloni')
DbInsertByName(dbPath,'comment','about dogs')

Put DbInsertDoFN(dbPath) into okay

@ --- Record 3 ---
DbInsertInit(dbPath,'books')

DbInsertByName(dbPath,'title','Android Databases')
DbInsertByName(dbPath,'author','Peters')
DbInsertByName(dbPath,'comment','Android and sql')

Put DbInsertDoFN(dbPath) into okay

.

c) Queries

Querying a database involves asking it if certain fields contain a search value(s), either strings or numbers. The database will then return any requested fields in the form of an array that can then be accessed for information. Queries can be quite complex, involving matching several fields to values, in which case SQLite really shows its power.

Building the query is the most difficult part of querying a database because the programmer needs to have some understanding of SQLite syntax. The example shown here is simple but still very useful.

There are three steps to querying a database:-
1 – Build – build the query command(string).
2 – Execute – execute the query command on the database.
3 – Retrieve – retrieve any results from query.

Note, if the query string contains single quotes then this can clash with HAC’s compiler syntax as HAC uses single quotes to start and end literal strings. Therefore in the example below the single quotes which are part of the query are implemented using the ChrFN(39) function. At the present time there are also some issues with the Android OS implementation of SQLite, in particular for strings containing special characters such as % sign.

@ --- Query database records for titles including 'Android' ---
Global dpPath
Local table,query,count,n

@ -- set table name --
Put 'books' into table

@ -- build SQLite query string --
Put 'SELECT _id, title FROM books WHERE title LIKE ' into query
Append ChrFN(39) onto query
Append '%Android%' onto query
Append ChrFN(39) onto query

@ -- display query in field 1 --
Put query into field 1

@ -- execute and display query status in field 2 --
Put DbExecQueryFN(dbPath,query) into field 2

@ -- see how many results were returned --
Put DbQueryCountFN(dbPath) into count

@ -- display count in field 3 --
Put count into field 3

@ -- display any results in field 4 --
Clear field 4
if count>0 then
    for n=1 to count
        Put DbQueryResultFN(dbPath,n,'title') after field 4
    endfor
endif

.

d) Close
It is best to close a database when it is not in use as this makes it less likely to be corrupted and also saves memory.

@ --- Close database ---
Global dbPath

DbClose(dbPath)

.
Summary
The above example should help almost anyone create their own database app with HAC. Although it doesn’t go into much depth with SQLite syntax it still shows how to create a database, add information to it, query the database, and then close it.

HAC supports both internal and external databases, and apps can have multiple databases open at the same time.

For more information about creating database apps with HAC, look at HAC’s built-in help or its HAC Help pdf.

There is a database project and its built app on our examples web page http://www.hypernextandroid.com/hnfiles/rescreator.html Compared to the example presented here, the project is more of a test bed that demonstrates HAC’s database functionality.

.

Members of HAC forums can download the latest trial version of HAC, see details here:- http://www.hypernextandroid.com/hnfiles/downloads.html

 
Leave a comment

Posted by on 15/10/2012 in Databases, HAC, How-to

 

7 How To: UDP Messaging and Datagrams

UDP Messaging
This article describes how to use UDP to create a simple chat program with HAC but first what is UDP?

UDP stands for User Datagram Protocol and is an easy way to send short messages because unlike TCP it does not expect an acknowledgment from the receiver. The message is sent to the target as a datagram which has just two parts, the sender’s address and the message content. UDP is often used in games and other time critical applications where the sender does not have time to wait for an acknowledgement from the receiving party. It is useful when the loss of a single message is not crucial although in practical terms message loss is very unlikely on local networks unless the network and/or the related devices are very busy.

UDP advantages are:-

  1. fire and forget with no need to check if received.
  2. fast as packets are much shorter.

UDP disadvantages are:-

  1. does not work on some phone networks as they block ports.
  2. for internet use it may not work if you or your target are behind a router.

A example of using UDP is when a master device must communicate with a number of slave devices such as in local network of a school or business. Another example is using a device to communicate with a microprocessor or other hardware device that supports UDP.

More information about UDP is given towards the end of this article and further details can also be found here:-

eHow – about UDP ports

What is UDP on Yahoo

.

How to use UDP?
Using UDP is very simple, just create a socket and set some parameters. You need to know the device input address, target address and which ports to use. As HAC apps can have several sockets open at a time so most UDP commands/functions need a socket number.

The app has to create a socket and then attach this socket to a port on the device. Ports are like openings onto the computer that can both receive and send data. Ports can listen for incoming datagrams and trigger an event when one arrives.

The basic parts of using a UDP socket are:-

  1. Create a UDP socket that handles ports and events.
  2. Connect the socket to a port to enable listening and receiving.
  3. Send a message.
  4. Receive a message.
  5. Event Handling.

.

UDP Example Project
This example comes from the HAC UDP demo project which is included with the more recent versions of HAC installer. It is also available on our website along with a built Android app:- HAC Project Web Page

If you need to test your UDP app then a full featured but easy to use UDP tester can be downloaded from  here:- Simple Tools UDP Test Tool

The UDP project described here has just two screens, the network setup screen and the chat screen.

The network setup screen in Fig 1 shows the device(host/local address) as 192.168.1.64 and the target/recipient as 192.168.1.71. Both the host and target are using port 5042.

Fig 1- UDP Network Setup

.

A screen shot of the actual chat part of the app is shown below in Fig 2. The top field is where the user enters their message and the lower field is the log where both their text and that of their target appear.

Fig 2 – UDP Chat

.

1) UDP Socket Creation
A socket is used to connect with the port and trigger any UDP events. The UdpCreateFN function will try to create a socket and if successful will return a positive integer as the socket number, otherwise it will return 0.

Global sockNum

Put UdpCreateFN into sockNum

if sockNum<1 then
   Message 'Cannot create socket'
endif

To delete a socket and free up its memory use the UdpDelete command.

.

2) UDP Binding to a Port
In order to send or receive messages a socket must be bound or connected to a port. Once a connection is made then the port will listen for incoming messages and transfer them to the socket so it can raise a UDP event. As well as a socket number, making a port connection also requires the expected maximum size of the message in bytes and a rest time specified in milliseconds. The maximum message size is used in creating a buffer for holding the message and details of acceptable sizes are given later on. The rest time is used to reduces the load on the device so that after a message is received the listener will rest before listening again. If the rest time is set to zero then no rest is allowed and the listener will work continuously.

In the code below the message size is set as 1024 bytes and the rest time as 1000mS.
The port number is obtained from field 2 and is 5042 as shown in Fig 2.

Global sockNum
Local port

Put field 2 into port

UdpConnect(sockNum,port,1000,1024)

To stop listening but still keep the socket in memory use the UdpClose command.

.

3) UDP Sending a Message
Sending a message requires specifying the target address, the message and the encoding to use for the message.

In the code below field 1 is where the user enters their text and field 2 is the log window as shown in Fig 2. The target address is obtained from the network screen, in Fig 1, as when the Chat button is pressed it simply loads the value of field 1 into the global variable targetAddress.

The encoding is used to set the format of the message string and depends upon the message contents such as language used or whether it is binary. Both the sender and receiver should agree on the encoding used.

Global sockNum,targetAddress
Local message

Put field 1 into message

Put 'Local ' after field 2
Append message onto field 2

UdpSend(sockNum,targetAddress,message,'UTF8')

.

4) UDP Receiving a Message
When a message is received by a port that is bound to a socket then that socket will trigger a UDP ‘Data Received’ event. In this event the app can process the message and make any necessary response.

The received datagram has two parts, the message, and the sender’s address. Assuming a datagram has been received then the following code would extract the data and address from the specified socket. The actual socket number can be found within the event as shown later.

Local data,address

Put UdpRxDataFN(sock) into data

Put UdpRxAddressFN(sock) into address

.

5) UDP Events
There are three types of UDP event in HAC apps, Data Received, Message Sent, and Error. Their integer values are 1,2 and 3 respectively.

When a UDP event occurs it triggers the UDP script. This script can be edited using the script editor and is located in the Specials section of the Editor.

Whenever a UDP event occurs then the event script should check to see:-

  1. Which socket raised the event.
  2. What the event is.

The following code shows how to handle a UDP event:-

Local sock,event,data,address

Put UdpIndexFN into sock

Put UdpEventFN into event

if event=1 then
   @ Data Received
   Put UdpRxDataFN(sock) into data
   Put UdpRxAddress(sock) into address
else
   if event=2 then
      @ Message sent
   else
      @ Error
   endif
endif


Additonal Info
It is possible to create your own protocol by embedding commands inside the messages so that both receiver and sender can coordinate their responses. As the messages are just strings then a simple protocol might be as follows:-

  • first 3 characters representing the command – eg 001
  • the next 5 characters representing the port – eg 45000
  • the rest of the message.

Note, on some platforms the UDP listener will hear its own messages but they can be filtered out by checking if the address of the incoming datagram matches that of the device address. An app can find its own address using the function InputAddressFN.

The maximum size of a datagram message is 65,508 bytes although some networks limit this to 8,192 bytes. If the message size exceeds the network limit then the message will be split into multiple datagram packets therefore if the maximum size is not known then 8192 bytes might be a safe size to use.

.

Summary
With UDP it is very easy to make a simple messaging system although how complex it becomes will depend upon your needs. Messages are sent to the target machine as a datagram that includes just the message and sender’s address so allowing simple chat systems to be built. The main drawback of UDP is that it has problems  working on the internet where the computers are one of several connected behind a router or on mobile phone networks where mobile providers often block ports.

Despite UDP’s drawbacks it is very easy to set up a messaging system on a local network or send data to any device that understand UDP.

.

Members of HAC forums can download the latest trial version of HAC, see details here:- http://www.hypernextandroid.com/hnfiles/downloads.html

 
Leave a comment

Posted by on 01/06/2012 in HAC, How-to, network

 

6 How To: Develop for the Kindle Fire

What is the Kindle Fire
Amazon’s Kindle Fire is a tablet computer version of their Kindle eBook reader. It runs a modified version of Google’s Android operating system so allowing users to run and source apps originally intended for Android devices.

http://en.wikipedia.org/wiki/Kindle_Fire

http://www.amazon.com/Kindle-Fire-Amazon-Tablet/dp/B0051VVOB2

http://gigaom.com/mobile/kindle-fire-helps-amazon-appstore-hits-31000-apps-in-first-year/

This article takes a brief look at using HAC(HyperNext Android Creator) to develop apps for the Kindle Fire. Before that though we mention the two traditional approaches to developing for the Kindle Fire. However, if you don’t know or don’t want to use Java then just skip this next section and go to:- HAC and Kindle development.

Kindle and Android SDKs
Amazon provides a free Kindle SDK(Software Development Kit) so developers with a good knowledge of Java and the Android APIs can create their own apps. The Kindle Fire runs a modified version of Android Gingerbread and therefore has some differences from the official Google Android Gingerbread.

It is possible to use Google’s Android SDK to develop apps for the Kindle Fire but there is some Kindle functionality that the Android SDK cannot provide.  In contrast the Kindle SDK gives the developer full access to all the Kindle Fire’s functionality such as showing and hiding the Options Bar whereas the Android SDK cannot access these Kindle specific features.

The advantage of using only the Android SDK approach is that your app can potentially run on both standard Android devices such as Xoom etc as well as the Kindle Fire and you do not have to try to keep projects synchronised with the Kindle SDK. The disadvantage is that it can be awkward to get your app to look right on the screen because the Options Bar can hide the lower part of it:-
http://stackoverflow.com/questions/9340606/

HAC and Kindle Development
Developing for the Kindle Fire with HAC(HyperNext Android Creator) is much the same as using HAC to develop for a standard Android device with just a couple of things to look out for. Note, that HAC apps know when they are running on a Kindle Fire and automatically take care of optimising the screen coverage so users don’t have content hidden by the Options Bar. HAC developers can also add a device check inside their app to see which type of Android device it is running on and so take appropriate actions.

1) Screen Sizes
The Kindle Fire screen size is 1024 x 600 pixels with 20 pixels taken by the top Status bar and 40 pixels taken by bottom Options bar. HAC built apps automatically detect screen dimensions and handle the screen drawing so the app creator just has to choose the appropriate screen settings as described below.

HAC offers 3 options for allowable screen orientation;- either portrait or landscape, portrait only, landscape only.

During the development of your app HAC offers 3 screen scaling options: none, fit or stretch. The option none is only really useful when targeting a specific device where both orientation and screen size are known in advance. The fit option keeps the ratio of the apps height to width ratio constant irrespective of which physical device it is running on or whether the screen orientation is changed. This ratio is determined from the size given to the home card. The stretch option simply stretches the app’s screen area to fully cover the usable screen area but can result in large distortion if both portrait and landscape orientations are allowed.

To setup the screen orientation and scaling, open HAC’s Your Application window via the Android menu and it should look similar to Fig 1 below:-

Setting orientations and screen scaling

Fig 1 –  HAC’s Your Application window showing app screen setup

2) Carousel Icons
Most Android smart phones and tablets have used a 2D array of icons to represent their installed apps but the Kindle Fire also has a  stylish carousel to display them in. The carousel displays the most recent apps, books etc and represents an app by displaying its attached icon . If it can’t find the correct icon it will use an app’s launcher icon although this can result in apps with low resolution  icons looking very shabby and dated.

Fig 2 below shows the carousel on a Kindle Fire although unfortunately the camera could not accurately capture the true color of the app icons.  Three of the apps are made by HAC with one having a 200 x 200 icon and the others using older 48 x 48 icons.

From left to right the apps on the carousel are:-

1 – Kindle Test with 200 x 200 icon

2 – Lunar Lander with 48 x 48 icon

3, 4, 5 – standard high res Kindle icons

6 – PreSchool Sums with 48 x 48 icon

Note that as they are PNGs their transparency works

Fig 2 – Kindle Fire carousel

HAC supports icons up to 800 x 800 pixels so allowing an app to look stylish in the Kindle Fire’s carousel. If the icon is in PNG format then transparency is supported. Note that these icons will still work on older Android devices such as the G1 smartphone because the Android system does its own scaling.

To add an icon to your app, open HAC’s Your Application window using the Android menu and assign the icon to the area highlighted by red as shown in Fig 3  below. Either drop your icon onto the icon area or else navigate to it using the Launcher button:-

Setting icon for your app

Fig 3 – HAC’s Your Application window showing launcher icon area


Summary
When designing for the Kindle Fire, just treat it as another Android Device but remember to create a higher resolution icon for it otherwise your app can look shabby and dated sitting on the carousel. Also think about which screen orientation(s) your app needs. Note, although this article has covered the Kindle Fire, the above points about screen sizes, orientations and launcher icons are still relevant to creating apps for other Android devices.

Members of HAC forums can download the latest trial version of HAC, see details here:- http://www.hypernextandroid.com/hnfiles/downloads.html

 
 

5 How To: Create and Use an Emulator (AVD)

Emulators, also known as AVDs(Android Virtual Device) allow users to test their apps on different versions and setups of the Android operating system without having an actual physical device present. Here we will explain how to create an emulator, launch it and run your app/project on it. At the end are a few tips on emulators.

Creating an AVD in three steps
It is very easy to create an Android emulator using the Android AVD Manager.

1) From within HAC, load the Android AVD Manager by using the menu Android and option Android Emulators.
The AVD Manager image below shows it with no AVDs created:-

1 Empty AVD Manager

.
2) To create a new AVD click the New button as shown above and the following window will open.
An AVD needs these options setting:- the name of the AVD, the target Android API to use and the SD Card size in MB as underlined in the picture.

2 Create AVD

.
3) Once the settings have been filled in then click the Create AVD button and it will open the AVD Manager showing the entry for this newly created AVD:-

3 AVD Manager with AVD present

.
Running an Emulator
There are two easy ways to run an emulator. Firstly by using the Android AVD Manager as shown above, in which case just highlight the required emulator and click the Start button. Secondly, from within HAC using its Android Device Manager as shown below. This lists all the AVDs known to HAC in the top half of the window and displays running AVDs and Android devices in the the bottom half. To run an emulator just select it from the upper list then use the HAC menu Go and option Launch Emulator.

HAC Manage Devices

.
Running Project on an Emulator/Device
HAC’s Android Device Manager lists all of the running emulators and Android devices in the bottom list. To run the project on an already running emulator or device just select the target emulator/device from the lower list then use the HAC menu Go and option Run Android.
.
A Few Tips
(1) An emulator’s first run is very slow and newer APIs can take many minutes to start up.
(2) Emulators like Honeycomb and Ice Cream Sandwich do more and so use more resources, therefore on older PCs don’t run non-essential background apps or the emulator might crawl to a halt.
(3) Some of the newer emulators may occasionally crash or freeze during startup but just try again.
(4) Emulator graphics can be very slow but are still very useful in setting up a game or apps screen layout.
(5) If you need to test your game but don’t have an Android device then use older emulators as they will draw more frames/second, run your code faster and be more responsive.
(6) Emulator keyboards can be problematic so use at least one Android device to check its behaviour.
(7) When creating an emulator ignore the density setting as HAC copes automatically with screen scaling.
(8) Test your app on a range of Android emulators.

 
Leave a comment

Posted by on 07/02/2012 in How-to

 

4: How To: Background Multi-tasking Apps

Its such a simple need, you want your app to keep running in the background while the user is sending a text message or playing a game. This behaviour is called background multi-tasking but it can be a big problem for smart-phone software developers

How can running background apps be such a big deal when our desktop/laptop computers run as many apps as we need, and we can switch effortlessly between them? Well there must be something important about multi-tasking otherwise there wouldn’t have been such a long running debate between Android and Apple smart-phone supporters over whose operating system is better at multi-tasking. The truth is that developing apps for smart-phones is very different to developing them for desktop computers because smart-phones currently have very limited computing resources compared to a typical desk-top or lap-top computer. Below is some brief information about developing multi-tasking apps on Android and how HAC makes it easier for the developer.

The Problem of Background Multi-tasking
With modern desktop/laptop computers a user will often have several apps ‘running’ simultaneously and the app developers generally didn’t have to consider what would happen if a user sent their app to the background when switching to another app. The reason desktop developers have an easier time is because the desktop operating system has enough memory(RAM and disk space) to keep all  apps active at once. Contrast the situation on smart-phones which generally have far slower processors and far less memory than typical home computers. As the first smart-phones had such limited computing resources and limited battery life the operating systems often had to  shut down non-essential apps in order to keep the foreground app running. This has traditionally made it much harder for developers to port or write an app for a smartphone because their design must take into account that the app could be shutdown at anytime.

Consider an Android smart-phone and what happens if a user has your app in the foreground but then decides to use another app, perhaps they want to send a text message or play their chess game. Your app is sent to the background and depending upon its design may be deactivated in which case when brought back to the foreground the Android OS will reload it and assume your app has restored its own state.

Android OS distinguishes between Activities and Services. Activities are what the app user interacts with, the screen for instance, and when the app is sent to the background its activity can be deactivated or effectively removed from memory by the operating system. Therefore the app developer must ensure their app’s activity can handle being forcibly removed from memory and restore its previous state when reactivated again. Services by contrast are intended to run continuously and can remain active even when their app’s activity is in the background and has been deactivated.

HAC Apps and Background Multi-tasking
All HAC apps have two components, an Activity and a Service. The activity is the screen(card) that the user will see and interact with, and which the operating system can shut down when the app is pushed to the background. The service is the engine of a HAC app and runs continuously, ready to execute instructions or respond to events, and the operating system will try to keep it running. Usually the engine will be idling and waiting for events to occur such as when the user clicks a button, the GPS system sends new location data or a timer kicks in and request some action. The engine is the core of a HAC app because it holds the apps memory and ensures the app can do whatever the user needs without interruption from other activities such as text messaging, alarm clocks etc.

How to Create your multi-tasking HAC App
When it to comes to creating background apps HAC developers have a much easier time than most other Android software developers because HAC apps can naturally keep running in the background and require no extra coding to get them to multi-task or to restore their state. Developers just have to ensure the app works well in the foreground, and while in the background doesn’t use unnecessary resources. As HAC apps know when they are in the background the developer can switch off screen drawing or get their app to idle if need be. Note, HAC apps can still update their screen while in the background so that when brought to the foreground again their screen is up-to-date. To sum up, developers use the HAC desktop designer to create the user interface(activity) and add their scripts(service) using the Script Editor.

Performance
As HAC apps are able to run continuously in the background it would therefore be helpful to know just how much they affect the Android device’s performance. We carried out a series of tests on an older model of Android phone, a HTC G1, as this would highlight any performance issues due to its relatively low processor speed and memory capacity as compared to newer Android smart-phones.

We did four tests, firstly to see how much CPU and RAM was being used when idling. Then three tests using HAC demo projects that placed an increasing load on the system. In order of increasing load they were, Hello World, GPS Satellite, and Lunar Lander.

Between tests the G1 was switched off to reset it and clear its memory so that all tests were equal. Note, except for the Lunar Lander test, the app screen shots were taken after all the tests were run. Below, as well as the stats, there is also a screen shot of each app as it appears when in the foreground.

To measure performance we used an app called SystemPanel App/Task Manager by NextApp Inc. They also have a lite version on Android MarketPlace. Please note that these test results are only approximate but they do give an indication of how much each app loaded the system.

1 – Idling Performance
The picture below shows the G1 after it had been switched on and was running with no other apps loaded except SystemPanel. The CPU usage is about 5.3% and RAM usage at 27M average.

Android G1 idle

2 – Hello World Performance
The Hello World app uses very few resources and so is a good indicator of how much overhead an empty HAC built Android app has.The pictures below shows the G1 after it had been switched on and only SystemPanel and Hello World were running. The Hello World CPU usage was about 4.6% and effective RAM usage was about 11.1M.

Hello World screen shot

Hello World Overview

Hello Worlds Overview

Hello World Stats

Hello World stats

3 – GPS Satellite Performance
The GPS Satellite app might be expected to use lots of resources when running in the background and actively acquiring GPS satellite data. During the tests it made fix requests every second or so and made about 140 requests in total with most of them being mad when the app was in the background. Note, the app wasn’t sent to the background until satellites were located and fix readings were coming in. The pictures below shows the G1 after it had been switched on and only SystemPanel and GPS Satellite app were running. GPS Satellite app CPU usage was about 10.2% and effective RAM usage was about 12.1M.

GPS screen shot

GPS Overview

GPS Overview

GPS Stats

GPS Stats

4 – Lunar Lander Performance
The Lunar Lander game would be expected to use lots of resources when running in the background and especially use lots of CPU time. The pictures below shows the G1 after it had been switched on and only SystemPanel and Lunar Lander game were running. Two tests were made with the first sending Lunar Lander to the back after a game had finished in which case the CPU usage was about 10.3% and effective RAM usage was about 13.1M. In the second test Lunar Lander was sent to the back after a game had just started in which case the CPU usage was about 19.0% and effective RAM usage was about 14.6M.

The Lunar Lander game

Lunar Lander screen shot

Lunar Lander Overview

Lunar Lander Overview

Lunar Lander Stats Game Over

Lunar Lander Stats

Lunar Lander Game Running

Lunar Lander Stats Game Running

Final Thoughts
Actual numbers are very important for both design and comparison purposes. The tests showed that the CPU usage on an Android G1 smart phone for the Hello World, GPS Satellite, and Lunar Lander game were 4.6%, 10.2% and 19.0% respectively. As the Hello World app effectively sits there doing nothing and uses only 4.6% CPU usage on an old device then most HAC apps while idling should use far less on a modern Android device, that is unless they are very active such as when doing number crunching, drawing graphics, acquiring GPS data etc.

Thankfully for HAC users creating multi-tasking background apps is quite easy and as long as they follow sensible guidelines their apps will place little load on the device. With the newer and more powerful Android smart phones and tablets the ability of devices to run background apps is now no big deal. If you are concerned your users might not like your app running in the background then just tell them your app has the Menu Quit option so they can really quit it.

 
Leave a comment

Posted by on 10/01/2012 in How-to

 

3 How to: Making a Splash Screen

Most apps have a splash screen that loads before the app’s working screens and the splash screen can be used to describe the app, show an advert or just look cool. The splash screen can also serve as an About Box that shows whether the user has registered the app or not.

This post will show how to create a splash screen like the one below that will be visible for 10 seconds or the user can skip by touching the onscreen okay button.
Splashscreen on Android G1

A

Screens and Cards
Before creating our splash screen here is a brief overview about screens in HAC apps.

We use the terminology card to describe a screen in a HAC app. A HAC app is like a deck of playing cards with each card having its own set of controls. Only one card may be visible at a time and the app can move between cards using one of several types of GotoCard command.

The programmer doesn’t have to worry about displaying the controls as they are defined when you create your card inside the HAC designer. Furthermore the card size can be adjusted to automatically fit the screen so the programmer doesn’t have to worry about scaling etc.

The first card in any HAC app is called the Home Card (card 1) and as it always loads first it makes sense to use this card as your splash screen. As the app loads it is possible to immediately jump to another card but more on this later.

BR

Splash Screen
This splash screen will be on the Home Card and will lead to a second card that implements your app’s functionality. At any time the user can return back to the splash screen using a menu option.

Its a good idea when making a new project to create at least two cards, your Home Card splash screen and the second card for content.

1. Create a new project and give it a name you like.

Use the File menu and option New.

Create a new project

BR

2. Create a second card using the New Card button on the toolbar.

Creating a second card

3. Naming a card

You don’t have to rename a card but if your app has more than two cards it easier to recognise them in the toolbar card list. The picture above shows where a card’s name can be changed.

4. Filling in the Splash Screen

Add the command to preload the backdrop image by opening the Script Editor and in the MainCode’s Start Up section add the following command:-

CardLoadImage(1,'Local:splash.jpg',1)

The backdrop image is just an old one from the HyperNext Neural Network analyser project and the CardLoadImage command stretches it to fit the screen. Note, it needs to be placed in the project’s Local folder.
Splashscreen backdrop image

A

To add a text to a card just use a Text control and fill in it’s text value with something like “Our Simple SplashScreen”


To add a button to a card just use a Button control. Set the button’s text value to something like “Okay” and from the toolbar set its Goto target to card 2.

Adding a timer to  a card is similar to adding any other control, just select the timer from the Toolbar, use the New Timer button, then click on the card to place it.

This timer causes the app to go to the second card and in order to do this it needs some code. The code is simple, just one command, “GotoCard 2”. With the timer selected open its script and add this command to it:-


GotoCard 2

By default when a timer is created it will be in the off state. To activate a timer the TimerSetMode command is used. We need the timer to start counting when the home card opens so the TimerSetMode command should be placed in the card’s handler script. To do this, select the card and open its script then enter this command into it:-


TimerSetMode(1,1,10000)

5. Second Card
Just add some text or even leave it blank.

6. Menu option
We now need to modify the default About menu option so that it jumps to the home card. Open the Menu Designer and it should appear as in the image below. Next, select the About item, its in the yellow box, then click the About item as highlighted in blue, then open the Script Editor  using “Edit Script” button and enter the GotoCard command:-


GotoCard 1

Now close the Script Editor and the project should be ready to run or build.

MenuDesigner

BR

Running the Splash Screen Project
The picture below shows the built app running on an Android G1 phone:

Splashscreen on Android G1

BR

Overriding the Splash Screen
Some apps such as a file utility might not need the splash screen to show at startup as it could irritate the users. In that case you could either put your splash screen on a later card and let the Home Card contain the functionality or else have a GotoCard in the Home Card’s open handler so the splash screen flies by.

BR

Roundup
By now you should have an idea for making a splash screen for your app. Get into the habit of leaving the Home card free for use as a splash screen. Some apps don’t need a splash screen so in that case you could use one of the later cards for  info about your app. The complete project is available here: Splashscreen.zip

 
Leave a comment

Posted by on 22/12/2011 in How-to

 

2 HowTo: GPS Android App

The GPS functionality now available in HAC apps allows a location determining app to be built that can run continuously either in the foreground or background. The ability of HAC apps to run continuously in the background makes developing such a GPS app quite easy. All it needs is an Android device with either GPS hardware or access to a mobile network that can provide location data.
This post gives a basic overview of GPS location finding and shows the major parts of making your own GPS app with HAC. Fuller details are in the GPS example project included with the HAC installer. There is also both a project and a ready built demo of the GPS app on our Projects web page. The GPS demo app can be installed on an Android device from this link:-
http://www.hypernextandroid.com/binaries/apks/GPS%20Satellite.apk

GPS and Locations
Location finding refers to determining one’s latitude and longitude and is usually simply referred to as GPS.  There are two forms of location finding, GPS using satellites and Assisted GPS where the location information comes from a Mobile Network.
Satellite GPS is much more accurate than Mobile Network assisted GPS and if several satellites are in view then a fix can be accurate down to a few metres. It takes 3 satellites to give a fix for latitude longitude but 4 satellites to give an altitude fix. However, there are a number of drawbacks with satellite GPS. It can take several minutes to give the first fix and also if the sky is obscured by buildings or rock then the device may fail to see a satellite.
Mobile network or assisted GPS is fast and can usually work indoors. Its drawbacks include network charges plus low accuracy, perhaps few hundred meters, depending upon the location of the mobile network towers.

GPS Usage
There are three main steps in getting location information, Firstly to specify the location provider, GPS or Mobile Network. Secondly to specify when location events should be available. Thirdly responding when a location event occurs and processing the information provided.

GPS Demo
The demo included with HAC and on our website has three screens, for Network, GPS, and both Network GPS. Below is a screenshot of it running on an Android G1 phone. The green text is a count of how many fixes it has received.
.
GPS screenshot on Android G1
.
Scripting GPS Demo
As mentioned above there are three steps to acquiring location data and shortened versions of the scripts are shown below. The card displays location values of accuracy, latitude, longitude, altitude and speed using five text controls as shown in the above screenshot. The three scripts are:

1) Specify the location providers, here using both Network and Satellite.
Location Providers

2) Start the location service and request it send update at least very 10000mS and change of 1m.
null

3) Respond to a GPS data event and process it. The event values indicating a fix is available are 4 for first fix, 5 for location changed and 6 for time changed. This script resides in the GPS event hander.
GPS events

Conclusions
It is quite easy to make a basic GPS app with HAC as it provides all the basic functionality required. It also provides functions for converting from numeric values of latitude & longitude to degree, minute and second values, plus functions for handling bearings from one location to another.
The best way to understand how this all fits together is to run the GPS project and play around with it. You can also test it to see if the app can truly work while in the background – once you have installed the GPS app, started it and have some location data returning then send it to the back for a while and then later look at the green fix count – it should have increased.
The GPS app demo is here:-http://www.hypernextandroid.com/binaries/apks/GPS%20Satellite.apk
A word of caution though as not all Android devices are equal and the results can depend upon the device hardware and your mobile network.

 
Leave a comment

Posted by on 20/12/2011 in How-to

 

1 How to: Making Android Apps

This is the start of a series on making Android apps using HAC. It helps if you have already run HAC and have tried to make the Hello World program described here:-
http://www.hypernextandroid.com/hnfiles/progfirst.html

Here is a video http://www.youtube.com/watch?v=lPDb0VcKF1U

However if you are very new to HAC then the links on our HAC website are a good place to start as they cover Installing HAC and building the Hello World program. Writing your first program is very important to understanding this series because it makes you use the HAC designer, introduces you to the layout of a typical HAC android app and gets you to run it on an Emulator or Android device.

Note, if you come here after writing apps in Java and using the Android SDK then you might get a suprise as we don’t cover any of that low-level stuff here because HAC users don’t need to know it. HAC and its screen designer wraps most of that up into simple commands so allowing users to be more productive. HAC doesn’t do everything that the Java and Android SDK can offer but its getting better with every release.

Installing HAC
Installing HAC itself takes just a few minutes but the prerequisite helper programs can take an hour to download with most of the time being spent by the Android SDK updating itself.
The install steps are very simple and are described here:-
http://www.hypernextandroid.com/hnfiles/proginstall.html

HAC Help
There is quite a bit of info around on HAC and its HyperNext programming language. We have two forums covering different aspects of HyperNext. Our HyperNext Studio forum covers using the HyperNext Language and building apps for both Windows and OS X desktop PCs. Our HAC forums are aimed at developings apps for Android devices.  The core HyperNext programming language is almost identical across the various platforms so if you can’t find your answer in one forum it might be in the other.

1. HAC Built in help
HAC comes with built in help that is available from the Guide Menu and Overview option:-Help Memu

2. Help PDF
This is a PDF version of HAC’s built in help and can be searched.
http://www.hypernextandroid.com/binaries/HAC_help.pdf

3. Quickstart PDF
The Quickstart PDF is really meant for HyperNext Studio users but still has a lot in common with HAC.
http://www.tigabyte.com/docs/QuickStart.pdf

4. Language Reference PDF
The Language Reference PDF is meant for HyperNext Studio users but much of the content also applies to HAC programs.
http://www.tigabyte.com/docs/LanguageReference.pdf

Hello World Program
This describes how to create an Hello World program and also has a link to our YouTube Hello World video:-
http://www.hypernextandroid.com/hnfiles/progfirst.html

If you haven’t already done so then please try this because then you will see how easy it is to create an Android app with HAC.

 
3 Comments

Posted by on 19/09/2011 in HAC, How-to